1. numpy.dot()
兩個數(shù)組的點乘操作,即先對應位置相乘然后再相加
- 如果 a, b 均是一維的,則就是兩個向量的內積
- 如果不都是一維的,則為矩陣乘法,第一個的行與第二個的列分別相乘求和
- If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
- If both a and b are 2-D arrays, it is matrix multiplication, but using
matmulora @ bis preferred.- If either a or b is 0-D (scalar), it is equivalent to
multiplyand usingnumpy.multiply(a, b)ora * bis preferred.- If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
- If a is an N-D array and b is an M-D array (where
M>=2), it is a sum product over the last axis of a and the second-to-last axis of b
- e.g.
>>> import numpy as np
>>> np.dot([1,2,3],[4,5,6])
32
>>> np.dot([1,2,3],2)
array([2, 4, 6])
>>> np.dot([[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]) # 注意維度
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)
>>> np.dot([[1,2,3],[4,5,6]],[[1,2,3],[4,5,6],[7,8,9]])
array([[30, 36, 42],
[66, 81, 96]])
- 矩陣場景
np.dot的參數(shù)是矩陣時則執(zhí)行矩陣運算
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> np.dot(a,b)
32
>>> np.dot(np.mat(a), np.mat(b))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
>>> np.dot(np.mat([[1,2,3],[4,5,6]]),np.mat([[1,2,3],[4,5,6],[7,8,9]]))
matrix([[30, 36, 42],
[66, 81, 96]])
--------------------------------------------------------------------------------------------------------------------
2. 乘號 *
對數(shù)組執(zhí)行對應位置相乘操作
對矩陣執(zhí)行矩陣乘法操作
- e.g.
>>> a = np.arange(1,7).reshape(2,3)
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> b = np.arange(0,6).reshape(2,3)
>>> b
array([[0, 1, 2],
[3, 4, 5]])
>>> a*b
array([[ 0, 2, 6],
[12, 20, 30]])
>>> (np.mat(a))*(np.mat(b.T)) #注意 a 的行數(shù)與 b 的列數(shù)相同
matrix([[ 8, 26],
[17, 62]])
----------------------------------------------------------------------------------------------------------------------
3. np.multiply()
Multiply arguments element-wise.
數(shù)組和矩陣對應位置相乘,輸出與相乘數(shù)組/矩陣的大小一致
>>> np.multiply(a,a)
array([[ 1, 4, 9],
[16, 25, 36]])
>>> np.multiply(np.mat(a),np.mat(a))
matrix([[ 1, 4, 9],
[16, 25, 36]])