Lesson 3.5 · Stage 03: The maths behind machine learning
Maths chapter 3: Matrices: tables of numbers
A matrix is a rectangular table of numbers. It is how ML stores a whole dataset and how it transforms vectors.
A matrix is a rectangular table of numbers. It is how ML stores a whole dataset and how it transforms vectors.
3.1 What a matrix is
A matrix with 2 rows and 3 columns is called a 2 × 3 matrix (“2 by 3”). Rows always come first.
Think of a table in a database: each row is one data item (one house), each column is one feature (area, bedrooms, age). The number in row 2, column 3 is written a₂₃ = 6.
3.2 Matrix times vector
Take each row of the matrix, dot it with the vector (Chapter 2), and stack the answers.
The matrix turned the arrow (1, 2) into the arrow (4, 7). A matrix is a machine that transforms vectors: it can stretch, rotate or flip them.
Size rule: the number of columns in the matrix must equal the number of components in the vector.
3.3 Matrix times matrix
Each answer entry = (row from the first matrix) · (column from the second matrix).
Warning: order matters. Swap the two matrices and you get a different answer (try it: the top-left entry becomes 23). With ordinary numbers 2 × 3 = 3 × 2, but with matrices AB is usually not BA.
3.4 Special matrices and operations
- Identity matrix I: 1s on the diagonal, 0s elsewhere. It does nothing, like multiplying by 1: Iv = v.
- Transpose Aᵀ: rows become columns. The transpose of the 2 × 3 matrix A above is a 3 × 2 matrix with rows (1, 4), (2, 5), (3, 6).
- Determinant: one number that says how much a matrix stretches area. For a 2 × 2 matrix:
- Inverse A⁻¹: the matrix that undoes A, so A⁻¹A = I. For a 2 × 2 matrix, swap a and d, change the signs of b and c, and divide by the determinant:
If the determinant is 0, there is no inverse. Such a matrix squashes the plane flat, and you can’t un-squash it.
3.5 Solving equations with matrices
The class 9–10 problem “2x + y = 5 and x + 3y = 10” can be written as one matrix equation Ax = b:
- Determinant: 2 × 3 − 1 × 1 = 5.
- Inverse: (1/5) × [[3, −1], [−1, 2]].
- x = A⁻¹b = (1/5) × (3 × 5 − 1 × 10, −1 × 5 + 2 × 10) = (1/5) × (5, 15) = (1, 3).
- Check: 2 × 1 + 3 = 5 and 1 + 3 × 3 = 10. Correct.
Why ML needs it: linear regression is solved with exactly this idea, just with bigger matrices. A neural network layer is “matrix times vector”.
Try it
- Work out [[1, 2], [0, 3]] × (4, 1).
- Work out [[1, 0], [2, 1]] × [[3, 1], [1, 2]].
- Write the transpose of [[1, 2], [3, 4]].
- Find the determinant of [[3, 1], [4, 2]].
- Solve x + y = 5 and x − y = 1 (any method).