dot的用法比較搞检号,主要是因?yàn)橐智闆r焰望,a,b的位置不同秕磷,結(jié)果就不同锈颗。 其中重要的不僅僅是對于a,b的維度判斷顷霹,因?yàn)檫@對于a,b哪個(gè)axis做alignment很重要(否則就要報(bào)錯(cuò)),然后對于產(chǎn)生結(jié)果的shape也有直接影響击吱。廢話不說淋淀,直接列出以下所有情況:
#%% dot of array:
# 情況1: If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
# 本來也就是處理a,b形狀一樣的情況 也就是shape=(n,)
# 不需要轉(zhuǎn)置直接內(nèi)積,最后得到一個(gè)scalar
# a,b 嚴(yán)格來說既不是column vector也不是row vector, 但是可以act like either one based on the position in a dot product.
a = np.array([1,2,3])
b = np.array([1,2,3])
c = np.dot(a,b)
print("c as inner product of vectors:", c) # c = 14
# 情況2:If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
a = np.arange(1,5).reshape((2,2))
b = np.arange(5,9).reshape((2,2))
c = np.dot(a,b)
print(c) # [[19 22],[43 50]]
# 情況3:If both a and b are 0-D arrays, it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.
a = 1
b = 2
c = np.dot(1,2)
print(c) # 2
# 情況4: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.
a=np.arange(3).reshape((1,3))
b= np.arange(3) # 這里b是1D,shape(3,)
c= np.dot(a,b) # 用a的最后一個(gè)axis也就是3 去align b的唯一axis3, 匹配覆醇,然后分別乘法相加
print(c) # 5 as shape(1,) 因?yàn)樯弦徊絘和b的3都align 相當(dāng)于抵了朵纷,剩下一個(gè)a的(1,)就作為c的shape
print(c.shape)
# 情況5: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:
# 這種情況就是需要第一個(gè)變量的最后axis去匹配第二個(gè)變量的倒數(shù)第二個(gè)axis
d=np.arange(12).reshape((3,4))
c= np.dot(b,d) # b: shape(3,) d: shape(3,4)
print(c) # array([20, 23, 26, 29]) 其中用b的3 去匹配倒數(shù)第二個(gè)axis也就是3叫乌,那么匹配柴罐,所以相互乘法后相加
print(c.shape) # 相互約去3之后,只有d剩一個(gè)(,4)這種情況放在shape里就是(4,)