2

I am going through difficulties to understand this code snippet.

import torch
import torch.nn as nn
import torchvision.models as models

def ResNet152(out_features = 10):
      return getattr(models, "resnet152")(pretrained=False, num_classes = out_features)

def VGG(out_features = 10):
      return getattr(models, "vgg19")(pretrained=False, num_classes = out_features)

In this code segment, features for an input image is extracted by ResNet152 and Vgg19 model. But I have the question, from whether which part of these models the features are being extracted whether the part is last pooling layer or the layer before the classification layer or something else.

Rafi
  • 105
  • 2
  • 7

1 Answers1

1

Note that getattr(models, 'resnet152') is equivalent to models.resent152.

Hence, the code below is returning the model itself.

getattr(models, "resnet152")(pretrained=False, num_classes = out_features)
# is same as
models.resnet152(pretrained=False, num_classes = out_features)

Now, if you look at the structure of the model by simply printing it, the last layer is a fully-connected layer, so that is what you're getting as features here.

print(ResNet152())

ResNet(
  (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
...
  (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
  (fc): Linear(in_features=2048, out_features=10, bias=True)
)

The same is the case for VGG().

kHarshit
  • 11,362
  • 10
  • 52
  • 71
  • So, are we actually using the classification layer output as our extracted image features here? – Rafi Jan 26 '22 at 07:11
  • 2
    Yes, you can get features from earlier layers as well. Check https://stackoverflow.com/questions/55083642/extract-features-from-last-hidden-layer-pytorch-resnet18 I'm not sure which code you're following, so can't comment much. – kHarshit Jan 26 '22 at 07:16