Finetuning vgg18

in pytorch transfer learning tutorial there is following code:

model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
# Here the size of each output sample is set to 2.
# Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).
model_ft.fc = nn.Linear(num_ftrs, 2)

they removed last fully connected layer, and replaced new one.i still don’t understand how model_ft.fc.in_features works, there is no docs about that.what does model_ft.fc return? last layer?and if model has 5 fully connected layer, what it will return?

You can see the layers via print(model) or have a look at the source code.

You’ll see that, model.fc addresses the last linear layer, so you can just reassign a new layer to this attribute.

Each nn.Linear layer has a weight matrix (and optionally bias), which is defined by the input and output shape of this particular layer. in_features returns the given number of input features for this layer.

1 Like