Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fine Tuning Pretrained Model MobileNet_V2 in Pytorch

I am new to pyTorch and I am trying to Create a Classifier where I have around 10 kinds of Images Folder Dataset, for this task I am using Pretrained model( MobileNet_v2 ) but the problem is I am not able to change the FC layer of it. There is not model.fc attribute. Can anyone help me to do this. Thanks

like image 336
Sachin Sharma Avatar asked Jul 31 '19 07:07

Sachin Sharma


People also ask

What is Num_classes in PyTorch?

The other inputs are as follows: num_classes is the number of classes in the dataset, batch_size is the batch size used for training and may be adjusted according to the capability of your machine, num_epochs is the number of training epochs we want to run, and feature_extract is a boolean that defines if we are ...


Video Answer


2 Answers

From the MobileNet V2 source code it looks like this model has a sequential model called classifier in the end. Therefore, you should be able to change the final layer of the classifier like this:

import torch.nn as nn
import torchvision.models as models
model = models.mobilenet_v2()
model.classifier[1] = nn.Linear(model.last_channel, 10)

Unfortunately, I cannot test this code right now.
This is also a good reference, on how to finetune models.

like image 130
chron0x Avatar answered Sep 24 '22 19:09

chron0x


Do something like below:

import torch
model = torch.hub.load('pytorch/vision', 'mobilenet_v2', pretrained=True)
print(model.classifier)

model.classifier[1] = torch.nn.Linear(in_features=model.classifier[1].in_features, out_features=10)
print(model.classifier)

output:

Sequential(
  (0): Dropout(p=0.2)
  (1): Linear(in_features=1280, out_features=1000, bias=True)
)
Sequential(
  (0): Dropout(p=0.2)
  (1): Linear(in_features=1280, out_features=10, bias=True)
)

Note: you would need torch >= 1.1.0 to use torch.hub.

like image 31
Anubhav Singh Avatar answered Sep 21 '22 19:09

Anubhav Singh