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

问题描述 投票:-1回答:1

我正在尝试加载我在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:“函数”对象没有属性“副本”

Pytorch:

>>> 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个回答
0
投票

我猜这是您的错误操作。您保存了功能

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

而不是state_dict()

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

否则,一切都会按预期进行。 (我在Colab上测试了以下代码)

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)))
© www.soinside.com 2019 - 2024. All rights reserved.