具有多个元素的数组的真值不明确

数据挖掘 机器学习 麻木的
2022-03-13 03:28:43

我试图打印概率数组的每个最大概率的索引,在执行以下代码时出现错误

" 具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()"

for prob_ in prob:
        max_prob=max(prob_)
        index=clf.classes_[prob.index(max(prob_))]

其中 prob 是一个数组

1个回答

我的代码中有同样的问题:

c = max(
[np.dot(theta[j], X[i]) for j in range(theta.shape[0])]
) / temp_parameter

我运行调试器并发现它们theta[j], X[i]的形状不同,因此点积给出了一个 ndarray 而不是标量。max()函数对此有点困惑,因为它不适用于 ndarrays。所以,结论是:

  • 如果prob_是 ndarray,请使用numpy.max(),它肯定可以工作:

    [In]: f = np.array([[1, 1, 1], [2, 2, 2]]) [In]: max(f) [Out]: Traceback (most recent call last): File "<input>", line 1, in <module> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() [In]: np.max(f) [Out]: 2

  • 如果prob_是一个列表,检查它的组件是标量还是列表:

    [In]: f = [[1, 1, 1], [2, 2, 2]] [In]: max(f) [Out]: [2, 2, 2] [In]: g = [numpy.array([1, 1, 1]), numpy.array([2, 2, 2])] [In]: max(g) [Out]: Traceback (most recent call last): File "<input>", line 1, in <module> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()