python - 混合 numpy 矩阵和数组的危险

标签 python arrays matrix numpy

我正在处理的科学/工程应用程序有很多线性代数矩阵乘法,因此我使用 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() 调用中以确保它们仍然是矩阵真的很麻烦。这方面似乎没有标准,因此可能导致难以检测的错误。

最佳答案

出于以下几个原因,我倾向于在 numpy 中使用 array 而不是 matrix:

  1. matrix 严格来说是二维的,而您可以拥有任意维度的 numpy array
  2. 除了一些差异之外,arraymatrix 操作非常相似interchangeable对于 Matlab 用户。
  3. 如果您始终使用 array,那么您将使用 numpy.dot()(或者在 Python 3.5 中使用新的 @ 二元运算符)用于矩阵乘法。这将防止不确定 * 在您的代码中实际做了什么的问题。当您遇到乘法错误时,您可以更轻松地发现问题,因为您确定要执行哪种乘法。

所以我建议您尝试坚持使用 numpy.array,但也要记住 arraymatrix 之间的区别。

最后,我发现在 bpython 上使用 numpy/scipy 是一种乐趣.自动提示可以帮助您以比不断查阅 numpy/scipy 文档更快的速度了解您尝试使用的函数的属性。

编辑: arraymatrix 之间的区别可能最好在这里回答:'array' or 'matrix'? Which should I use?

关于python - 混合 numpy 矩阵和数组的危险,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12024820/

相关文章:

python - 如何以优雅且安全(关于Python模块重新加载)的方式使用super()?

python - 使用 pyspark 从没有 accountkey 的 blob 中读取数据

arrays - 在 F# 中的数组中创建重复序列的最佳方法是什么?

javascript - 在 node.js 中,为什么会有一个 util.isArray 和一个 Array.isArray?

c - 遍历 const 矩阵和 vector

c++ - 是否可以找出两个模板参数之间的表达式类型?

arrays - 在 julia 中获取多维数组的一维子集

python - Numba nopython 模式的三对角矩阵算法

python - Django 和限制 RAM 使用 : Recommended syntax, 约定和策略?

python - 从 python 数组创建元素明智的字典