【发布时间】:2012-08-15 00:36:30
【问题描述】:
我正在研究的科学/工程应用程序有很多线性代数矩阵乘法,因此我使用 Numpy 矩阵。但是,python 中有许多函数可以互换地接受矩阵或数组类型。不错,不是吗?嗯,不是真的。让我用一个例子来说明这个问题:
from scipy.linalg import expm
from numpy import matrix
# Setup input variable as matrix
A = matrix([[ 0, -1.0, 0, 0],
[ 0, 0, 0, 1.0],
[ 0, 0, 0, 0],
[ 0, 0, 1.0, 0]])
# Do some computation with that input
B = expm(A)
b1 = B[0:2, 2:4]
b2 = B[2:4, 2:4].T
# Compute and Print the desired output
print "The innocent but wrong answer:"
print b2 * b1
print "The answer I should get:"
print matrix(b2) * matrix(b1)
运行时会得到:
The innocent but wrong answer:
[[-0.16666667 -0.5 ]
[ 0. 1. ]]
The answer I should get, since I expected everything to still be matrices:
[[ 0.33333333 0.5 ]
[ 0.5 1. ]]
关于如何避免这种混淆的任何提示或建议?在 matrix() 调用中继续包装变量以确保它们仍然是矩阵真的很麻烦。在这方面似乎没有标准,因此可能会导致难以检测的错误。
【问题讨论】:
-
这就是人们使用 Java 和其他静态语言的原因。 IDE 和编译器会因为使用不同的类型而绞尽脑汁(IDE 会告诉你类型)
-
如果你想要点积,最好使用
numpy.dot,而不是依赖于覆盖乘法运算符的矩阵。 Explicit is better than implicit. -
不得不使用 np.dot 真的很烦人,尤其是当你有如下等式时:A = GPG_tran+ MUM_tran
-
@Mehdi,我同意,但是,我发现坚持使用 numpy 数组总体上是一种更好的体验。不用担心返回类型,在矩阵上使用
squeeze来减少维度可能会很烦人(例如[[1]])。 -
在今年的一次会议上,他们提到一旦采用另一种稀疏表示,numpy.matrix 就会贬值。避免使用 numpy.matrix 的另一个原因。
标签: python arrays matrix numpy