Learn machine learning from scratch

Start at chapter 1 and build up: what a model is, how it measures its own mistakes, and how it learns. Everything is worked out in plain Python, with the maths shown rather than assumed. Two shorter tracks hold reference notes on the maths and on modern architectures.

Track Progress: 0 Completed
0%
The Math Behind MLLEVEL 1 · BEGINNERChapter 1

Linear Algebra, Vector Spaces & Matrix Calculus

Vector norms, geometric projections, trace derivative identities, and multivariate matrix calculus.

Reference notes. Condensed summaries of each topic, not step-by-step lessons. The Core Course is the one to work through.

8 min Prerequisites: High School Algebra & Functions
Inspect Architecture: Linear regression

1. The idea

Every machine learning dataset lives inside a vector space R^D, and every neural network layer applies a parameterized affine transformation W x + b followed by coordinate-wise non-linear curvature. Matrix calculus provides the exact formal mechanics for computing how scalar loss functions change with respect to multidimensional weight matrices.

Two diagrams. Left: the unit balls of two norms, the points x with norm 1. For the L1 norm, the sum of absolute values, it is a diamond with corners on the axes at 1 and minus 1; for the L2 norm, the square root of x-transpose x, it is the circle through the same four points. Right: two vectors u and v from the same origin with angle theta between them. A dashed line drops from the tip of v at a right angle onto u, and the part of u up to that foot is the projection of v onto u, which equals (u-transpose v over the squared L2 norm of u) times u. Also shown: u-transpose v = the L2 norm of u times the L2 norm of v times cos theta.Two diagrams. Left: the unit balls of two norms, the points x with norm 1. For the L1 norm, the sum of absolute values, it is a diamond with corners on the axes at 1 and minus 1; for the L2 norm, the square root of x-transpose x, it is the circle through the same four points. Right: two vectors u and v from the same origin with angle theta between them. A dashed line drops from the tip of v at a right angle onto u, and the part of u up to that foot is the projection of v onto u, which equals (u-transpose v over the squared L2 norm of u) times u. Also shown: u-transpose v = the L2 norm of u times the L2 norm of v times cos theta.
Norms measure size, and the inner product measures alignment: projecting v onto u keeps only the part of v that points along u.

2. The math

Vector & Matrix Norms
∥x∥1=∑i=1D∣xi∣∥x∥2=xTx∥A∥F=Tr(ATA)=∑i,jAij2\|x\|_1 = \sum_{i=1}^D |x_i| \qquad \|x\|_2 = \sqrt{x^T x} \qquad \|A\|_F = \sqrt{\text{Tr}(A^T A)} = \sqrt{\sum_{i,j} A_{ij}^2}
L1 norm (Manhattan/sparsity), L2 norm (Euclidean distance), and Frobenius norm (matrix magnitude).
Inner Product, Cosine Similarity & Orthogonal Projection
⟨u,v⟩=uTv=∥u∥2∥v∥2cos⁡θproju(v)=uTv∥u∥22u\langle u, v \rangle = u^T v = \|u\|_2 \|v\|_2 \cos \theta \qquad \text{proj}_u(v) = \frac{u^T v}{\|u\|_2^2} u
Measures alignment angle θ and projects vector v onto the 1D subspace spanned by u.
Essential Matrix Calculus Identities
∇x(aTx)=a∇x(xTAx)=(A+AT)x∇WTr(AWB)=ATBT\nabla_x (a^T x) = a \qquad \nabla_x (x^T A x) = (A + A^T)x \qquad \nabla_W \text{Tr}(A W B) = A^T B^T
Analytical vector and matrix derivatives commonly used in loss minimization.
Matrix Form Least Squares Gradient
L(W)=1N∥XW−Y∥F2  ⟹  ∇WL=2NXT(XW−Y)\mathcal{L}(W) = \frac{1}{N} \|X W - Y\|_F^2 \implies \nabla_W \mathcal{L} = \frac{2}{N} X^T (X W - Y)
Vectorized gradient of matrix linear regression with N samples and multi-output dimensions.

• Let the residual error matrix be E = XW - Y in R^(N x K).

• Express the Frobenius norm using the trace operator: ||E||_F^2 = Tr(E^T E) = Tr((XW - Y)^T (XW - Y)).

• Expand the terms inside the trace: Tr(W^T X^T X W - W^T X^T Y - Y^T X W + Y^T Y).

• Apply the trace derivative identity ∇_W Tr(W^T A W) = (A + A^T) W = 2 A W (since A = X^T X is symmetric), and ∇_W Tr(A W) = A^T:

• ∇_W ||XW - Y||_F^2 = 2 X^T X W - 2 X^T Y = 2 X^T (X W - Y). Q.E.D.

3. How it works

1
Coordinate Transformations
Matrix-vector multiplication y = Ax rotates, shears, and scales the coordinate basis vectors e_i.
2
Jacobians & Multi-Output Sensitivity
For vector function f: R^n -> R^m, the Jacobian matrix J_ij = ∂f_i / ∂x_j maps input velocity to output perturbation.
3
Hessians & Local Curvature
The symmetric Hessian matrix H_ij = ∂²f / (∂x_i ∂x_j) defines the second-order quadratic landscape around critical points.

4. The code (python)

math_linalg.py
import numpy as np

# Numerical vs Analytical Matrix Gradient Verification
def check_matrix_gradient(N=50, D=5, K=2, eps=1e-5):
    np.random.seed(42)
    X = np.random.randn(N, D)
    W = np.random.randn(D, K)
    Y = np.random.randn(N, K)

    # Analytical gradient: (2/N) * X^T (X W - Y)
    grad_analytical = (2.0 / N) * np.dot(X.T, (np.dot(X, W) - Y))

    # Numerical gradient via central finite difference
    grad_numerical = np.zeros_like(W)
    for i in range(D):
        for j in range(K):
            W_pos = W.copy(); W_pos[i, j] += eps
            W_neg = W.copy(); W_neg[i, j] -= eps
            loss_pos = np.mean((np.dot(X, W_pos) - Y)**2)
            loss_neg = np.mean((np.dot(X, W_neg) - Y)**2)
            grad_numerical[i, j] = (loss_pos - loss_neg) / (2.0 * eps)

    max_diff = np.max(np.abs(grad_analytical - grad_numerical))
    print(f"Analytical vs Numerical Gradient Max Difference: {max_diff:.2e}")
    assert max_diff < 1e-6, "Gradient check failed!"
    print("✓ Matrix Calculus Gradient Identity Verified Successfully.")

if __name__ == "__main__":
    check_matrix_gradient()

5. Check yourself

Answer all 1 questions correctly to complete the chapter · 0 / 1 done
Q1/1 Why is the gradient of a general quadratic form f(x) = x^T A x equal to (A + A^T)x instead of 2Ax?

In the catalog

Finished this chapter?

Weekly newsletter

The Epoch Zero newsletter

What changed in ML architectures this week: new models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.