Numpy 中的多维矩阵

Multidimensional Matrix in Numpy

我读了一些关于 NumPy 的内容,它是 Matrix class。在作者写的文档中,我们只能创建一个二维矩阵。所以我认为他们的意思是你只能写这样的东西:

input = numpy.matrix( ((1,2), (3,4))

这样对吗? 但是当我这样写代码时:

input = numpy.matrix( ((1,2), (3,4), (4,5)) )

它也有效... 通常我会说好的,为什么不呢,我不关心它为什么起作用。但是我必须为我的大学参加考试,所以我必须知道我是否理解正确,或者它们对 2D Matrix 有其他含义吗?

感谢您的帮助

它们都是二维矩阵。第一个是 2x2 二维矩阵,第二个是 3x2 二维矩阵。它与编程中的二维数组非常相似。例如,第二个矩阵在 C 中定义为 int matrix[3][2]

那么,3D矩阵意味着它有如下定义:int 3d_array[3][2][3].

在 numpy 中,如果我用 3d 矩阵尝试这个:

>>> input = numpy.matrix((((2, 3), (4, 5)), ((6, 7), (8, 9))))
ValueError: matrix must be 2-dimensional

emre.的答案是正确的,但我还是想解决一下numpy矩阵的使用,这可能是你困惑的根源。


如果对使用 numpy.matrix 有疑问,请使用 ndarrays :

  • Matrix 实际上是一个 ndarray 子类:矩阵能做的一切,ndarray 都能做到(反过来不完全正确)。
  • 矩阵覆盖***运算符,Matrixndarray之间的任何运算都会return一个matrix,这对某些算法来说是有问题的。

关于 ndarraymatrix 关于 this SO post, and specifically this short answer

的辩论的更多信息

来自Numpy documentation

matrix objects inherit from the ndarray and therefore, they have the same attributes and methods of ndarrays. There are six important differences of matrix objects, however, that may lead to unexpected results when you use matrices but expect them to act like arrays:

  • Matrix objects can be created using a string notation to allow Matlab-style syntax where spaces separate columns and semicolons (‘;’) separate rows.

  • Matrix objects are always two-dimensional. This has far-reaching implications, in that m.ravel() is still two-dimensional (with a 1 in the first dimension) and item selection returns two-dimensional objects so that sequence behavior is fundamentally different than arrays.

  • Matrix objects over-ride multiplication to be matrix-multiplication. Make sure you understand this for functions that you may want to receive matrices. Especially in light of the fact that asanyarray(m) returns a matrix when m is a matrix.

  • Matrix objects over-ride power to be matrix raised to a power. The same warning about using power inside a function that uses asanyarray(...) to get an array object holds for this fact.

  • The default __array_priority__ of matrix objects is 10.0, and therefore mixed operations with ndarrays always produce matrices.

  • Matrices have special attributes which make calculations easier. [...]