Implementation Example of NumPy Matrix Multiplication

  • 2021-10-13 08:13:39
  • OfStack

Several types of matrix multiplication supported by NumPy are also important.

Element level multiplication

You have seen some elemental multiplication. You can do this using the multiply function or the * operator. Looking back at 1, it looks like this:


m = np.array([[1,2,3],[4,5,6]])
m
#  Displays the following results: 
# array([[1, 2, 3],
#  [4, 5, 6]])

n = m * 0.25
n
#  Displays the following results: 
# array([[ 0.25, 0.5 , 0.75],
#  [ 1. , 1.25, 1.5 ]])

m * n
#  Displays the following results: 
# array([[ 0.25, 1. , 2.25],
#  [ 4. , 6.25, 9. ]])

np.multiply(m, n) #  Equivalent to  m * n
#  Displays the following results: 
# array([[ 0.25, 1. , 2.25],
#  [ 4. , 6.25, 9. ]])

Matrix product

To get the matrix product, you can use the matmul function of NumPy.

If you have compatible shapes, it's as simple as this:


a = np.array([[1,2,3,4],[5,6,7,8]])
a
#  Displays the following results: 
# array([[1, 2, 3, 4],
#  [5, 6, 7, 8]])
a.shape
#  Displays the following results: 
# (2, 4)

b = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
b
#  Displays the following results: 
# array([[ 1, 2, 3],
#  [ 4, 5, 6],
#  [ 7, 8, 9],
#  [10, 11, 12]])
b.shape
#  Displays the following results: 
# (4, 3)

c = np.matmul(a, b)
c
#  Displays the following results: 
# array([[ 70, 80, 90],
#  [158, 184, 210]])
c.shape
#  Displays the following results: 
# (2, 3)

If your matrix has incompatible shapes, the following error will occur:


np.matmul(b, a)
#  Displays the following error: 
# ValueError: shapes (4,3) and (2,4) not aligned: 3 (dim 1) != 2 (dim 0)

dot Function of NumPy

Sometimes, where you think you want to use the matmul function, you may see the dot function of NumPy. It turns out that if the matrix is 2-dimensional, the results of dot and matmul functions are the same.

So these two results are equivalent:


a = np.array([[1,2],[3,4]])
a
#  Displays the following results: 
# array([[1, 2],
#  [3, 4]])

np.dot(a,a)
#  Displays the following results: 
# array([[ 7, 10],
#  [15, 22]])

a.dot(a) # you can call You can go straight to the  `ndarray`  Call  `dot` 
#  Displays the following results: 
# array([[ 7, 10],
#  [15, 22]])

np.matmul(a,a)
# array([[ 7, 10],
#  [15, 22]])

Although these two functions return the same results for 2D data, you should be careful when using them for other data shapes. You can find out more about the differences between matmul and dot documentation and find links to other NumPy functions.


Related articles: