What Is Optimization for Learning#
Every machine learning model — whether a linear regressor, a decision tree, or a billion-parameter transformer — 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 entire machinery of this course — convexity, gradient methods, convergence rates — exists to solve equation efficiently and reliably for the kinds of objectives that appear in machine learning.
Why not just set the derivative to zero and solve? For a linear model with squared error loss, you can (that is Week 4's closed-form solution). But for most modern models — deep nets, tree ensembles, generative models — is a complicated, nonconvex function of millions of parameters. There is no closed form. The only practical route is to start somewhere and take small steps downhill.
Empirical Risk Minimization#
The name ERMEmpirical Risk Minimization 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 nicest possible ERM problems. We will exploit that niceness in Weeks 3–4.
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 .
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 — a scalar times the feature vector. This simple form is why SGD (Week 6) is 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.
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 — you're 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).
Given $f(x) = 3x^2$, compute $\nabla f(2)$ as a scalar value.
Empirical Risk Minimisation minimises the ___ loss over the training dataset.
Browser lab#
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]))