Skip to main content
© 2026 ePowerAI — free, open courseware. No login required.
CoursesContact
ePOWERAI
CoursesContact
Week 1: Optimization for Learning
Optimization

Foundations

  1. 01Week 1: Optimization for Learning
  2. 02Week 2: Convex Sets and Functions
  3. 03Week 3: Gradient Descent Theory

Model problems

  1. 04Week 4: Least Squares and Conditioning
  2. 05Week 5: Classification Losses

First-order stack

  1. 06Week 6: Stochastic Gradient Descent
  2. 07Week 7: Momentum and Acceleration
  3. 08Week 8: Adaptive First-Order Methods
  4. 09Week 9: Practical Training Dynamics

Structure

  1. 10Week 10: Nonsmooth and Composite Objectives
  2. 11Week 11: Constraints: Projections and Penalties
  3. 12Week 12: Duality for Practitioners

Nonconvex practice

  1. 13Week 13: Nonconvex Deep Learning
  2. 14Week 14: Capstone — Theory Meets Training
Week 01· Optimization· Foundations9 min read

Week 1: Optimization for Learning

Learning Outcomes
  • Frame supervised learning as empirical risk minimization over a parameter vector
  • Compute gradients using the chain rule and vector-matrix differentiation
  • Write the gradient descent update rule and step through it manually
  • Visualize GD iterates on a 2D loss surface
Prerequisites

Background: Linear Algebra complete (course index). Basic comfort with derivatives and partial derivatives (reviewed in this lesson). No prior optimization experience required.

Later weeks: Every subsequent week builds on the gradient descent mechanics and ERMEmpirical Risk Minimization framing established here.

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 fθf_\thetafθ​ parameterised by a vector θ\thetaθ, measure how wrong it is with a loss ℓ(y^,y)\ell(\hat y, y)ℓ(y^​,y), and average that loss over a dataset of nnn examples. The result is the objective function (also called the cost or the empirical risk):

J(θ)=1n∑i=1nℓ(fθ(xi),yi)J(\theta) = \frac{1}{n} \sum_{i=1}^n \ell(f_\theta(x_i), y_i)J(θ)=n1​∑i=1n​ℓ(fθ​(xi​),yi​)

"Training" the model means finding the θ\thetaθ that makes J(θ)J(\theta)J(θ) as small as possible:

θ∗=arg⁡min⁡θJ(θ)\theta^* = \arg\min_\theta J(\theta)θ∗=argminθ​J(θ)

This is exactly an optimization problem. The machinery of this course, covering convexity, gradient methods, and convergence rates, exists to solve equation (∗)(\ast)(∗) 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, J(θ)J(\theta)J(θ) 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 ERMEmpirical Risk Minimization captures the idea: we empirically measure risk on the data we have, then minimise it. Two things matter:

  1. The loss ℓ(y^,y)\ell(\hat y, y)ℓ(y^​,y) encodes what "wrong" means. For regression, ℓ(y^,y)=(y^−y)2\ell(\hat y, y) = (\hat y - y)^2ℓ(y^​,y)=(y^​−y)2 (squared error). For classification, ℓ\ellℓ is cross-entropy (Week 5).
  2. The data {(xi,yi)}\{(x_i, y_i)\}{(xi​,yi​)} 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 θ=w∈Rd\theta = w \in \mathbb{R}^dθ=w∈Rd, model fw(x)=wTxf_w(x) = w^T xfw​(x)=wTx, and squared error loss ℓ(y^,y)=(y^−y)2\ell(\hat y, y) = (\hat y - y)^2ℓ(y^​,y)=(y^​−y)2. Then

J(w)=1n∑i=1n(wTxi−yi)2=1n∥Xw−y∥22J(w) = \frac{1}{n}\sum_{i=1}^n (w^T x_i - y_i)^2 = \frac{1}{n}\|Xw - y\|_2^2J(w)=n1​∑i=1n​(wTxi​−yi​)2=n1​∥Xw−y∥22​

where X∈Rn×dX \in \mathbb{R}^{n \times d}X∈Rn×d stacks the xix_ixi​ as rows and y∈Rny \in \mathbb{R}^ny∈Rn stacks the labels. This is a convex quadratic in www, 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 f:Rd→Rf: \mathbb{R}^d \to \mathbb{R}f:Rd→R, the gradient ∇f(x)\nabla f(x)∇f(x) is the vector of partial derivatives:

∇f(x)=(∂f∂x1(x)⋮∂f∂xd(x))\nabla f(x) = \begin{pmatrix} \frac{\partial f}{\partial x_1}(x) \\ \vdots \\ \frac{\partial f}{\partial x_d}(x) \end{pmatrix}∇f(x)=​∂x1​∂f​(x)⋮∂xd​∂f​(x)​​

At any point xxx, ∇f(x)\nabla f(x)∇f(x) points in the direction of steepest ascent. So −∇f(x)-\nabla f(x)−∇f(x) points downhill.

The chain rule for vector functions is the workhorse of modern ML. Suppose f(x)=g(h(x))f(x) = g(h(x))f(x)=g(h(x)) where h:Rd→Rph: \mathbb{R}^d \to \mathbb{R}^ph:Rd→Rp and g:Rp→Rg: \mathbb{R}^p \to \mathbb{R}g:Rp→R. Then

∇f(x)=∇h(x)T ∇g(h(x))\nabla f(x) = \nabla h(x)^T \, \nabla g(h(x))∇f(x)=∇h(x)T∇g(h(x))

where ∇h(x)\nabla h(x)∇h(x) is the p×dp \times dp×d Jacobian of hhh (row iii holds the gradient of the iii-th output component).

Worked numeric example: quadratic gradient.

Let f(w)=12(w12+2w22)f(w) = \frac{1}{2}(w_1^2 + 2 w_2^2)f(w)=21​(w12​+2w22​). The gradient is

∇f(w)=(∂f∂w1∂f∂w2)=(w12w2)\nabla f(w) = \begin{pmatrix} \frac{\partial f}{\partial w_1} \\ \frac{\partial f}{\partial w_2} \end{pmatrix} = \begin{pmatrix} w_1 \\ 2 w_2 \end{pmatrix}∇f(w)=(∂w1​∂f​∂w2​∂f​​)=(w1​2w2​​)

At w=(4,4)w = (4, 4)w=(4,4), we have ∇f(4,4)=(4,8)\nabla f(4,4) = (4, 8)∇f(4,4)=(4,8). The function is steeper in the w2w_2w2​ direction.

Chain rule worked example: linear regression gradient.

With f(w)=12∥Xw−y∥22f(w) = \frac{1}{2}\|Xw - y\|_2^2f(w)=21​∥Xw−y∥22​, let r=Xw−yr = Xw - yr=Xw−y (the residual). Then f=12∥r∥22=12rTrf = \frac{1}{2}\|r\|_2^2 = \frac{1}{2}r^T rf=21​∥r∥22​=21​rTr. By the chain rule:

∇f(w)=XT(Xw−y)\nabla f(w) = X^T(Xw - y)∇f(w)=XT(Xw−y)

For a single data point fi(w)=12(wTxi−yi)2f_i(w) = \frac{1}{2}(w^T x_i - y_i)^2fi​(w)=21​(wTxi​−yi​)2, we get ∇fi(w)=(wTxi−yi)xi\nabla f_i(w) = (w^T x_i - y_i) x_i∇fi​(w)=(wTxi​−yi​)xi​, 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 x0x_0x0​, then repeatedly move a small step in the negative gradient direction:

xk+1=xk−η∇f(xk)x_{k+1} = x_k - \eta \nabla f(x_k)xk+1​=xk​−η∇f(xk​)

where η>0\eta > 0η>0 is the step size (also called the learning rate).

Choosing η\etaη 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 f(w1,w2)=12(w12+2w22)f(w_1, w_2) = \frac{1}{2}(w_1^2 + 2 w_2^2)f(w1​,w2​)=21​(w12​+2w22​) with gradient ∇f(w)=(w1,2w2)\nabla f(w) = (w_1, 2w_2)∇f(w)=(w1​,2w2​). Start at w(0)=(4,4)w^{(0)} = (4, 4)w(0)=(4,4) with η=0.3\eta = 0.3η=0.3.

  • k=0k = 0k=0: w(0)=(4,4)w^{(0)} = (4, 4)w(0)=(4,4), gradient =(4,8)= (4, 8)=(4,8)
  • Step: w(1)=(4,4)−0.3⋅(4,8)=(2.8,1.6)w^{(1)} = (4, 4) - 0.3 \cdot (4, 8) = (2.8, 1.6)w(1)=(4,4)−0.3⋅(4,8)=(2.8,1.6)
  • k=1k = 1k=1: gradient at (2.8,1.6)(2.8, 1.6)(2.8,1.6) is (2.8,3.2)(2.8, 3.2)(2.8,3.2)
  • Step: w(2)=(2.8,1.6)−0.3⋅(2.8,3.2)=(1.96,0.64)w^{(2)} = (2.8, 1.6) - 0.3 \cdot (2.8, 3.2) = (1.96, 0.64)w(2)=(2.8,1.6)−0.3⋅(2.8,3.2)=(1.96,0.64)

The objective values: f(4,4)=24f(4,4) = 24f(4,4)=24, f(2.8,1.6)=6.48f(2.8, 1.6) = 6.48f(2.8,1.6)=6.48, f(1.96,0.64)=2.33f(1.96, 0.64) = 2.33f(1.96,0.64)=2.33. The minimum is f(0,0)=0f(0,0) = 0f(0,0)=0, and we're getting closer every step.

Notice that w2w_2w2​ shrinks faster than w1w_1w1​ because its gradient component is twice as large. This direction-dependent convergence speed is a preview of the condition-number story in Week 4.

gradient descent steps downhill, opposite the gradient start minimum contours of f

GD takes steps opposite the gradient, so iterates march downhill across the contours of fff 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 f(xk)f(x_k)f(xk​) against iteration kkk. 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. η\etaη 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 η\etaη slightly or adding momentum (Week 7).

Knowledge Check#

Exercise · Fill in the blank

Given f(x) = 3x², compute ∇f(2) as a scalar value.

Question 1 of 4

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 f(x,y)=x2+2y2f(x,y) = x^2 + 2y^2f(x,y)=x2+2y2 and visualise the iterate trajectory overlaid on the loss contour.

python · runs in browser
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, xk+1=xk−η∇f(xk)x_{k+1} = x_k - \eta \nabla f(x_k)xk+1​=xk​−η∇f(xk​).
  • The chain rule makes this practical: for f(w)=12∥Xw−y∥22f(w) = \frac{1}{2}\|Xw - y\|_2^2f(w)=21​∥Xw−y∥22​ the gradient is XT(Xw−y)X^T(Xw - y)XT(Xw−y), 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 η\etaη 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.

Next →
Week 2: Convex Sets and Functions
On this page
  • What is optimization for learning
  • Empirical risk minimization
  • Gradients and the chain rule
  • Gradient descent
  • Reading loss curves
  • Knowledge Check
  • Browser lab: gradient descent on a 2D quadratic
  • Key takeaways
  • Further reading