pytorch bug 記錄
RuntimeError: Boolean value of Tensor with more than one value is ambiguous
簡單復現(xiàn)以下錯誤:
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))
加括號原因:位運算符優(yōu)先級高于等于運算符
同理: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))