作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 here 中的代码训练模型来预测从 0
到 9
的打印样式编号:
idx_to_class = {0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7:"7", 8: "8", 9:"9"}
def predict(model, test_image_name):
transform = image_transforms['test']
test_image = Image.open(test_image_name)
plt.imshow(test_image)
test_image_tensor = transform(test_image)
if torch.cuda.is_available():
test_image_tensor = test_image_tensor.view(1, 3, 224, 224).cuda()
else:
test_image_tensor = test_image_tensor.view(1, 3, 224, 224)
with torch.no_grad():
model.eval()
# Model outputs log probabilities
out = model(test_image_tensor)
ps = torch.exp(out)
topk, topclass = ps.topk(1, dim=1)
# print(topclass.cpu().numpy()[0][0])
print("Image class: ", idx_to_class[topclass.cpu().numpy()[0][0]])
predict(model, "path_of_test_image")
但是当我尝试使用预测
时出现错误:
Traceback (most recent call last):
File "<ipython-input-12-f8636d3ba083>", line 26, in <module>
predict(model, "/home/x/文档/Deep_Learning/pytorch/MNIST/test/2/QQ截图20191022093955.png")
File "<ipython-input-12-f8636d3ba083>", line 9, in predict
test_image_tensor = transform(test_image)
File "/home/x/.local/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 61, in __call__
img = t(img)
File "/home/x/.local/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 166, in __call__
return F.normalize(tensor, self.mean, self.std, self.inplace)
File "/home/x/.local/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 217, in normalize
tensor.sub_(mean[:, None, None]).div_(std[:, None, None])
RuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0
我该如何解决这个问题?谢谢。
最佳答案
我怀疑您的 test_image
每个像素都有一个额外的 Alpha channel ,因此它有 4 个 channel ,而不是只有 3 个。
尝试:
test_image = Image.open(test_image_name).convert('RGB')
关于python - Pytorch运行时错误: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58496858/
我是一名优秀的程序员,十分优秀!