如何在 Pytorch 中的 EfficieNet 预训练模型中添加最后一个分类层?

How to add the last classification layer in EfficieNet pre-trained model in Pytorch?

我在 Pytorch 中为我的 图像分类 项目使用 EfficientNet 预训练模型,我的目的是改变 类 最初是 1000 到 4。 但是,为此,当我尝试添加 model._fc 层时,我一直看到此错误“EfficientNet”对象没有属性“分类器”。这是我的代码 (Config.NUM_CLASSES = 4):

elif Config.MODEL_NAME == 'efficientnet-b3':
      
    from efficientnet_pytorch import EfficientNet
    model = EfficientNet.from_pretrained('efficientnet-b3')
    model._fc= torch.nn.Linear(in_features=model.classifier.in_features, **out_features=Config.NUM_CLASSES**, bias=True)

当我在Resnet部分的末尾添加model._fc时,情况就不同了,它显然将Resnet-18中的输出数类更改为4。这是相关代码:

if Config.MODEL_NAME == 'resnet18': model = models.resnet50(pretrained=True) model.fc = torch.nn.Linear(in_features=model.fc.in_features, out_features=Config.NUM_CLASSES, bias=True)

solution 适用于 TensorFlow 和 Keras,如果有人能在 PyTorch 中帮助我,我将不胜感激。

此致,

EfficentNet class 没有属性 classifier,您需要将 in_features=model.classifier.in_features 更改为 in_features=model._fc.in_features

import torchvision.models as models

NUM_CLASSES = 4

#EfficientNet
from efficientnet_pytorch import EfficientNet
efficientnet = EfficientNet.from_pretrained('efficientnet-b3')
efficientnet ._fc= torch.nn.Linear(in_features=efficientnet._fc.in_features, out_features=NUM_CLASSES, bias=True)

#mobilenet_v2
mobilenet = models.mobilenet_v2(pretrained=True)
mobilenet.classifier = nn.Sequential(nn.Dropout(p=0.2, inplace=False),
                  nn.Linear(in_features=mobilenet.classifier[1].in_features, out_features=NUM_CLASSES, bias=True))

#inception_v3
inception = models.inception_v3(pretrained=True)
inception.fc =  nn.Linear(in_features=inception.fc.in_features, out_features=NUM_CLASSES, bias=True)


Torchvision >= 0.11 包括 EfficientNet,它确实有一个分类器属性。获取 in_features :

import torchvision

model = torchvision.models.efficientnet_b5()
num_ftrs = model.classifier[1].in_features