numpy数组和矩阵有什么区别?我应该使用哪一个?

问题:numpy数组和矩阵有什么区别?我应该使用哪一个?

每种都有哪些优点和缺点?

从我所看到的情况来看,如果需要,任何一个都可以替代另一个,所以我应该同时使用这两个还是应该仅使用其中之一?

程序的样式会影响我的选择吗?我正在使用numpy进行一些机器学习,因此确实有很多矩阵,但也有很多向量(数组)。

What are the advantages and disadvantages of each?

From what I’ve seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them?

Will the style of the program influence my choice? I am doing some machine learning using numpy, so there are indeed lots of matrices, but also lots of vectors (arrays).


回答 0

根据官方文件,不再建议使用矩阵类,因为将来会删除它。

https://numpy.org/doc/stable/reference/generation/numpy.matrix.html

正如其他答案所指出的那样,您可以使用NumPy数组实现所有操作。

As per the official documents, it’s not anymore advisable to use matrix class since it will be removed in the future.

https://numpy.org/doc/stable/reference/generated/numpy.matrix.html

As other answers already state that you can achieve all the operations with NumPy arrays.


回答 1

numpy的矩阵是严格2维的,而numpy的阵列(ndarrays)是N维的。矩阵对象是ndarray的子​​类,因此它们继承了ndarray的所有属性和方法。

numpy矩阵的主要优点是它们为矩阵乘法提供了一种方便的表示法:如果a和b是矩阵,则a*b它们是矩阵乘积。

import numpy as np

a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
#  [2 1]]
print(b)
# [[1 2]
#  [3 4]]
print(a*b)
# [[13 20]
#  [ 5  8]]

另一方面,从Python 3.5开始,NumPy使用@运算符支持中缀矩阵乘法,因此您可以在Python> = 3.5中使用ndarrays实现相同的矩阵乘法便捷性。

import numpy as np

a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
#  [ 5  8]]

矩阵对象和ndarray都.T必须返回转置,但是矩阵对象也必须具有.H共轭转置和.I逆。

相反,numpy数组始终遵守以元素为单位应用操作的规则(除了new @运算符)。因此,如果ab是numpy数组,则a*b该数组是通过按元素逐个乘以组成的:

c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
#  [6 4]]

要获得矩阵乘法的结果,请使用np.dot(或@在Python> = 3.5中,如上所示):

print(np.dot(c,d))
# [[13 20]
#  [ 5  8]]

**运营商还表现不同:

print(a**2)
# [[22 15]
#  [10  7]]
print(c**2)
# [[16  9]
#  [ 4  1]]

由于a是矩阵,所以a**2返回矩阵乘积a*a。由于c是ndarray,因此c**2返回一个ndarray,每个组件的元素均平方。

矩阵对象和ndarray之间还有其他技术差异(与np.ravel,项目选择和序列行为有关)。

numpy数组的主要优点是它们比二维矩阵更通用。当您需要3维数组时会发生什么?然后,您必须使用ndarray,而不是矩阵对象。因此,学习使用矩阵对象的工作量更大-您必须学习矩阵对象操作和ndarray操作。

编写一个将矩阵和数组混合在一起的程序会使您的生活变得困难,因为您必须跟踪变量是什么类型的对象,以免乘法返回您不期望的东西。

相反,如果仅使用ndarray,则可以执行矩阵对象可以执行的所有操作,以及更多操作,但功能/符号略有不同。

如果您愿意放弃NumPy矩阵产品表示法的视觉吸引力(使用python> = 3.5的ndarrays几乎可以优雅地实现),那么我认为NumPy数组绝对是可行的方法。

PS。当然,您实际上不必选择以牺牲另一个为代价,因为np.asmatrixnp.asarray允许您将一个转换为另一个(只要数组是二维的)。


还有就是与NumPy之间的差异大纲arraysVS NumPy的matrixES 这里

Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.

The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are matrices, then a*b is their matrix product.

import numpy as np

a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
#  [2 1]]
print(b)
# [[1 2]
#  [3 4]]
print(a*b)
# [[13 20]
#  [ 5  8]]

On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @ operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.

import numpy as np

a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
#  [ 5  8]]

Both matrix objects and ndarrays have .T to return the transpose, but matrix objects also have .H for the conjugate transpose, and .I for the inverse.

In contrast, numpy arrays consistently abide by the rule that operations are applied element-wise (except for the new @ operator). Thus, if a and b are numpy arrays, then a*b is the array formed by multiplying the components element-wise:

c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
#  [6 4]]

To obtain the result of matrix multiplication, you use np.dot (or @ in Python >= 3.5, as shown above):

print(np.dot(c,d))
# [[13 20]
#  [ 5  8]]

The ** operator also behaves differently:

print(a**2)
# [[22 15]
#  [10  7]]
print(c**2)
# [[16  9]
#  [ 4  1]]

Since a is a matrix, a**2 returns the matrix product a*a. Since c is an ndarray, c**2 returns an ndarray with each component squared element-wise.

There are other technical differences between matrix objects and ndarrays (having to do with np.ravel, item selection and sequence behavior).

The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work — you have to learn matrix object operations, and ndarray operations.

Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don’t expect.

In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.

If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.

PS. Of course, you really don’t have to choose one at the expense of the other, since np.asmatrix and np.asarray allow you to convert one to the other (as long as the array is 2-dimensional).


There is a synopsis of the differences between NumPy arrays vs NumPy matrixes here.


回答 2

Scipy.org建议您使用数组:

*’array’或’matrix’?我应该使用哪个?-简短答案

使用数组。

  • 它们是numpy的标准向量/矩阵/张量类型。许多numpy函数返回数组,而不是矩阵。

  • 在逐元素运算和线性代数运算之间有明显的区别。

  • 如果愿意,可以有标准向量或行/列向量。

使用数组类型的唯一缺点是,您将不得不使用dot而不是*乘(减少)两个张量(标量积,矩阵向量乘法等)。

Scipy.org recommends that you use arrays:

*’array’ or ‘matrix’? Which should I use? – Short answer

Use arrays.

  • They are the standard vector/matrix/tensor type of numpy. Many numpy function return arrays, not matrices.

  • There is a clear distinction between element-wise operations and linear algebra operations.

  • You can have standard vectors or row/column vectors if you like.

The only disadvantage of using the array type is that you will have to use dot instead of * to multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.).


回答 3

只是将一个案例添加到unutbu的列表中。

与numpy矩阵或矩阵语言(如matlab)相比,numpy ndarray对我而言最大的实际差异之一是,在归约运算中未保留维。矩阵始终为2d,而数组的均值则少一维。

例如,矩阵或数组的行为不佳的行:

带矩阵

>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
        [2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
        [ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5,  0.5],
        [-0.5,  0.5]])

带阵列

>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
       [2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5,  2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
       [ 0.5,  0.5]])
>>> a - am[:, np.newaxis]  #right
array([[-0.5,  0.5],
       [-0.5,  0.5]])

我还认为混合数组和矩阵会带来很多“快乐的”调试时间。但是,就乘法而言,scipy.sparse矩阵始终是矩阵。

Just to add one case to unutbu’s list.

One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.

For example demean rows of a matrix or array:

with matrix

>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
        [2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
        [ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5,  0.5],
        [-0.5,  0.5]])

with array

>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
       [2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5,  2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
       [ 0.5,  0.5]])
>>> a - am[:, np.newaxis]  #right
array([[-0.5,  0.5],
       [-0.5,  0.5]])

I also think that mixing arrays and matrices gives rise to many “happy” debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.


回答 4

正如其他人提到的那样,也许它的主要优点matrix是它为矩阵乘法提供了一种方便的符号。

但是,在Python 3.5中,终于有了一个专用的infix运算符用于矩阵乘法@

在最新的NumPy版本中,它可以与ndarrays 一起使用:

A = numpy.ones((1, 3))
B = numpy.ones((3, 3))
A @ B

因此,如今,如果有更多疑问,您应该坚持ndarray

As others have mentioned, perhaps the main advantage of matrix was that it provided a convenient notation for matrix multiplication.

However, in Python 3.5 there is finally a dedicated infix operator for matrix multiplication: @.

With recent NumPy versions, it can be used with ndarrays:

A = numpy.ones((1, 3))
B = numpy.ones((3, 3))
A @ B

So nowadays, even more, when in doubt, you should stick to ndarray.