Boolean value of Tensor with more than one value is ambiguous

pytorch bug 记录

RuntimeError: Boolean value of Tensor with more than one value is ambiguous
简单复现以下错误:

a = torch.zeros(2)
print(a)  # tensor([0., 0.])
b = torch.ones(2)
print(b)  # tensor([1., 1.])
print(a == b)  # 可以 tensor([False, False])
# print((a == b) or (a != b))  # 报错
# RuntimeError: Boolean value of Tensor with more than one value is ambiguous

原因:and or not逻辑运算符三兄弟只能处理单个变量,没法对张量使用

解决方法:
使用位运算符

print((a == b) | (a != b))

加括号原因:位运算符优先级高于等于运算符

同理:numpy也会有这个问题,解决方式一样

import numpy as np
a = np.zeros(2)
print(a)  # [0. 0.]
b = np.ones(2)
print(b)  # [1. 1.]
print((a == b))  # [False False]
print((a == b) or (a != b))  # 报错
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
print((a == b) | (a != b))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容