python - 无效的参数组合 - eq()
问题描述
我正在使用此处共享的代码来测试 CNN 图像分类器。当我调用测试函数时,我在第 155 行得到了这个错误:
test_acc += torch.sum(prediction == labels.data)
TypeError: eq() received an invalid combination of arguments - got (numpy.ndarray), but expected one of:
* (Tensor other)
didn't match because some of the arguments have invalid types: ([31;1mnumpy.ndarray[0m)
* (Number other)
didn't match because some of the arguments have invalid types: ([31;1mnumpy.ndarray[0m)
函数片段test
:
def test():
model.eval()
test_acc = 0.0
for i, (images, labels) in enumerate(test_loader):
if cuda_avail:
images = Variable(images.cuda())
labels = Variable(labels.cuda())
#Predict classes using images from the test set
outputs = model(images)
_,prediction = torch.max(outputs.data, 1)
prediction = prediction.cpu().numpy()
test_acc += torch.sum(prediction == labels.data) #line 155
#Compute the average acc and loss over all 10000 test images
test_acc = test_acc / 10000
return test_acc
快速搜索后,我发现该错误可能与prediction
and之间的比较有关labels
,就像在这个SO question中所显示的那样。
关于如何解决这个问题的任何想法?
解决方案
你为什么在.numpy()
这里prediction = prediction.cpu().numpy()
?这样你就可以将 PyTorch 张量转换为 NumPy 数组,使其与labels.data
.
删除.numpy()
部分应该可以解决问题。
推荐阅读
- swift - SKAction.move(to: ...) 和 SKAction.move(by: ...) 为我做同样的事情
- keras - 矩阵大小不兼容的keras
- python - 考虑到 upload_to() 函数,如何获取 FieldField 的路径
- spring-boot - Spring Boot、Debian、Embedded Tomcat 关闭外部端口
- angular - 在 Ngrx-nx Monorepo 中管理共享样式和资产
- mysql - 创建 MySQL 时出错 ERROR 1067 (42000): 'end' 的默认值无效
- sql-server - ORDER BY 中的字段影响窗口函数的结果
- javascript - 跟踪所有其他对象对每个 javascript 对象的引用的方法?
- javascript - Eslint:Arrays/Objects/Function 元素中的换行符取决于行大小
- python - 用 django 服务器和 GET 一起写的数字有什么意义?