Hello everyone!
From what I’ve realized, in the case of matrix multiplication(where we have 2D matrices), these three give the same output and can be used interchangeably. Although, for 1D matrices, it may not be true.
I even did a small experiment with a 1*3
and a 3*3
matrix and the results for all three cases were the same, so I was wondering if we could use just any of them in our assignments where we are doing matrix multiplication between two 2D matrices.
Also, I read somewhere that @
and np.matmul
are better than np.dot
and wanted to know whether this is true or not.
Here is my experiment:
import numpy as np
a = np.array([1,2,3]).reshape(3,1)
b = np.array([[4,5,6],[7,8,9],[1,2,3]])
print("\n\na=\n",a)
print("\n\nb=\n",b)
print("\n\nshapes\n",a.shape)
print(b.shape,"\n\n")
print("\n\n a^t=\n",a.T)
print("\n\n b= \n",b)
#using np.dot
ansDot = np.dot(a.T,b)
print("\n ans dot=\n",ansDot)
print("\n shape=",ansDot.shape)
#using np.matmul
ansmat=np.matmul(a.T,b)
print("\n ans matmul=\n",ansmat)
print("\n shape=",ansmat.shape)
#using @
ansAt = a.T @ b
print("\n ans atsign=\n",ansAt)
print("\n shape=",ansAt.shape)
print("\n\n\n----------------------------------------")
#add bias to the 1*3 matrix using broadcasting
b1 =1
print(ansDot + b1)
print(ansmat + b1)
print(ansAt + b1)
Output:
a=
[[1]
[2]
[3]]
b=
[[4 5 6]
[7 8 9]
[1 2 3]]
shapes
(3, 1)
(3, 3)
a^t=
[[1 2 3]]
b=
[[4 5 6]
[7 8 9]
[1 2 3]]
ans dot=
[[21 27 33]]
shape= (1, 3)
ans matmul=
[[21 27 33]]
shape= (1, 3)
ans atsign=
[[21 27 33]]
shape= (1, 3)
----------------------------------------
[[22 28 34]]
[[22 28 34]]
[[22 28 34]]