pytorch:无法加载 CNN 模型并进行预测 TypeError:“collections.OrderedDict”对象不可调用

2023-12-21

我使用 MNIST 数据集训练了一个 CNN 模型,现在想要预测图像的分类,其中包含数字 3。

但是当我尝试使用这个 CNN 进行预测时,pytorch 给了我这个错误:

TypeError: 'collections.OrderedDict' object is not callable

这是我写的:

cnn = torch.load("/usr/prakt/w153/Desktop/score_detector.pkl")
img = scipy.ndimage.imread("/usr/prakt/w153/Desktop/resize_num_three.png")
test_x = Variable(torch.unsqueeze(torch.FloatTensor(img), dim=1), volatile=True).type(torch.FloatTensor).cuda()
test_output, last_layer = cnn(test_x)
pred = torch.max(test_output, 1)[1].cuda().data.squeeze()
print(pred)

这是一些解释:img为待预测图像,尺寸为28*28score_detector.pkl是经过训练的CNN模型

任何帮助将不胜感激!


事实上,您正在加载 state_dict 而不是模型本身。

保存模型如下:

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

而要加载模型状态,您首先需要初始化模型,然后加载状态

model = Model()
model.load_state_dict(torch.load('model_state.pth'))

如果您在 GPU 上训练模型,但想在没有 CUDA 的笔记本电脑上加载模型,那么您需要再添加一个参数

model.load_state_dict(torch.load('model_state.pth', map_location='cpu'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pytorch:无法加载 CNN 模型并进行预测 TypeError:“collections.OrderedDict”对象不可调用 的相关文章