天天看点

numpy中dot与*的区别

dot是矩阵相乘,只要矩阵满足前一个矩阵的列与后一个矩阵的行相匹配即可

*是遵循numpy中的广播机制,必须保证行列相对应才可以进行运算

先看一则正例

>>import numpy as np
#test1与test2行列相同
>>test1 = np.array([[1,2],[3,4]])
>>test2 = np.array([[3,3],[2,2]])
>>test1 * test2
array([[3, 6],
       [6, 8]])
>>np.dot(test1,test2)
array([[ 7,  7],
       [17, 17]])
           

再看一则反例

#test3与test4行列数不相同
>>test3 = np.array([[1,2],[2,3]])
>>test4 = np.array([[2,3,4],[4,5,6]])
>>test3*test4
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2,2) (2,3) 
>>np.dot(test3,test4)
array([[10, 13, 16],
       [16, 21, 26]])
           

很明显,错误信息是由于test3中的(2,2)与test4(2,3)行列不匹配,故不可以进行*运算,而dot则可以因为test3中的列2 = test4中的行2