Skip to main content
© 2026 ePowerAI. All rights reserved.
CoursesContact
eAI
CoursesContact
Week 1: Optimization for Learning
Optimization
01Week 1: Optimization for Learning
02Week 2: Convex Sets and Functions
03Week 3: Gradient Descent Theory
04Week 4: Least Squares and Conditioning
05Week 5: Classification Losses
06Week 6: Stochastic Gradient Descent
07Week 7: Momentum and Acceleration
08Week 8: Adaptive First-Order Methods
09Week 9: Practical Training Dynamics
10Week 10: Nonsmooth and Composite Objectives
11Week 11: Constraints: Projections and Penalties
12Week 12: Duality for Practitioners
13Week 13: Nonconvex Deep Learning
14Week 14: Capstone — Theory Meets Training
Week 01· Optimization· Foundations22 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 billion-parameter transformer — 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 entire machinery of this course — convexity, gradient methods, convergence rates — exists to solve equation (∗)(\ast)(∗) 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 — J(θ)J(\theta)J(θ) 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:

  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 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 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 d×pd \times pd×p Jacobian of hhh.

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​ — 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 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.

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 — you're 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).

Exercise · Fill in the blank

Given $f(x) = 3x^2$, compute $\nabla f(2)$ as a scalar value.

Question 1 of 4

Empirical Risk Minimisation minimises the ___ loss over the training dataset.

Browser lab#

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]))
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
  • Browser lab