我想使用 numpy 来计算逆。但我收到一个错误:
'numpy.ndarry' object has no attribute I
要在 numpy 中计算矩阵的逆矩阵,比如矩阵 M,它应该很简单:
打印M.I
代码如下:
x = numpy.empty((3,3), dtype=int)
for comb in combinations_with_replacement(range(10), 9):
x.flat[:] = comb
print x.I
我猜,这个错误是因为 x 现在是平的,因此 'I
' 命令不兼容。有解决办法吗?
我的目标是打印每个可能的数字矩阵组合的逆矩阵。
最佳答案
I
属性只存在于 matrix
对象上,而不存在于 ndarray
上。您可以使用numpy.linalg.inv
反转数组:
inverse = numpy.linalg.inv(x)
请注意,您生成矩阵的方式并非所有矩阵都是可逆的。您要么需要更改生成矩阵的方式,要么跳过不可逆的矩阵。
try:
inverse = numpy.linalg.inv(x)
except numpy.linalg.LinAlgError:
# Not invertible. Skip this one.
pass
else:
# continue with what you were doing
此外,如果您想遍历所有元素从 [0, 10) 中提取的 3x3 矩阵,您需要以下内容:
for comb in itertools.product(range(10), repeat=9):
而不是 combinations_with_replacement
,否则你会跳过类似的矩阵
numpy.array([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
关于python - 使用 numpy 逆矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21638895/