Matrix Product

Matrix multiplication (the matrix product) is a fundamental operation in linear algebra that combines two matrices to produce a new one - and it powers core calculations behind Linear Regression, Neural Networks, and many other Machine Learning algorithms.

Matrix Product vs Element-Wise Multiplication

It's important not to confuse the matrix product with simple element-wise multiplication (using *), which just multiplies corresponding elements. The matrix product follows specific linear algebra rules instead.

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

print(a * b)     # element-wise: [[5, 12], [21, 32]]
print(a @ b)     # matrix product: [[19, 22], [43, 50]]
print(np.dot(a, b))   # same result as a @ b

How Matrix Multiplication Works

For two matrices to be multiplied, the number of columns in the first matrix must equal the number of rows in the second. Each element in the result is calculated as the sum of products between a row from the first matrix and a column from the second.

import numpy as np

a = np.array([[1, 2, 3]])        # shape (1, 3)
b = np.array([[4], [5], [6]])    # shape (3, 1)

result = a @ b
print(result)   # [[32]]  ->  (1*4 + 2*5 + 3*6)
Matrix multiplication is literally the mathematical operation behind how a neural network's layers transform data as it passes through the network - understanding it here makes Deep Learning far less intimidating later in the course.

Coming Up Next

Next, you'll explore more useful NumPy functions for sorting, searching, and summarizing array data.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course