我正在尝试加载模型 state_dict
我在 Google Colab GPU 上训练过,这是我加载模型的代码:
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' object has no attribute 'copy'
火炬:
>>> import torch
>>> print (torch.__version__)
1.4.0
>>> import torchvision
>>> print (torchvision.__version__)
0.5.0
请帮助我到处搜索都无济于事
[完整的错误详情][1] /image/s22DL.png
最佳答案
我猜这是你做错了什么。
你保存了函数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)))
关于python - Pytorch: AttributeError: 'function' 对象没有属性 'copy',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61242966/