How can extract the Features map of ResNet 50

Hy guys, how can I extract the features in a resnet50 before the general average pooling? I need the image of 7x7x2048. If I put the FC in an nn.Identity in forward I only obtain the features vector. I need the image before the final pooling. How can I make?

You can get the output of any layer of a model by doing model.layer_name(input). This will give you the output of whatever layer you want, assuming that your input is correct.

Do you know the layer_name that I need? :sweat_smile:

I think you would have to look into your resnet architecture, right? :thinking:

I think that will be the self.layer4, ResNet’s code here:

        self.bn1 = norm_layer(self.inplanes)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       dilate=replace_stride_with_dilation[0])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       dilate=replace_stride_with_dilation[1])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       dilate=replace_stride_with_dilation[2])
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)

Many thanks :slight_smile:

1 Like

I solved with:

model = torchvision.models.resnet50()
model.avgpool = nn.Identity()
model.fc = nn.Identity()

I abilitate model.eval(). it went only in forward to obtain what i wanted.
it is solved

1 Like

@Giuseppe I use your code to replace the avgpool layer and fc layer with nn.Indentity(), but the output still be a vector. :dizzy_face:

The vector is feature map. It is right!