Removing the last layers loses the name of the others layers

Hi
I have this model


And I got rid of the layers in red.
like this

removed = list(model.children())[:-2]
model = nn.Sequential(*removed)
print(model)

But ends up losing the name of my layer

Is there any thing I can do to keep the name of the layers. Because I might refers to them latters

I have the same issue. Is there a way to keep the names of the layers? I am removing the first layer of ResNet and substituting it with another one, but then all the other layer’s names are numbered.

self.backbone = models.resnet50(pretrained=False)
first_layer = torch.nn.Conv2d(12, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
self.backbone = torch.nn.Sequential(first_layer, *list(self.backbone.named_children())[1:])

I managed to get it working with the following:

self.backbone = models.resnet50(pretrained=False)
first_layer = torch.nn.Conv2d(12, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
self.backbone2 = nn.Sequential()
self.backbone2.add_module(name="conv1", module=first_layer)
[self.backbone2.add_module(name, child) for name, child in self.backbone.named_children() if name != "conv1"]
self.backbone = self.backbone2

nn.Sequential() has a add_module() function that takes a name and the module as parameter which we can use to get the same names as the original architecture.

Hope that helps (after 2 years) :smiley:

2 Likes

Thank you so much! I got my problem fixed very fast!