np.dot()使用方法

2022-09-10 13:08:40

np.dot()函数主要有两个功能,向量点积和矩阵乘法,这里我就简单列举了三种最常用到的情况

  1. np.dot(a, b), 其中a为一维的向量,b为一维的向量,当然这里a和b都是np.ndarray类型的, 此时因为是一维的所以是向量点积。
importnumpyasnpa=np.array([1,2,3,4,5])b=np.array([6,7,8,9,10])print(np.dot(a,b))output:130[Finishedin0.2s]
  1. np.dot(a, b), 其中a为二维矩阵,b为一维向量,这时b会被当做一维矩阵进行计算
importnumpyasnpa=np.random.randint(0,10,size=(5,5))b=np.array([1,2,3,4,5])print("the shape of a is "+str(a.shape))print("the shape of b is "+str(b.shape))print(np.dot(a,b))output:theshapeofais(5,5)theshapeofbis(5,)[4285508176][Finishedin0.2s]

这里需要注意的是一维矩阵和一维向量的区别,一维向量的shape是(5, ), 而一维矩阵的shape是(5, 1), 若两个参数a和b都是一维向量则是计算的点积,但是当其中有一个是矩阵时(包括一维矩阵),dot便进行矩阵乘法运算,同时若有个参数为向量,会自动转换为一维矩阵进行计算。

  1. np.dot(a ,b), 其中a和b都是二维矩阵,此时dot就是进行的矩阵乘法运算
importnumpyasnpa=np.random.randint(0,10,size=(5,5))b=np.random.randint(0,10,size=(5,3))print("the shape of a is "+str(a.shape))print("the shape of b is "+str(b.shape))print(np.dot(a,b))output:theshapeofais(5,5)theshapeofbis(5,3)[[668098][536060][658485][25113101][427877]][Finishedin0.2s]
  • 作者:wxtRelax
  • 原文链接:https://blog.csdn.net/w_weixiaotao/article/details/109767856
    更新时间:2022-09-10 13:08:40