np.array()中, “ * ”,np.dot(),np.multiply(),np.matmul()和@的用法
import numpy as np
a=np.array([[1,2],[3,4]])
b=np.array([[1,2],[3,4]])
c=np.array([1,3])
d=np.array([0,1])
e=np.array([[2,1]])
(1) * 的用法,對應位置元素相乘; multiply對應元素相乘,類似 *
print(a*b)#對應位置元素相乘
print(np.multiply(a,b))#對應位置元素相乘
[[ 1 4]
[ 9 16]]
[[ 1 4]
[ 9 16]]
print(a*c)
print(np.multiply(a,c))
[[ 1 6]
[ 3 12]]
[[ 1 6]
[ 3 12]]
print(c*d)
print(np.multiply(c,d))
[0 3]
[0 3]
print(d*e)
print(np.multiply(d,e))
[[0 1]]
[[0 1]]
(2) dot 行對列,對應元素相乘再相加,@,matmul三者相似
a=np.array([[1,2],[3,4]])
b=np.array([[1,2],[3,4]])
c=np.array([1,3])
d=np.array([0,1])
e=np.array([[2,1]])
print(np.dot(a,b))#行對列,對應元素相乘再相加求和(矩陣乘法)
print([email protected])
print(np.matmul(a,b))
[1,2] [1,2]
[3,4] [3,4]
計算過程為 :
[1x1+2x3 1x2+2x4]
[3X1+4x3 3x2+4x4]
[[ 7 10]
[15 22]]
[[ 7 10]
[15 22]]
[[ 7 10]
[15 22]]
print(np.dot(a,c))
print([email protected])
print(np.matmul(a,c))
[ 7 15]
print(np.dot(c,d))
print([email protected])
print(np.matmul(c,d))
3
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-88-a4f728f79257> in <module>
----> 1 print(np.dot(d,e))
<__array_function__ internals> in dot(*args, **kwargs)
ValueError: shapes (2,) and (1,2) not aligned: 2 (dim 0) != 1 (dim 0)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-90-afe09a6d039d> in <module>
1 #兩者都報錯
----> 2 print(np.matmul([email protected]))
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 2)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-91-b9f371cba1e1> in <module>
----> 1 print([email protected])
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 2)