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

标签 python tensorflow pytorch

我使用 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*28 score_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'))

关于python - pytorch:无法加载 CNN 模型并进行预测 TypeError: 'collections.OrderedDict' 对象不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48419626/

相关文章:

tensorflow - ResNet34 - 使用 tensorflow 在 imagenet 上预训练模型

python - 在 Keras Tensorflow 中将 TimeseriesGenerator 与多元数据集结合使用

python - 为什么 PyTorch 找不到我的 NVIDIA 驱动程序来支持 CUDA?

python - 迭代 torch 张量

python - 删除 Torch 张量中的行

javascript - 为什么我的 WebSocket 使用 Flask 自动关闭?

python - win32gui.SetActiveWindow() 错误 : The specified procedure could not be found

python - 如何在 Python pandas DataFrame 中对列值进行切片

python - Firefox:编译错误 "' ascii' 编解码器无法编码字符”

docker - 动态决定要在哪个GPU上运行-NVIDIA docker上的TF