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?
I think you would have to look into your
resnet architecture, right?
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) self.layer2 = self._make_layer(block, 128, layers, stride=2, dilate=replace_stride_with_dilation) self.layer3 = self._make_layer(block, 256, layers, stride=2, dilate=replace_stride_with_dilation) self.layer4 = self._make_layer(block, 512, layers, stride=2, dilate=replace_stride_with_dilation) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes)
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
@Giuseppe I use your code to replace the avgpool layer and fc layer with nn.Indentity(), but the output still be a vector.
The vector is feature map. It is right!