What is optimization for learning#
Every machine learning model, whether a linear regressor, a decision tree, or a transformer with billions of parameters, starts from the same template: choose a model parameterised by a vector , measure how wrong it is with a loss , and average that loss over a dataset of examples. The result is the objective function (also called the cost or the empirical risk):
"Training" the model means finding the that makes as small as possible:
This is exactly an optimization problem. The machinery of this course, covering convexity, gradient methods, and convergence rates, exists to solve equation efficiently and reliably for machine learning objectives.
Setting the derivative to zero yields a closed-form solution for a linear model with squared error loss (Week 4). For most modern models, such as deep nets, tree ensembles, and generative models, is a nonconvex function of millions of parameters without a closed form. The practical route is to start somewhere and take small steps downhill.
Empirical risk minimization#
The name ERM captures the idea: we empirically measure risk on the data we have, then minimise it. Two things matter:
- The loss encodes what "wrong" means. For regression, (squared error). For classification, is cross-entropy (Week 5).
- The data is a finite sample from some unknown distribution. ERM minimises the average on this sample, hoping it generalises to the distribution.
The rest of this course focuses on the minimisation part. The generalisation part (why minimising training loss also minimises test loss) belongs to statistical learning theory, though we will touch it when we discuss overparameterisation in Week 13.
Worked example: linear regression as ERM.
Take , model , and squared error loss . Then
where stacks the as rows and stacks the labels. This is a convex quadratic in , one of the simplest ERM problems. Weeks 3 and 4 build on this form.
Gradients and the chain rule#
To take steps downhill, we need to know which direction is down. For a scalar-valued function , the gradient is the vector of partial derivatives:
At any point , points in the direction of steepest ascent. So points downhill.
The chain rule for vector functions is the workhorse of modern ML. Suppose where and . Then
where is the Jacobian of (row holds the gradient of the -th output component).
Worked numeric example: quadratic gradient.
Let . The gradient is
At , we have . The function is steeper in the direction.
Chain rule worked example: linear regression gradient.
With , let (the residual). Then . By the chain rule:
For a single data point , we get , which is a scalar times the feature vector. This simple form makes SGD (Week 6) cheap per example.
Gradient descent#
The gradient descent algorithm is wonderfully simple: start at , then repeatedly move a small step in the negative gradient direction:
where is the step size (also called the learning rate).
Choosing is the central tuning problem. Too small and you crawl toward the minimum (underfitting in training-budget terms). Too large and you overshoot, possibly diverging.
Worked manual iteration: 2D quadratic.
Take with gradient . Start at with .
- : , gradient
- Step:
- : gradient at is
- Step:
The objective values: , , . The minimum is , and we're getting closer every step.
Notice that shrinks faster than because its gradient component is twice as large. This direction-dependent convergence speed is a preview of the condition-number story in Week 4.
GD takes steps opposite the gradient, so iterates march downhill across the contours of and settle at the minimum. The path is not straight when the contours are elongated, illustrating the conditioning problem of Week 4.
Reading loss curves#
Plot against iteration . A healthy GD run shows a smooth, monotonically decreasing curve that flattens as it approaches the minimum:
- Smooth decrease: The step size is working; the gradient is driving consistent progress.
- Plateau: The curve is nearly flat. Either the gradient is very small (you're near the minimum) or the step size is too conservative.
- Oscillation: The curve bounces up and down. The step size may be too large, overshooting the valley floor each iteration.
- Divergence: The curve rises steadily. is far too large; the descent lemma (Week 3) is violated.
A useful diagnostic: if the loss drops quickly for the first few iterations then plateaus far from zero, you may be stuck in a shallow region. Try increasing slightly or adding momentum (Week 7).
Knowledge Check#
Given f(x) = 3x², compute ∇f(2) as a scalar value.
Empirical Risk Minimisation minimises the ___ loss over the training dataset.
Browser lab: gradient descent on a 2D quadratic#
Perform gradient descent on a 2D quadratic and visualise the iterate trajectory overlaid on the loss contour.
import numpy as np
import matplotlib.pyplot as plt
def f(x, y):
return 0.5 * (x**2 + 2 * y**2)
def grad(x, y):
return np.array([x, 2 * y])
eta = 0.3
n_steps = 12
xy = np.array([4.0, 4.0])
path = [xy.copy()]
for _ in range(n_steps):
xy = xy - eta * grad(*xy)
path.append(xy.copy())
path = np.array(path)
xs = np.linspace(-5, 5, 200)
ys = np.linspace(-5, 5, 200)
X, Y = np.meshgrid(xs, ys)
Z = f(X, Y)
fig, ax = plt.subplots(figsize=(6, 5))
ax.contour(X, Y, Z, levels=20, cmap="viridis", alpha=0.7)
ax.plot(path[:, 0], path[:, 1], "o-", color="tab:red", markersize=4, label="GD iterates")
ax.plot(0, 0, "x", color="black", markersize=10, label="optimum (0,0)")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title(f"GD with η={eta} on f(x,y) = ½(x² + 2y²)")
ax.legend()
ax.set_aspect("equal")
plt.show()
print("Final position:", path[-1])
print("Final loss:", f(*path[-1]))
print("Notice: the iterates march downhill and settle at the optimum (0, 0) — final loss ≈ 0.")
Key takeaways#
- Supervised learning is empirical risk minimization: pick a model, pick a loss, minimize the average loss over the sample.
- The gradient points uphill; gradient descent steps opposite it, .
- The chain rule makes this practical: for the gradient is , and for one example it is a scalar error times the feature vector, making SGD cheap.
- The step size is the central tuning knob: too small and you crawl, too large and you overshoot or diverge.
- The loss curve is a live diagnostic: smooth decrease is healthy, oscillation means is too large, a steady rise means it is far too large, and a plateau can mean either a shallow region or a step size that is too conservative.
- Faster shrinkage in one coordinate than another is the first sign of ill-conditioning, which Week 4 makes precise.
Further reading#
- Stephen Boyd & Lieven Vandenberghe, Convex Optimization (Cambridge University Press, 2004). Chapter 1 frames the optimisation problem and §9.1 covers descent methods. Freely available at stanford.edu/~boyd/cvxbook.
- Ian Goodfellow, Yoshua Bengio & Aaron Courville, Deep Learning (MIT Press, 2016). Chapter 4 reviews the calculus and Chapter 8 develops optimisation for training deep models.
- Jorge Nocedal & Stephen Wright, Numerical Optimization (2nd ed., Springer, 2006). Chapter 3 covers line search and steepest-descent methods.
Reading is free. PDF and ePub unlock with the newsletter. Join once and every lesson opens in this browser.