我使用 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/