在Pytorch中微调预训练的模型MobileNet_V2

时间:2019-07-31 07:16:04

标签: deep-learning classification pytorch pre-trained-model mobilenet

我是pyTorch的新手,我正在尝试创建一个分类器,其中有大约10种Images Folders数据集,对于此任务,我使用的是Pretrained模型(MobileNet_v2),但问题是我无法更改FC一层。没有model.fc属性。 谁能帮我做到这一点。 谢谢

3 个答案:

答案 0 :(得分:2)

执行以下操作:

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)

输出:

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

注意:您需要torch >= 1.1.0才能使用torch.hub

答案 1 :(得分:1)

MobileNet V2 source code看来,该模型最后具有一个称为分类器的顺序模型。因此,您应该能够像这样更改分类器的最后一层:

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

很遗憾,我现在无法测试此代码。
对于如何微调模型,This也是很好的参考。

答案 2 :(得分:0)

MobilenetV2实现要求输入num_classes(默认为1000),并提供self.classifier作为属性,它是torch.nn.Linear层,其输出尺寸为num_classes。您可以使用此属性进行微调。您可以自己查看code,以更好地理解。 import torch.nn as nn import torchvision.models as models model = models.mobilnet_v2(num_classes=10)

相关问题