Chapter 4.2 - Matrix Multiplication
✖️ Matrix Multiplication
Matrix multiplication is essentially just doing many Dot Products all at once.
Let's visualize how a matrix multiplies with another matrix mathematically. We will use colors to track exactly where each number goes.
The Rule: Rows Columns
To find the top-left number of the answer, we take the Top Row of the first matrix and calculate the dot product with the Left Column of the second matrix.
Example with Numbers
Let's use some real numbers to see this in action. Suppose we have two matrices, and .
When we multiply :
Matrix Multiplication in PyTorch
In Python using PyTorch, we can perform this exact same mathematical operation instantly using the @ symbol:
import torch
X = torch.tensor([
[1, 2],
[3, 4]
])
Y = torch.tensor([
[5, 6],
[7, 8]
])
# Perform matrix multiplication using the @ operator
result = X @ Y
print(result)
Output:
tensor([[19, 22],
[43, 50]])
Matrix multiplication (@) is the engine of all Neural Networks. Whenever you see @ in PyTorch, just remember it means: "Take each row of the matrix on the left, and compute its dot product with each column of the matrix on the right."