python - Pytorch: AttributeError: 'function' 对象没有属性 'copy'

标签 python deep-learning pytorch torch

我正在尝试加载模型 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/

相关文章:

python - 在python中将字符串转换为unicode

python - 将 Pandas 堆积的 DataFrame 转换为 Matrix

python - 在pandas中运行fig = plt.figure()会打开两个数字

machine-learning - 如何在Google Colaboratory上解压.7z文件?

machine-learning - 为什么不训练部分时期呢?

python - 导入pytorch时出现导入错误

gpu - 我们可以在 GPU 上使用 pytorch scatter_

python - Pandas 的合并返回名称后附加了 _x 的列

python - 如何修复 : RuntimeError: size mismatch in pyTorch

pytorch - pytorch 中的 model.cuda()