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))
网友评论