Image Feature Extraction in PyTorch

Viewed 911

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.

1 Answers

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().

Related