在 Pytorch 中微调预训练模型 MobileNet_V2

Sac*_*rma 5 classification deep-learning pre-trained-model pytorch mobilenet

我是 pyTorch 的新手,我正在尝试创建一个分类器,其中我有大约 10 种图像文件夹数据集,为此我使用的是预训练模型(MobileNet_v2),但问题是我无法更改它的 FC 层. 没有model.fc 属性。谁能帮我做到这一点。谢谢

chr*_*n0x 5

MobileNet V2 源代码来看,这个模型最终有一个称为分类器的序列模型。因此,您应该能够像这样更改分类器的最后一层:

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

不幸的是,我现在无法测试此代码。
也是一个很好的参考,关于如何微调模型。

  • @AnubhavSingh,实际上自从最近的 torchvision 更新以来确实如此。https://pytorch.org/docs/stable/torchvision/models.html (2认同)

Anu*_*ngh 5

执行以下操作:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

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)
)
Run Code Online (Sandbox Code Playgroud)

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