如何使用 Pytorch 创建自定义的 EfficientNet,最后一层写对了

How to use Pytorch to create a custom EfficientNet with the last layer written correctly

我有一个 class化问题来预测 8 classes 例如,我在 here 的 pytorch 中使用 EfficientNetB3。但是,我对我的自定义 class 是否正确编写感到困惑。我想我想去掉预训练模型的最后一层以适应 8 个输出,对吗?我做对了吗?因为当我在 DataLoader 中打印 y_preds = model(images) 时,它似乎给我 1536 预测。这是预期的行为吗?

!pip install geffnet 
import geffnet

class EfficientNet(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.model = geffnet.create_model(config.effnet, pretrained=True)
        n_features = self.model.classifier.in_features
        # does the name fc matter?
        self.fc = nn.Linear(n_features, config.num_classes)
        self.model.classifier = nn.Identity()
        
    def extract(self, x):
        x = self.model(x)
        return x

    def forward(self, x):
        x = self.extract(x).squeeze(-1).squeeze(-1)
        return x
    
model = EfficientNet(config=config)
if torch.cuda.is_available():
    model.cuda()

打印示例代码y_pred:

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

for step, (images, labels) in enumerate(sample_loader):
    images = images.to(device)
    labels = labels.to(device)
    batch_size = images.shape[0]        
    y_preds = model(images)
    print('The predictions of the 4 images is as follows\n', y_preds)
    break

你甚至没有在前向传球中使用 self.fc

要么直接介绍为:

def forward(self, x):
    ....
    x = extract(x)...
    x = fc(x)
    return x

或者您可以简单地替换名为 classifier 的层(这样您就不需要身份层):

self.model.classifier = nn.Linear(n_features, config.num_classes)

还有,这里的config.num_classes应该是8。