NumPy ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all() [英] NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

查看:105
本文介绍了NumPy ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在NumPy中计算矩阵的特征向量和特征值,只是想通过assert()检查结果.这会抛出一个我不太了解的ValueError,因为打印这些比较效果很好.我有什么技巧可以使此assert()工作?

I was calculating eigenvectors and eigenvalues of a matrix in NumPy and just wanted to check the results via assert(). This would throw a ValueError that I don't quite understand, since printing those comparisons works just fine. Any tips how I could get this assert() working?

import numpy as np
A = np.array([[3,5,0], [5,7,12], [0,12,5]])
eig_val, eig_vec = np.linalg.eig(A)
print('eigenvalue:', eig_val)
print('eigenvector:', eig_vec)

for col in range(A.shape[0]):
    assert( (A.dot(eig_vec[:,col])) == (eig_val[col] * eig_vec[:,col]) )

推荐答案

正如所说的那样,它是模棱两可的.您的数组比较返回一个布尔数组.方法any()和all()减少数组中的值(逻辑或或逻辑和).而且,您可能不想检查是否相等.您应该将条件替换为:

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

这篇关于NumPy ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆