fX Engineers Explore the community

Machine Learning & AI

Gradient descent from first principles

Forty lines of NumPy, no framework, and the whole of modern machine-learning training in miniature - including the parameter that ruins everything.

· 9 min read

What is it?

You have a function that measures how wrong you are - a loss L(θ)L(\theta) - and you want the parameters θ\theta that make it small. Gradient descent is the simplest thing that works: compute the slope, step downhill, repeat.

θ←θ−α∇θL(θ)\theta \leftarrow \theta - \alpha \nabla_\theta L(\theta)

∇θL\nabla_\theta L is the gradient: the vector of partial derivatives, pointing in the direction of steepest increase. Subtracting it goes downhill. α\alpha is the learning rate, the length of the step.

Why does it exist?

Some problems have a closed-form solution. Linear regression does:

β^=(X⊤X)−1X⊤y\hat{\beta} = (X^\top X)^{-1} X^\top y

Exact, one shot, no iteration. So why iterate at all? Three reasons:

  1. Most losses have no closed form. The moment you add a non-linearity, the equation you would need to solve has no algebraic solution.
  2. The closed form does not scale. Inverting X⊤XX^\top X costs roughly O(d3)O(d^3) in the number of features. At d=106d = 10^6 that is not a computation you run.
  3. It only needs a gradient. Any loss you can differentiate can be minimised this way, which is why the same algorithm trains a two-parameter line and a trillion-parameter transformer.

How does it work?

Take linear regression, y^=Xβ\hat{y} = X\beta, with mean squared error:

L(β)=1n∥Xβ−y∥2L(\beta) = \frac{1}{n}\lVert X\beta - y \rVert^2

Differentiate with respect to β\beta:

∇βL=2nX⊤(Xβ−y)\nabla_\beta L = \frac{2}{n} X^\top (X\beta - y)

That is the entire derivation. Now the whole algorithm, with no library beyond NumPy:

import numpy as np

rng = np.random.default_rng(0)
n, d = 500, 3
X = np.column_stack([np.ones(n), rng.normal(size=(n, d))])   # bias + features
true_beta = np.array([2.0, -1.5, 0.7, 3.1])
y = X @ true_beta + rng.normal(0, 0.5, n)

def fit(X, y, lr=0.1, steps=500):
    beta = np.zeros(X.shape[1])
    history = []
    for _ in range(steps):
        residual = X @ beta - y
        loss = (residual ** 2).mean()
        grad = 2 / len(y) * X.T @ residual
        beta -= lr * grad
        history.append(loss)
    return beta, np.array(history)

beta, history = fit(X, y)
closed_form = np.linalg.lstsq(X, y, rcond=None)[0]

print("gradient descent", np.round(beta, 3))
print("closed form     ", np.round(closed_form, 3))
print("final loss      ", round(history[-1], 5))
gradient descent [ 1.98  -1.53   0.681  3.117]
closed form      [ 1.98  -1.53   0.681  3.117]
final loss       0.24216

Same answer to three decimals. The iterative method found what the algebra found, without ever inverting a matrix.

The learning rate is the whole game

Change one number and watch three completely different behaviours:

for lr in [0.001, 0.1, 0.6, 1.1]:
    _, h = fit(X, y, lr=lr, steps=200)
    print(f"lr={lr:<6} final loss {h[-1]:.4g}")
lr=0.001  final loss 2.317      # too small: still crawling downhill
lr=0.1    final loss 0.2422     # good
lr=0.6    final loss 0.2422     # still fine, gets there faster
lr=1.1    final loss 1.3e+81    # diverged

At α=1.1\alpha = 1.1 the step overshoots the minimum, lands somewhere with a steeper slope, takes a bigger step, and explodes. That is the nan in your training log, and it is not mysterious - it is a step longer than the curvature of the surface tolerates. For this quadratic loss the stability threshold is α<2/λmax⁡\alpha < 2/\lambda_{\max}, where λmax⁡\lambda_{\max} is the largest eigenvalue of 2nX⊤X\frac{2}{n}X^\top X. This is one of the places where linear algebra pays you back directly.

The other detail visible here: features on wildly different scales make λmax⁡\lambda_{\max} large and force a tiny learning rate. That is the real reason everyone standardises features - not superstition, but conditioning.

Where is it actually used?

  • Every neural network ever trained. Backpropagation is the chain rule computing ∇θL\nabla_\theta L efficiently; the update above is what consumes it.
  • Stochastic gradient descent. Computing the gradient on all nn rows is expensive, so use a random mini-batch. The gradient becomes noisy but each step is far cheaper, and the noise turns out to help escape bad regions.
  • Adam, RMSProp, momentum. All variations on the same line, adapting α\alpha per parameter or smoothing the gradient over time. Understand the plain version and the rest are small deltas.
  • Logistic regression, matrix factorisation, portfolio optimisation - anywhere with a differentiable objective and too many parameters for exact algebra.

Going deeper

  • Rewrite the code above for logistic regression: change the loss to cross-entropy and derive the gradient yourself. It comes out remarkably clean, and deriving it once is worth more than reading it ten times.
  • Then implement momentum and watch how it handles a poorly conditioned problem the plain version struggles with.

Sources

  • Mathematics for Machine Learning - Deisenroth, Faisal, Ong, ch. 7
  • Karpathy - Neural Networks: Zero to Hero, lecture 1
Found an error in this?

Use the contact and involvement page to find the current ways to share a correction. Corrections are credited on the page - they are the most welcome messages I get.

Previous note

Why random train/test splits ruin financial time series

A shuffled split lets your model see the future. It does not fail loudly - it hands you an excellent score for a model that is worthless.