[英]pytorch: can't load CNN model and do prediction TypeError: 'collections.OrderedDict' object is not callable
I trained a CNN model using MNIST dataset and now want to predict a classification of the image, which contains a number 3. 我使用MNIST数据集训练了CNN模型,现在想预测包含数字3的图像分类。
But when I tried to use this CNN to predict, pytorch gives me this error: 但是,当我尝试使用此CNN进行预测时,pytorch给了我这个错误:
TypeError: 'collections.OrderedDict' object is not callable
And here's what I write: 这是我写的:
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)
here's some explaination: img
is the to be predicted image with size 28*28 score_detector.pkl
is the trained CNN model 这是一些解释:
img
是尺寸为28 * 28的待预测图像score_detector.pkl
是经过训练的CNN模型
any help will be appreciated! 任何帮助将不胜感激!
I'm pretty sure score_detector.pkl
is actually a state_dict and not the model itself. 我很确定
score_detector.pkl
实际上是state_dict而不是模型本身。 You will need to instantiate the model first and then load the state_dict, so your first line should be replaced by something like this: 您将需要首先实例化模型,然后加载state_dict,因此您的第一行应替换为以下内容:
cnn = MyModel()
cnn.load_state_dict("/usr/prakt/w153/Desktop/score_detector.pkl")
and then the rest should work. 然后其余的应该工作。 See this link for more information.
有关更多信息,请参见此链接 。
Indeed, you are loading a state_dict rather than the model itself. 实际上,您是在加载state_dict而不是模型本身。
Saving the model is as follows: 保存模型如下:
torch.save(model.state_dict(), 'model_state.pth')
Whereas to load the model state you first need to init the model and then load the state 而要加载模型状态,您首先需要初始化模型,然后加载状态
model = Model()
model.load_state_dict(torch.load('model_state.pth'))
If you trained your model on GPU but would like to load the model on a laptop which doesn't have CUDA, then you would need to add one more argument 如果您在GPU上训练了模型,但想将模型加载到没有CUDA的笔记本电脑上,那么您需要再添加一个参数
model.load_state_dict(torch.load('model_state.pth', map_location='cpu'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.