You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch中修改EfficientNet预训练模型最后分类层(类别数从1000调整为4)时的属性错误求助

Fixing EfficientNet Classifier Layer Modification in PyTorch

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_pytorch implementation, the pre-trained model's final linear layer is stored as _fc, so we use model._fc.in_features to get the number of input features for our new layer.
  • We then replace the existing _fc layer with our new linear layer that outputs 4 classes, just like you did with ResNet's fc layer.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:27:34