DEV Community

Cover image for NumPy matrix multiplication: Get started in 5 minutes
Erin Schaffer for Educative

Posted on • Originally published at educative.io

NumPy matrix multiplication: Get started in 5 minutes

NumPy is a popular Python library that offers a range of powerful mathematical functions. The library is widely used in quantitative fields, such as data science, machine learning, and deep learning. We can use NumPy to perform complex mathematical calculations, such as matrix multiplication.

Matrix multiplication can help give us quick approximations of very complicated calculations. It can help us with network theory, linear systems of equations, population modeling, and much more. In this tutorial, we’ll explore some basic computations with NumPy matrix multiplication.

Let’s get started!

We'll cover:

What is NumPy?

NumPy is an open-source Python library that we can use to perform high-level mathematical operations with arrays, matrices, linear algebra, Fourier analysis, and more. The NumPy library is very popular within scientific computing, data science, and machine learning. NumPy is compatible with popular data science libraries like pandas, matplotlib, and Scikit-learn. It’s much faster than Python lists because it integrates faster codes, such as C and C++, in Python. It also breaks down our tasks into multiple pieces and processes each piece concurrently.

Installing and importing NumPy

Before we get started, let’s make sure we have NumPy installed. If you already have Python, you can install NumPy with one of the following commands:

conda install numpy
Enter fullscreen mode Exit fullscreen mode

or

pip install numpy
Enter fullscreen mode Exit fullscreen mode

To import NumPy into our Python code, we can use the following command:

import numpy as np
Enter fullscreen mode Exit fullscreen mode

What is a NumPy matrix?

A matrix is a 2-D array. Each element in the array has two indices. Let’s look at an example in NumPy:

import numpy as np

A = [[6, 7],
      [8, 9]]

print(np.array(A) [0,0])

=> 6
Enter fullscreen mode Exit fullscreen mode

In the above code, we have matrix A [[6, 7], [8, 9]]. We ask for the element given at (0,0), and our output returns 6. When we want to define the shape of our matrix, we use the number of rows by the number of columns. That means that matrix A has a shape of 2x2.

​Now, let’s take a look at some different NumPy matrix multiplication methods.

NumPy matrix multiplication methods

There are three main ways to perform NumPy matrix multiplication:

  • np.dot(array a, array b): returns the scalar or dot product of two arrays
  • np.matmul(array a, array b): returns the matrix product of two arrays
  • np.multiply(array a, array b): returns the element-wise matrix multiplication of two arrays

Let’s take a closer look at each of the three methods:

Scalar multiplication or dot product with numpy.dot

Scalar multiplication is a simple form of matrix multiplication. A scalar is just a number, like 1, 2, or 3. In scalar multiplication, we multiply a scalar by a matrix. Each element in the matrix is multiplied by the scalar, which makes the output the same shape as the original matrix.

With scalar multiplication, the order doesn’t matter. We’ll get the same result whether we multiply the scalar by the matrix or the matrix by the scalar.

Let’s take a look at an example:

import numpy as np

A = 5

B = [[6, 7],
      [8, 9]]

print(np.dot(A,B))

=> [[30 35]
=>  [40 45]]
Enter fullscreen mode Exit fullscreen mode

Now, let’s multiply a 2-dimensional matrix by another 2-dimensional matrix. When multiplying two matrices, the order matters. That means that matrix A multiplied by matrix B is not the same as matrix B multiplied by matrix A.

Before we get started, let's look at a visual for how the multiplication is done.

Alt Text

import numpy as np

A = [[6, 7],
      [8, 9]]

B = [[1, 3],
      [5, 7]]

print(np.dot(A,B))

print("----------")

print(np.dot(B,A))

=> [[41 67]
=>  [53 87]]
----------
=> [[30 34]
=>  [86 98]]
Enter fullscreen mode Exit fullscreen mode

Note: It’s important to note that we can only multiply two matrices if the number of columns in the first matrix is equal to the number of rows in the second matrix.

Matrix product with numpy.matmul

The matmul() function gives us the matrix product of two 2-d arrays. With this method, we can’t use scalar values for our input. If one of our arguments is a 1-d array, the function converts it into a matrix by appending a 1 to its dimension. This is removed after the multiplication is done.

If one of our arguments is greater than 2-d, the function treats it as a stack of matrices in the last two indexes. The matmul() method is great for times when we’re unsure of what the dimensions of our matrices will be.

Let’s look at some examples:

Multiplying a 2-d array by another 2-d array

import numpy as np

A = [[2, 4],
      [6, 8]]

B = [[1, 3],
      [5, 7]]

print(np.matmul(A,B))

=> [[22 34]
=>  [46 74]]
Enter fullscreen mode Exit fullscreen mode

Multiplying a 2-d array by a 1-d array

import numpy as np

A = [[5, 0],
      [0, 5]]

B = [5, 2]

print(np.matmul(A,B))

=> [25 10]
Enter fullscreen mode Exit fullscreen mode

One array with dimensions greater than 2-d

import numpy as np

A = np.arange(8).reshape(2, 2, 2)

B = np.arange(4).reshape(2, 2)

print(np.matmul(A,B))

=> [[[ 2  3]
=>   [ 6 11]]

=>  [[10 19]
=>   [14 27]]]
Enter fullscreen mode Exit fullscreen mode

Element-wise matrix multiplication with numpy.multiply

The numpy.multiply() method takes two matrices as inputs and performs element-wise multiplication on them. Element-wise multiplication, or Hadamard Product, multiples every element of the first matrix by the equivalent element in the second matrix. When using this method, both matrices should have the same dimensions.

Let’s look at an example:

import numpy as np

A = np.array([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]])

B = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]])

print(np.multiply(A,B))

=> [[ 1  6 15 28 45]
=>  [10 16 18 16 10]]
Enter fullscreen mode Exit fullscreen mode

We can pass certain rows, columns, or submatrices to the numpy.multiply() method. The sizes of the rows, columns, or submatrices that we pass as our operands should be the same. Let’s look at an example:

import numpy as np

A = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

B = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])

print(np.multiply(A[ 0,:], B[ 1,: ]))

print("----------")

print(np.multiply(A[ 1,:], B[ 0,:]))

=> [ 16  34  54  76 100]
=> ----------
=> [ 66  84 104 126 150]
Enter fullscreen mode Exit fullscreen mode

Wrapping up and next steps

Congrats on taking your first steps with NumPy matrix multiplication! It’s a complicated, yet important part of linear algebra. It helps us further our understanding of different aspects of data science, machine learning, deep learning, and other prevalent fields. There’s still a lot more to learn about NumPy and matrices. Some recommended topics to cover next are:

  • NumPy matrix transpose
  • NumPy arrays (ndarray)
  • NumPy vectorization

To get started learning these concepts and more, check out Educative’s learning path Python Data Analysis and Visualization. This hands-on learning path will help you master the skills to extract insights from data using a powerful assortment of popular Python libraries.

Happy learning!

Continue learning about Python

Top comments (0)