How can I add simple modification for the forward method of ResNet50?

Hi all,

How can I add one statement to the forward method before the FC layer?

I can achieve this if I’ve defined my own CNN model, but I am unsure how to do it with a pre-trained model (e.g., ResNet50).

class CNN(nn.Module):
    """CNN."""
    def __init__(self):
        """CNN Builder."""
        super(CNN, self).__init__()
       
        self.newLayer = newLayer(s, True)
        
        self.conv_layer = nn.Sequential(

            ...
            ...
            ...
            
        )

        self.fc_layer = nn.Sequential(
            ...
            ...
            ...
        )

    def forward(self, x):
        # conv layers
        x = self.conv_layer(x)
        
        x = self.newLayer(x)
        
        # flatten
        x = x.view(x.size(0), -1)
        
        # fc layer
        x = self.fc_layer(x)

        return x

When I checked the source code for Resnet50, I found two links, I am not sure about the correct approach:
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/torchvision_models.py

My attempt:

class MyResNet50(ResNet):
    def __init__(self):
        super(MyResNet50, self).__init__(BasicBlock, [3, 4, 6, 3])
        self.newLayer = newLayer(s, True)

    def forward(self, input):
        x = self.features(input)

         x = self.newLayer(x)

        x = self.logits(x)
        return x
model = MyResNet50()
#load pretrained weights
model.load_state_dict(models.resnet50(pretrained=True).state_dict())

The error:
RuntimeError: Error(s) in loading state_dict for MyResNet50:
Unexpected key(s) in state_dict:

I’ve done it by following instructions in this post: How can I replace the forward method of a predefined torchvision model with my customized forward function? - #8 by Shisho_Sama