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

加载预训练AlexNet模型时遇AttributeError:'dict'无'features'属性求助

Hey, let's fix this error right away! The problem here is that your alexnet_places365.pth.tar file doesn't contain a full PyTorch model instance—it's just a state_dict (a dictionary storing the model's trained parameters). When you call torch.load() on it, you get a dict, not a model with a features attribute, hence the AttributeError.

Here's how to fix it step by step:

  • First, initialize the base AlexNet model structure (the Places365 AlexNet uses the same architecture as the standard AlexNet in torchvision).
  • Load the pretrained weights from the .pth.tar file (which is a dict), then map those weights to your base model.
  • Then you can safely extract the features layers you need.

Revised Full Code

import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.models as models

class AlexSal(nn.Module):
    def __init__(self):
        super(AlexSal, self).__init__()
        # Step 1: Initialize the base AlexNet structure
        base_alexnet = models.alexnet(pretrained=False)
        
        # Step 2: Load the pretrained weights dict and adjust for possible prefixes
        pretrained_weights = torch.load('alexnet_places365.pth.tar')
        # Many Places365 weights are saved with a 'module.' prefix (from distributed training)
        # We need to strip that to match the base model's parameter names
        if 'state_dict' in pretrained_weights:
            weight_dict = pretrained_weights['state_dict']
        else:
            weight_dict = pretrained_weights
        # Remove 'module.' prefix if present
        cleaned_weight_dict = {k.replace('module.', ''): v for k, v in weight_dict.items()}
        
        # Load the cleaned weights into the base model
        base_alexnet.load_state_dict(cleaned_weight_dict)
        
        # Step 3: Extract the first N layers of features (exclude last 2)
        self.features = nn.Sequential(*list(base_alexnet.features.children())[:-2])
        
        # Remaining layers stay the same
        self.relu = nn.ReLU()
        self.sigmoid = nn.Sigmoid()
        self.conv6 = nn.Conv2d(256, 1, kernel_size=(1, 1), stride=(1, 1))

    def forward(self, x):
        x = self.relu(self.features(x))
        x = self.sigmoid(self.conv6(x))
        x = x.squeeze(1)
        return x

model = AlexSal().cuda()

Quick Debug Tip

If you're unsure about the structure of your pretrained file, print its keys first to confirm:

pretrained_weights = torch.load('alexnet_places365.pth.tar')
print(pretrained_weights.keys())

This will tell you if the weights are stored directly in the dict or under a state_dict key, so you can adjust the loading logic accordingly.

This should resolve the AttributeError and let you initialize your AlexSal model correctly.

内容的提问来源于stack exchange,提问作者Mr.Danish Mukhtar Zargar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:55:22