【问题标题】:Pytorch: AttributeError: 'function' object has no attribute 'copy'Pytorch:AttributeError:'function'对象没有属性'copy'
【发布时间】:2020-07-29 06:18:54
【问题描述】:

我正在尝试加载我在 Google Colab GPU 上训练的模型 state_dict,这是我加载模型的代码:

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

model = models.resnet50()
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, n_classes)
model.load_state_dict(copy.deepcopy(torch.load("./models/model.pth",device)))
model = model.to(device)
model.eval()

这是错误:

state_dict = state_dict.copy()

AttributeError: 'function' 对象没有属性 'copy'

火炬:

>>> import torch
>>> print (torch.__version__)
1.4.0
>>> import torchvision
>>> print (torchvision.__version__)
0.5.0

请帮忙,我到处找都没用

[完整错误详情][1]https://i.stack.imgur.com/s22DL.png

【问题讨论】:

    标签: python deep-learning pytorch torch


    【解决方案1】:

    我猜这是你做错了。 你保存了函数

    torch.save(model.state_dict, 'model_state.pth')

    而不是 state_dict()

    torch.save(model.state_dict(), 'model_state.pth')

    否则,一切都应该按预期工作。 (我在 Colab 上测试了以下代码)

    model.state_dict() 替换为model.state_dict 以重现错误

    import copy
    model = TheModelClass()
    torch.save(model.state_dict(), 'model_state.pth')
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model.load_state_dict(copy.deepcopy(torch.load("model_state.pth",device)))
    

    【讨论】:

      猜你喜欢
      • 2020-05-21
      • 2019-08-13
      • 2016-03-17
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2017-07-07
      • 2016-03-10
      相关资源
      最近更新 更多