12 Optimisation in ML

12.1 Optimisation Formulations

In machine learning, the goal is always to find the best set of parameters ww for a model. "Best" means the model performs as well as possible, and can be formally defined as an optimisation problem, specifically minimising or maximising some objective function.
4 main ways.

12.1.0.1 Empirical Loss Minimisation

Given a dataset of nn training examples (xi,yix_i, y_i), we want to find parameters ww that minimise the average loss over all examples. minw{1n∑i=1nℓ(hw(xi),yi)}\min_w \left\{ \frac{1}{n} \sum_{i=1}^{n} \ell(h_w(x_i), y_i) \right\} For example, in linear regression, hw(x)=wTxh_w(x)=w^T x and the loss is squared error ℓ(ŷ,y)=(ŷ−y)2\ell(\hat{y},y)=(\hat{y}-y)^2.

12.1.0.2 Regularised Empirical Loss Minimisation

Regularisation aims to prevent overfitting. minw{1n∑i=1nℓ(hw(xi),yi)+λ2∥w∥2}\min_w \left\{ \frac{1}{n} \sum_{i=1}^{n} \ell(h_w(x_i), y_i) + \frac{\lambda}{2} \|w\|^2 \right\} Regularisation term λ2∥w∥2\frac{\lambda}{2} \|w\|^2 aims to keep the weights small, making the model simpler.
This is also called L2 regularisation (taking squared of weights).

12.1.0.3 Maximum Likelihood Estimation

This is now from a probabilistic perspective: finding the parameters that make the observed data most probable. maxθ∈Θ{∑i=1nlogpθ(Xi)}\max_{\theta \in \Theta} \left\{ \sum_{i=1}^{n} \log p_\theta(X_i) \right\}

12.1.0.4 Maximum a Posteriori (MAP) Estimation

MLE only uses the data. MAP includes any prior beliefs about what the parameters should look like, before seeing any data. maxθ∈Θ{∑i=1nlogp(Xi|θ)+logp(θ)}\max_{\theta \in \Theta} \left\{ \sum_{i=1}^{n} \log p(X_i | \theta) + \log p(\theta) \right\} The log-prior term log⁡p(θ)\log p(\theta) encodes belief about θ\theta.
If the prior is Gaussian (p(θ)=𝒩(0,σ2)p(\theta) = \mathcal{N}(0,\sigma^2)), then log⁡p(θ)∝−∥θ∥2\log p(\theta) \propto -\|\theta\|^2. MAP then becomes identical to regularised ERM. Hence L2 regularisation is equivalent to placing a Gaussian prior on the parameters.

12.2 Mathematical Properties of Functions

12.2.1 Lipschitz smoothness

Describes how quickly the gradient can change.
ϕ:ℝd→ℝ\phi: \mathbb{R}^d \to \mathbb{R} is LL-smooth if ϕ\phi is differentiable and its gradient ∇ϕ\nabla\phi is LL-Lipschitz continuous: ∥∇ϕ(w)−∇ϕ(w′)∥≤L∥w−w′∥,∀w,w′∈ℝd\|\nabla\phi(w) - \nabla\phi(w')\| \leq L\|w - w'\|, \quad \forall w, w' \in \mathbb{R}^d This means if you move a little in parameter space from ww to w′w', the gradient cannot change by more than LL times that distance. The gradient is not allowed to change abruptly.

Note: ∇\nabla is the gradient operator. It collects all the partial derivatives of a function into a vector. If w=(w1,w2,…,wd)w = (w_1, w_2, \ldots, w_d), then ∇ϕ(w)=(∂ϕ∂w1∂ϕ∂w2⋮∂ϕ∂wd)\nabla\phi(w) = \begin{pmatrix} \frac{\partial\phi}{\partial w_1} \\ \frac{\partial\phi}{\partial w_2} \\ \vdots \\ \frac{\partial\phi}{\partial w_d} \end{pmatrix} It is a vector that points in the direction of steepest increase of ϕ\phi at the point ww. In 1D, ∇ϕ(w)\nabla\phi(w) is just the ordinary derivative ϕ′(w)\phi'(w).

12.2.1.1 Sufficient condition

A way to verify LL-smoothness is through the Hessian (the matrix of second derivatives): ∇2ϕ(w)≼LIdfor any w\nabla^2\phi(w) \preceq LI_d \quad \text{for any } w ∇2ϕ(w)\nabla^2\phi(w) is the Hessian, the matrix of second derivatives. It shows how fast the gradient is changing at ww. ∇2ϕ(w)=(∂2ϕ∂w12∂2ϕ∂w1∂w2⋯∂2ϕ∂w2∂w1∂2ϕ∂w22⋯⋮⋱)\nabla^2\phi(w) = \begin{pmatrix} \frac{\partial^2\phi}{\partial w_1^2} & \frac{\partial^2\phi}{\partial w_1 \partial w_2} & \cdots \\ \frac{\partial^2\phi}{\partial w_2 \partial w_1} & \frac{\partial^2\phi}{\partial w_2^2} & \cdots \\ \vdots & & \ddots \end{pmatrix} In 1D, the Hessian is just the second derivative ϕ″(w)\phi''(w).
The ≼\preceq means the matrix inequality - all eigenvalues of ∇2ϕ(w)\nabla^2\phi(w) are at most LL. This bounds how curved the function can be in any direction.
In 1D, for ϕ(w)=w2\phi(w)=w^2, the Hessian is just the scalar ϕ″(w)=2\phi''(w)=2. The single eigenvalue is 2. So the function is LL-smooth with L=2L=2.

12.2.1.2 Key inequality

If ϕ\phi is LL-smooth, then for any ww, w′w': |ϕ(w′)−ϕ(w)−∇ϕ(w)⊤(w′−w)|≤L2∥w′−w∥2|\phi(w') - \phi(w) - \nabla\phi(w)^\top(w' - w)| \leq \frac{L}{2}\|w' - w\|^2 The first-order Taylor approximation of ϕ\phi at point ww is: ϕ(w′)≈ϕ(w)+∇ϕ(w)⊤(w′−w)\phi(w')\approx \phi(w) + \nabla\phi(w)^\top(w' - w) where ∇ϕ(w)⊤(w′−w)\nabla\phi(w)^\top(w' - w) is a dot product, it measures how much the function is expected to change as you move from ww to w′w', based on the gradient at ww alone.
The true value ϕ(w′)\phi(w') and the approximation ϕ(w)+∇ϕ(w)⊤(w′−w)\phi(w) + \nabla\phi(w)^\top(w' - w) are not exactly. So the left side of the inequality is exactly the error of the tangent approximation — how far off the linear approximation is from the true value.
This error is at most L2∥w′−w∥2\frac{L}{2}\|w' - w\|^2. The function is sandwiched within a quadratic bowl around the tangent plane.
This inequality is what lets us prove each GD step reduces the objective. How much the function changes per step can be bound.

12.2.2 Strong convexity

ϕ:ℝd→ℝ\phi:\mathbb{R}^d\to\mathbb{R} is μ\mu-strongly convex if: ϕ(w′)≥ϕ(w)+∇ϕ(w)⊤(w′−w)+μ2∥w′−w∥2,∀w,w′∈ℝd\phi(w') \geq \phi(w) + \nabla\phi(w)^\top(w' - w) + \frac{\mu}{2}\|w' - w\|^2, \quad \forall w, w' \in \mathbb{R}^d Comparing to the smoothness inequality: While smoothness gives an upper bound (the function doesn’t grow faster than a quadratic), strong convexity gives a lower bound (the function grows at least as fast as a quadratic).
Together, smoothness and strong convexity sandwich the function between two parabolas, which is what makes optimization tractable and fast.
This also means the function curves upward everywhere, and it curves upward by at least μ\mu. This guarantees a unique global minimum exists, and the function does not have flat regions or saddle points to get stuck in.

12.2.2.1 Sufficient condition

∇2ϕ(w)≽μIdfor any w\nabla^2\phi(w) \succeq \mu I_d \quad \text{for any } w All eigenvalues of the Hessian are at least μ>0\mu > 0 everywhere. The function is uniformly curved upward in every direction.

12.2.2.2 The PL-Condition (Polyak-Łojasiewicz)

From the strong convexity definition, we can derive the PL-condition: ∥∇ϕ(w)∥2≥2μ(ϕ(w)−minwϕ(w))\|\nabla\phi(w)\|^2 \geq 2\mu\left(\phi(w) - \min_w \phi(w)\right) This means the gradient norm squared is always at least 2μ2\mu times the suboptimality gap.

This rules out the gradient vanishing before you reach the minimum, which is what guarantees convergence.

Taking LL-smoothness and μ\mu-strong convexity together, μId≼∇2ϕ(w)≼LId\mu I_d \preceq \nabla^2 \phi(w) \preceq LI_d The function is squeezed between two parabolas with curvatures μ\mu and LL.
This leads to the condition number: κ=Lμ\kappa = \frac{L}{\mu}

12.3 Gradient descent

12.3.1 The update rule

Gradient descent generates a sequence of parameters starting from some initial point w0w_0: wt+1=wt−ηt∇F(wt)w_{t+1} = w_t - \eta_t \nabla F(w_t)

Why negative gradient direction? ddtF(w−t∇F(w))|t=0=−∥∇F(w)∥2\frac{d}{dt}F(w - t\nabla F(w))\bigg|_{t=0} = -\|\nabla F(w)\|^2 If we start a point ww and move in the direction −∇F(w)-\nabla F(w) by a tiny amount tt, the LHS measures the rate of change of FF as we move in that direction. The result is the RHS, which is always negative. This formally proves that moving in the negative gradient direction always locally decreases the objective.
The gradient is orthogonal to the contour.
A contour (level set) is a curve along which the function value stays constant. The negative gradient therefore points directly inward, toward lower contours, which is exactly the direction GD moves.

12.3.1.1 Optimisation complexity

We need to define how fast the convergence is.
Iteration complexity is the number of steps tt needed so that F(wt)−F(w*)≤ϵF(w_t) - F(w_*) \leq \epsilon This is also the suboptimality gap. We want to know how many iterations until this gap is smaller than our required accuracy ϵ\epsilon.

12.3.1.2 Convergence rate of GD

Using the Lipschitz smoothness and PL-condition, we get the following key results.

  1. Guaranteed decrease per step
    Each step size is η=1L\eta = \frac{1}{L} Then F(wt+1)≤F(wt)−12L∥∇F(wt)∥2F(w_{t+1}) \leq F(w_t) - \frac{1}{2L}\|\nabla F(w_t)\|^2 Each step decreases the objective by at least 12L∥∇F(wt)∥2\frac{1}{2L}\|\nabla F(w_t)\|^2. The smoother the function (larger LL), the more cautiously GD must step, so the smaller the guaranteed decrease per step.

  2. Exponential shrinking of the gap F(wT)−F(w*)≤(1−μL)T(F(w0)−F(w*))F(w_T) - F(w_*) \leq \left(1 - \frac{\mu}{L}\right)^T(F(w_0) - F(w_*)) The suboptimality gap shrinks exponentially with each step. The factor (1−μL)(1 - \frac{\mu}{L}) is always between 0 and 1, so repeated multiplication (to the power of TT) drives the gap to zero.

  3. Iteration complexity T≥Lμlog⁡F(w0)−F(w*)ϵT \geq \frac{L}{\mu}\log\frac{F(w_0) - F(w_*)}{\epsilon} At least TT number of steps are needed to guarantee the suboptimality gap is below ϵ\epsilon. F(w0)−F(w*)F(w_0) - F(w_*) is just a constant. O(κlog1ϵ)O\left(\kappa \log\frac{1}{\epsilon}\right) 2 things control how many steps GD needs:

    1. The log⁡1ϵ\log\frac{1}{\epsilon} is favourable: getting 10x more accurate only costs a fixed number of extra steps.

    2. The κ=Lμ\kappa = \frac{L}{\mu} is a bottleneck: A large condition number means the landscape is poorly shaped (steep in some directions, flat in others). GD might struggle here.

    Both LL and μ\mu are properties of the problem itself.

12.4 Scaling problem with GD on large datasets

GD has a practical problem when applied to machine learning with large datasets.
The empirical risk minimisation for GD: minw∈ℝd{F(w)=1n∑i=1nfi(w)}\min_{w \in \mathbb{R}^d} \left\{ F(w) = \frac{1}{n}\sum_{i=1}^{n} f_i(w) \right\} where each fi(w)f_i(w) is the loss on a single training example ii. The total objective F(w)F(w) is an average over all nn training examples. This is called a finite sum problem.
However, in the GD update rule we need the gradient of F(w)F(w). Taking the gradient of the finite sum: ∇F(w)=1n∑i=1n∇fi(w)\nabla F(w) = \frac{1}{n}\sum_{i=1}^{n} \nabla f_i(w) To compute this, we must compute ∇fi(w)\nabla f_i(w) for every single data point i=1,2,…,ni = 1, 2, \ldots, n, then average them. Every single GD step requires a full pass through the entire dataset.
Hence GD is computationally expensive as the cost per step grows directly with dataset size nn.

12.4.0.1 Two complexity measures

We saw iteration complexity: the number of GD steps to achieve ϵ\epsilon-error: O(κlog1ϵ)O\left(\kappa\log\frac{1}{\epsilon}\right) This does not depend on nn, only counts steps.
There is also total complexity: total number of accesses to individual component gradients ∇fi\nabla f_i to achieve ϵ\epsilon-error: O(nκlog1ϵ)O\left(n\kappa\log\frac{1}{\epsilon}\right) This scales with nn because each GD step requires computing nn individual gradients.

12.5 Stochastic Gradient Descent (SGD)

SGD vs GD
SGD vs GD error

SGD is the direct solution to the scaling problem of GD. Instead of computing the gradient over all nn data points at every step, SGD approximates the gradient using just one randomly picked data point per step. This makes each step nn times cheaper.
The standard GD update step is: wt+1=wt−ηt∇F(wt)w_{t+1} = w_t - \eta_t \nabla F(w_t) Now the SGD update is: wt+1=wt−ηt∇fit(wt),it∼Uniform{1,2,…,n}w_{t+1} = w_t - \eta_t \nabla f_{i_t}(w_t), \quad i_t \sim \text{Uniform}\{1, 2, \dots, n\} The only difference is that SGD uses one randomly sampled gradient instead of the average of all nn gradients.
The stochastic gradient is a valid substitute for the full gradient because it is an unbiased estimator of it: 𝔼it[∇fit(wt)]=∇F(wt)\mathbb{E}_{i_t}[\nabla f_{i_t}(w_t)] = \nabla F(w_t) Since iti_t is drawn uniformly from {1,2,…,n}\{1,2,\ldots,n\}, the expected value of any single ∇fit(wt)\nabla f_{i_t}(w_t) is exactly the average over all nn gradients, which is ∇F(wt)\nabla F(w_t). So SGD is the same as GD in expectation at every step: 𝔼it[wt+1]=wt−ηt∇F(wt)\mathbb{E}_{i_t}[w_{t+1}] = w_t - \eta_t \nabla F(w_t) This means on average, each SGD step moves in the right direction. Any single step may be noisy and imprecise, but averaged over many steps, SGD heads toward the minimum.

Comparison of complexities

Iteration Complexity Total Complexity
GD SGD GD SGD
Strongly convex O(κlog1ϵ)O\left(\kappa\log\frac{1}{\epsilon}\right) Õ(κlog1ϵ+κσ2μϵ)\tilde{O}\left(\kappa\log\frac{1}{\epsilon} + \frac{\kappa\sigma^2}{\mu\epsilon}\right) O(nκlog1ϵ)O\left(n\kappa\log\frac{1}{\epsilon}\right) Õ(κlog1ϵ+κσ2μϵ)\tilde{O}\left(\kappa\log\frac{1}{\epsilon} + \frac{\kappa\sigma^2}{\mu\epsilon}\right)



For GD, each step accesses all nn components, so the total complexity (GD) is the iteration complexity (GD) times n.
For SGD, each step only accesses 1 component, so the total complexity (SGD) = iteration complexity (SGD).
SGD iteration complexity: Õ(κlog1ϵ+κσ2μϵ)\tilde{O}\left(\kappa\log\frac{1}{\epsilon} + \frac{\kappa\sigma^2}{\mu\epsilon}\right) SGD needs more iterations than GD because each step is noisy. There are two terms:

  1. κlog⁡1ϵ\kappa \log \frac{1}{\epsilon}: same as GD, this is the base number of steps needed.

  2. κσ2μϵ\frac{\kappa \sigma^2}{\mu \epsilon}: extra steps needed because of the noise from using only one gradient per step. σ2\sigma^2 measures how different individual gradients ∇fi(w)\nabla f_i(w) are from each other. If individual gradients vary widly, t he higher the variance σ2\sigma^2, the noisier the steps, hence more steps SGD needs to compensate.

For large nn, SGD’s total complexity is free of nn, compared to GD’s total complexity which scales with nn. SGD can perform nn steps for the same cost as one GD step, so even though each SGD step is noisier and less accurate, the sheer volume of steps compensates. SGD is the standard method in large scale machine learning.

Step size
The step size for GD was simply η=1L\eta = \frac{1}{L}.
The step size for SGD is more carefully chosen: η=min⁡{μϵLσ2,1L}\eta = \min\left\{\frac{\mu\epsilon}{L\sigma^2}, \frac{1}{L}\right\} The extra term to consider keeps the step size small enough to control the noise from the variance σ2\sigma^2. The noisier the gradients, the smaller the step must be to prevent SGD from bouncing around and overshooting.
So SGD needs to consider gradient noise in addition to smoothness when choosing step size.
Note that Õ\tilde{O} is used for SGD as the exact complexity involves some hidden logaorithmic factors, but is basically the same as OO.

13 Sampling

13.1 Monte-Carlo Integration

Under sampling, we want to estimate expectations of functions under some probability distribution.
Given a probability distribution pp and a function ff, we want to compute: 𝔼X∼p[f(X)]=∫f(x)p(x)dx\mathbb{E}_{X \sim p}[f(X)] = \int f(x)p(x)dx i.e. the values of f(x)f(x) weighted by how probable each xx is.
However, this integral is often intractable, meaning there is no closed form solution. pp may be too complex or the integral may be over a very high-dimensional space when standard numerical integration becomes computationally impossible.

Monte-Carlo integration approximates the integral using random samples.

If x1,…,xMx_1,\ldots,x_M are i.i.d, samples from pp, then by Law of Large Numbers, the sample average converges to the true expectation as M→∞M\to\infty. 1M∑i=1Mf(xi)→M→∞𝔼X∼p[f(X)]\frac{1}{M}\sum_{i=1}^{M} f(x_i) \xrightarrow{M \to \infty} \mathbb{E}_{X \sim p}[f(X)] The approximation error shrinks to zero with more samples.

The Monte-Carlo integration sounds simple, but the requirement is that we must be able to draw samples from p(x)p(x). In practice this may be hard because:

13.2 Bayesian Regression

Bayesian regression is a probabilistic approach to regression. Unlike standard regression which finds a single best set of parameters, Bayesian regression maintains a full probability distribution over parameters. This allows it to express uncertainty in its predictions, which is very useful in practice.
Posterior distribution
After observing training inputs 𝑿\mathbf{X}, the training data (outputs) 𝒚\mathbf{y} we update our belief about ww using Bayes’ theorem: p(w|𝒚)∝p(𝒚|w,𝑿)p(w)=∏i=1np(yi|xi,w)p(w)p(w|\mathbf{y}) \propto p(\mathbf{y}|w, \mathbf{X})p(w) = \prod_{i=1}^{n} p(y_i|x_i, w)p(w) The posterior p(w|𝒚)p(w|\mathbf{y}) combines the likelihood ∏i=1np(yi|xi,w)\prod_{i=1}^{n} p(y_i|x_i, w) of nn independent training examples and the prior p(w)p(w).
Predictive distribution
Given a new input xx, we want to predict new output yy. Instead of plugging in the best ww like in standard regression, we need to average the prediction over all possible values of ww, weighted by how probable each ww is under the posterior: p(y|𝒚,x)=∫p(y|w,x)p(w|𝒚)dwp(y|\mathbf{y}, x) = \int p(y|w, x)p(w|\mathbf{y})dw This is an expection of p(y|w,x)p(y|w,x) under the posterior distribution p(w|𝒚)p(w|\mathbf{y}).
Monte-Carlo approximates the predictive distribution integral above by drawing samples w1,…,wMw_1,\ldots, w_M from the posterior p(w|𝒚)p(w|\mathbf{y}) and averaging: 1M∑i=1Mp(y|wi,x)≈p(y|𝒚,x)\frac{1}{M}\sum_{i=1}^{M} p(y|w_i, x) \approx p(y|\mathbf{y}, x)

13.3 Langevin Monte-Carlo (LMC)

So we need to draw samples from the posterior p(w|𝒚)p(w|\mathbf{y}) to approximate the predictive distribution, but the posterior is too complex to sample from directly. LMC algorithm is a gradient-based sampling method, that constructs a sequence of points that gradually converges to the target distribution. Recall that the update step for GD is: wt+1=wt−η∇F(wt)w_{t+1} = w_t - \eta\nabla F(w_t) The LMC update is: wt+1=wt+η∇log⁡p(wt)+2ηξk,ξk∼𝒩(0,Id)w_{t+1} = w_t + \eta\nabla\log p(w_t) + \sqrt{2\eta}\xi_k, \quad \xi_k \sim \mathcal{N}(0, I_d) The gradient term (η∇log⁡p(wt)\eta\nabla\log p(w_t)) is positive, because we want to maximise the log probability, moving towards regions of high probability.
There is an extra noise term 2ηξk\sqrt{2\eta}\xi_k, which is a random Gaussian pertubation added at every step.

2 issues with LMC:

  1. Burn-in period: The sequence w0,w1,…w_0, w_1, \ldots starts from some arbitrary point w0w_0, which is likely far from the target distribution. The early particles are therefore not representative samples - they are just the algorithm finding its way toward the high probability region.
    The burn-in period is the initial phase of the chain that we discard. Only after burn-in do the particles start resembling samples from the true distribution.

  2. Sample correlation: Consecutive samples wtw_t and wt+1w_{t+1} are highly correlated because each step only moves a small distance. Using correlated samples defeats the purpose of Monte-Carlo: we need approximately independent samples for the average to be accurate.
    The solution is thinning: we run the chain for many steps but only retain every kk-th sample, discarding the intermediate ones. This reduces correlation between retained samples.

Note: LMC draws samples w0,w1,…w_0, w_1, \ldots from p(x)p(x) when we cannot sample directly, and MC integration then uses those to approximate some intractable integral.
In the context of Bayesian regression, LMC draws samples from the posterior p(w|𝒚)p(w|\mathbf{y}), and MC integration approximates the predictive distribution p(y|𝒚,x)p(y|\mathbf{y},x).

13.4 Bayesian Inference with LMC

To perform Bayesian Inference, the LMC update rule becomes: wt+1=wt+η∇logp(wt|y)+2ηξkw_{t+1}=w_{t}+\eta\nabla log~p(w_{t}|y)+\sqrt{2\eta}\xi_{k} where the gradient of the log posterior is: ∇logp(wt|y)=Σi=1N∇logp(yi|xi,w)+∇logp(w)\nabla log~p(w_{t}|y)=\Sigma_{i=1}^{N}\nabla~log~p(y_{i}|x_{i},w)+\nabla~log~p(w) The posterior distribution p(w|y)p(w|y) is the target PDF pp. We want to sample from this posterior distribution.

These two terms together balance fitting the data and staying close to the prior, which is the same tension as regularised ERM.