In this post, we will see how to perform matrix multiplication using NumPy. Input parameters for numpy matrix multiplication are two array-like objects (it can be a numpy ndarray or python lists as well), and it produces the product of two matrices as output. Performing matrix multiplication on NumPy arrays is more efficient than performing matrix multiplication on python lists.

Let’s start by importing NumPy and performing a simple matrix multiplication using NumPy’s matrix multiplication np.matmul.

Python 3.8.5 (default, Mar  8 2021, 13:02:45)

[GCC 9.3.0] on linux2

Type “help”, “copyright”, “credits” or “license” for more information.

>>> import numpy as np

>>> a = np.array([[1, 2, 3],

…           [4, 5, 6]])

>>> a.shape

(2, 3)

>>> b = np.array([[1, 1],

…           [1, 1],

…           [1, 1]])

>>> b.shape

(3, 2)

>>> c = np.matmul(a, b)

>>> c.shape

(2, 2)

>>> c

array([[ 6,  6],

           [15, 15]])

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/image1-44.png" data-lazy- height="812" src="data:image/svg xml,” width=”1726″>

The matrix multiplication in numpy follows the signature (n, k) * (k, m) -> (n, m). Sometimes, we need to perform a simple scalar multiplication of a matrix. To perform a scalar multiplication, the operator * can be used.

>>> a = np.ones((2, 3))

>>> a

array([[1., 1., 1.],

           [1., 1., 1.]])

>>> a * 2

array([[2., 2., 2.],

           [2., 2., 2.]])

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/image3-38.png" data-lazy- height="342" src="data:image/svg xml,” width=”1012″>

np.matmul could also be used to perform the multiplication of multi-dimensional matrices. In the case of multi-dimensional matrices, the last two dimensions of the input matrices are considered for matrix multiplication.

>>> a = np.ones((8, 3, 2))

>>> a.shape

(8, 3, 2)

>>> b = np.ones((8, 2, 5))

>>> b.shape

(8, 2, 5)

>>> c = np.matmul(a, b)

>>> c.shape

(8, 3, 5)

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/image2-44.png" data-lazy- height="454" src="data:image/svg xml,” width=”1012″>

When operating on the inputs for np.matmul, numpy compares their shape to check whether the matrix multiplication between the two arrays is compatible or not. Ideally, the last dimension of matrix 1 should be the same as the second to last dimension of matrix 2. If they are not compatible, a Value Error is raised.

>>> a = np.ones((2, 3))

>>> a.shape

(2, 3)

>>> b = np.ones((1, 2))

>>> b.shape

(1, 2)

>>> np.matmul(a, b)

Traceback (most recent call last):

ValueError: matmul: Input operand 1 has a mismatch …

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/image4-36.png" data-lazy- height="552" src="data:image/svg xml,” width=”1926″>