NumPy 中 ndarray 和 matrix 的区别

NumPy 中 ndarray 和 matrix 的区别

本文概述了numpy中的ndarray与matrix之间的使用差异,首先导入numpy:

import numpy as np
  1. 维数不同
    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]]]
  1. 矩阵乘法
    对于 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]])
  1. 相互转换
    两者可以互相用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])才是。

  2. 如何选择

尽量多使用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
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值