NumPy 中 ndarray 和 matrix 的区别
本文概述了numpy中的ndarray与matrix之间的使用差异,首先导入numpy:
import numpy as np
- 维数不同
matrix只能表示二维数据,而ndarray可以表示n维数据
a = np.mat([[1,2], [3,4]])
b = np.mat('5 6;7 8')
output:
a:matrix([[1, 2],
[3, 4]])
b:matrix([[5, 6],
[7, 8]])
生成其他维度的矩阵会报错:
c = np.mat([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# ValueError: matrix must be 2-dimensional
x = np.array([[1, 2], [3, 4]])
# x = [[1 2]
# [3 4]]
y = np.array([[5, 6], [7, 8]])
# y = [[5 6]
# [7 8]]
z = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# z = [[[1 2]
# [3 4]]
#
# [[5 6]
# [7 8]]]
- 矩阵乘法
对于 matrix,使用运算符 * 或 NumPy 的 dot() 方法计算矩阵乘法,使用NumPy 的 multiply() 方法计算逐元素相乘
a * b
# matrix([[19, 22],
# [43, 50]])
np.dot(a, b)
# matrix([[19, 22],
# [43, 50]])
np.multiply(a, b)
# matrix([[ 5, 12],
# [21, 32]])
对于 ndarray,使用 NumPy 或者 ndarray 的 dot() 方法计算矩阵乘法,使用 运算符 * 或 Numpy 的 multiply() 方法计算逐元素相乘
x * y
# array([[ 5, 12],
# [21, 32]])
x.dot(y)
# array([[19, 22],
# [43, 50]])
np.dot(x, y)
# array([[19, 22],
# [43, 50]])
此外,从 Python 3.5 和 Numpy 1.10 以后,可以使用中缀操作符 @ 计算 ndarray 间的矩阵乘法,写起来更加方便:
x @ y
# array([[19, 22],
# [43, 50]])
-
相互转换
两者可以互相用np.asmatrix()或np.asarray()互相转换,两者转换都不会复制数据,前者发生改变会影响后者。
注意:
np.array 取第一列A[:, 0] 返回的不是矩阵, shape是没有列的维度的(例如(3,) 而不是(3,1)), 而np.mat则是列向量形式的矩阵(符合预期)。
np.array([1,2,3])不是矩阵,np.array([[1,2,3]])或np.mat([1,2,3])才是。 -
如何选择
尽量多使用ndarray
- They are the standard vector/matrix/tensor type of numpy. Many numpy functions 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.
参考链接:
- https://blog.nex3z.com/2017/07/23/numpy-%E4%B8%AD-ndarray-%E5%92%8C-matrix-%E7%9A%84%E5%8C%BA%E5%88%AB/
- https://blog.csdn.net/wkl7123/article/details/84332899