2.3 Transition to Matrices
Up to now, we have written out our equations line-by-line using variables like and . But in machine learning, we deal with millions of data points and features. Writing out equations by hand is impossible!
To handle large-scale data, we pack our numbers into grids called Matrices. In this lecture, we will learn how to rewrite systems of equations in matrix form () and master the core rules of Matrix Multiplication.
1. Moving from Equations to Matrices ()
Let's take a standard system of linear equations:
We can separate this system into three compact parts:
- (Coefficient Matrix): A grid containing only the coefficients (the numbers in front of the variables).
- (Variable Vector): A column vector of our unknown variables.
- (Target Vector): A column vector containing the answers on the right side of the equals sign.
Now, we can write the entire system of equations in a single, elegant line of matrix algebra:
2. Matrix-Vector Multiplication: How It Works
To make sure is actually the same as our original equations, we need to know how to multiply a matrix by a vector.
The Rule: Row Dot Column
To multiply a matrix by a vector, we take each row of the matrix and compute its dot product with the column vector.
This yields a new column vector. Matching this result to our target vector gives us our original equations back!
3. Matrix-Matrix Multiplication
In machine learning, we often multiply matrices by other matrices (for example, when passing a batch of inputs through a neural network layer).
Suppose we want to multiply matrix (size ) by matrix (size ) to get a new matrix :
We calculate each cell in the result matrix using the Row-by-Column rule:
- Row 1 of A Column 1 of B Cell :
- Row 1 of A Column 2 of B Cell :
- Row 2 of A Column 1 of B Cell :
- Row 2 of A Column 2 of B Cell :
So, our final result is:
[!WARNING] Order Matters! In regular math, . But in matrix multiplication, in general! Changing the order of multiplication will yield a completely different result, or might even be mathematically impossible because the sizes don't match.
4. Visualizing Matrices in Code
In machine learning libraries like NumPy or PyTorch, matrices are represented as 2D arrays. Below is a visualization of a coefficients matrix in grid form:
5. Master the Calculation in the Lab
To build your mechanical intuition of how rows dot-product with columns step-by-step, go to the computational sandbox:
🔬 Matrix Multiplication & Vector Space Visualizer
6. Check Your Understanding
If you multiply matrix A of size (3 x 2) by matrix B of size (2 x 4), what will be the size of the resulting matrix C?
🔬 Interactive Laboratory Sandbox
Run practical simulations and numerical verifications associated with the mathematical equations derived in this note: