PyTorch中修改EfficientNet预训练模型最后分类层(类别数从1000调整为4)时的属性错误求助
Hey there! The issue you're running into comes down to a small difference in how the efficientnet_pytorch library structures its model compared to torchvision's ResNet implementations. Let's break this down and fix your code.
What's Going Wrong
In your current code, you're trying to access model.classifier.in_features to get the input dimension for your new linear layer—but the EfficientNet class from the efficientnet_pytorch library doesn't have a classifier attribute. Instead, its final classification layer is named _fc. That's why you're getting the "has no attribute 'classifier'" error.
On top of that, you have an extra pair of asterisks (**) around out_features=Config.NUM_CLASSES which will cause a syntax error—we'll fix that too.
Corrected Code
Here's the adjusted code that should work perfectly for your 4-class classification task:
elif Config.MODEL_NAME == 'efficientnet-b3': from efficientnet_pytorch import EfficientNet model = EfficientNet.from_pretrained('efficientnet-b3') # Access the correct attribute for input features, and fix the syntax issue model._fc = torch.nn.Linear( in_features=model._fc.in_features, out_features=Config.NUM_CLASSES, bias=True )
Why This Works
- For the
efficientnet_pytorchimplementation, the pre-trained model's final linear layer is stored as_fc, so we usemodel._fc.in_featuresto get the number of input features for our new layer. - We then replace the existing
_fclayer with our new linear layer that outputs 4 classes, just like you did with ResNet'sfclayer.
Quick Comparison to ResNet
Torchvision's ResNet models (like resnet18, resnet50) use fc as the name for their final classification layer, which is why your ResNet code works without issues. Different model implementations often use slightly different naming conventions for their layers, so it's always a good idea to check the model's structure if you run into attribute errors.
内容的提问来源于stack exchange,提问作者FarnooshAzour

