学习随笔-ValueError: The truth value of an array with more than one element is ambiguous
程序员文章站
2022-05-27 12:46:36
...
问题:
我的代码是想判断两个nparray是否完全相等,
if prediction[i] == Y_test[i]:
运行时报的错误为:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
原因:
假设存在两个nparray:
a = np.array([1,2,3])
b = np.array([1,3,2])
如果用 == 号判断二者元素是否完全相等:
print a==b
结果为:
[True False False]
可以看出它是对每个应用位置元素进行比较,
相同就返回True,不同就返回False,
所以, 源代码 相当于是:
if [True False False]:
逻辑上就不正确,
按照报错的提示,我们要使用any(), 或者 all(),
假设还是两个nparray如下:
a = np.array([1,2,3])
b = np.array([1,3,2])
运行:
print any(a==b)
print all(a==b)
对应结果为:
True
False
什么意思呢, 其实很简单,
首先 a==b 就是 [True False False]
那么
any([True False False])
表示只要有一个True 就返回 True,
all([True False False])
表示所有元素为True才会返回True, 否则返回False.
结论:
那么要比较两个nparray是否完全相等,
利用all()即可.
reference:
https://*.com/questions/28899920/numpy-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguousanswered by SmCaterpillar
上一篇: [numpy问题]The truth value of an array with more than one element is ambiguous.
下一篇: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or
推荐阅读
-
moviepy AudioClip帧处理ValueError: The truth value of array with more than one element is ambiguous
-
python报错ValueError: The truth value of an array with more than one element is ambiguous. Use a.any()
-
Python报错:The truth value of an array with more than one element is ambiguous
-
Python ValueError: The truth value of an array with more than one element is ambiguous.
-
成功解决Python的ValueError: The truth value of an array with more than one element is ambiguous
-
moviepy AudioClip帧处理ValueError: The truth value of array with more than one element is ambiguous
-
[numpy问题]The truth value of an array with more than one element is ambiguous.
-
学习随笔-ValueError: The truth value of an array with more than one element is ambiguous
-
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or
-
moviepy AudioClip帧处理ValueError: The truth value of array with more than one element is ambiguous