Access/replace layer using its name (string)

I want to access a layer in a model by its name (string) to change it.
In my case, I want to change a layer inside bn_vgg16 model (model.output.fc3)
I didn’t a way to access to the layer via its name or replace it

model = ptcv_get_model('bn_vgg16', pretrained=True)
model.load_state_dict(torch.load('bn_vgg16_vx.pth')
layer_name = 'output.fc3'
###  ###
model.(layer_name ) = nn.Linear(in_features, 5)

I know I can change the last layer easily using:

model = torch.nn.Sequential(*(list(model.children())[:-1]))
model = nn.Sequential(model, nn.Linear(in_features, 5))

but I am interested on accessing any layer by its name

Thank you in advance :slight_smile:

You could try some trick as mentioned here:

1 Like