What is it?
You have a function that measures how wrong you are - a loss - and you want the parameters that make it small. Gradient descent is the simplest thing that works: compute the slope, step downhill, repeat.
is the gradient: the vector of partial derivatives, pointing in the direction of steepest increase. Subtracting it goes downhill. is the learning rate, the length of the step.
Why does it exist?
Some problems have a closed-form solution. Linear regression does:
Exact, one shot, no iteration. So why iterate at all? Three reasons:
- Most losses have no closed form. The moment you add a non-linearity, the equation you would need to solve has no algebraic solution.
- The closed form does not scale. Inverting costs roughly in the number of features. At that is not a computation you run.
- 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, , with mean squared error:
Differentiate with respect to :
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 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 , where is the largest eigenvalue of . This is one of the places where linear algebra pays you back directly.
The other detail visible here: features on wildly different scales make 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 efficiently; the update above is what consumes it.
- Stochastic gradient descent. Computing the gradient on all 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 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.