12 Optimisation in ML
12.1 Optimisation Formulations
In machine learning, the goal is always to find the best set of
parameters
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 training examples (), we want to find parameters that minimise the average loss over all examples. For example, in linear regression, and the loss is squared error .
12.1.0.2 Regularised Empirical Loss Minimisation
Regularisation aims to prevent overfitting.
Regularisation term
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.
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.
The log-prior term
encodes belief about
.
If the prior is Gaussian
(),
then
.
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.
is
-smooth
if
is differentiable and its gradient
is
-Lipschitz
continuous:
This means if you move a little in parameter space from
to
,
the gradient cannot change by more than
times that distance. The gradient is not allowed to change abruptly.
Small : the gradient changes slowly, the function is very smooth.
Large : the gradient can change faster, the function has sharper features but is still controlled.
Note: is the gradient operator. It collects all the partial derivatives of a function into a vector. If , then It is a vector that points in the direction of steepest increase of at the point . In 1D, is just the ordinary derivative .
12.2.1.1 Sufficient condition
A way to verify
-smoothness
is through the Hessian (the matrix of second derivatives):
is the Hessian, the matrix of second derivatives. It shows how fast the
gradient is changing at
.
In 1D, the Hessian is just the second derivative
.
The
means the matrix inequality - all eigenvalues of
are at most
.
This bounds how curved the function can be in any direction.
In 1D, for
,
the Hessian is just the scalar
.
The single eigenvalue is 2. So the function is
-smooth
with
.
12.2.1.2 Key inequality
If
is
-smooth,
then for any
,
:
The first-order Taylor approximation of
at point
is:
where
is a dot product, it measures how much the function is expected to
change as you move from
to
,
based on the gradient at
alone.
The true value
and the approximation
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
.
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
is
-strongly
convex if:
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
.
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
All eigenvalues of the Hessian are at least 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: This means the gradient norm squared is always at least times the suboptimality gap.
If you are far from the minimum (large suboptimality gap), the gradient is large — GD takes big steps.
If you are close to the minimum (small gap), the gradient is small — but the PL-condition guarantees it is not too small relative to how far you still are.
This rules out the gradient vanishing before you reach the minimum,
which is what guarantees convergence.
Taking
-smoothness
and
-strong
convexity together,
The function is squeezed between two parabolas with curvatures
and
.
This leads to the condition number:
close to 1: the function is nearly spherical, easy to optimize.
very large: the function is elongated and narrow, much harder to optimize (gradient descent zigzags).
12.3 Gradient descent
12.3.1 The update rule
Gradient descent generates a sequence of parameters starting from some initial point :
: current parameter estimate at step .
: gradient at current point, pointing in the direction of steepest increase.
: negative gradient, pointing in the direction of steepest decrease.
: step size (learning rate) at step , controlling how far to move.
Too large : Might overshoot leading to the objective increasing.
Too small: progress too slow, too many steps needed.
Just right : guaranteed decrease of per step.
Hence .
Why negative gradient direction?
If we start a point
and move in the direction
by a tiny amount
,
the LHS measures the rate of change of
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
needed so that
This is also the suboptimality gap. We want to know how many iterations
until this gap is smaller than our required accuracy
.
12.3.1.2 Convergence rate of GD
Using the Lipschitz smoothness and PL-condition, we get the following
key results.
Guaranteed decrease per step
Each step size is Then Each step decreases the objective by at least . The smoother the function (larger ), the more cautiously GD must step, so the smaller the guaranteed decrease per step.
Exponential shrinking of the gap The suboptimality gap shrinks exponentially with each step. The factor is always between 0 and 1, so repeated multiplication (to the power of ) drives the gap to zero.
Iteration complexity At least number of steps are needed to guarantee the suboptimality gap is below . is just a constant. 2 things control how many steps GD needs:
The is favourable: getting 10x more accurate only costs a fixed number of extra steps.
The 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 and 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:
where each
is the loss on a single training example
.
The total objective
is an average over all
training examples. This is called a finite sum problem.
However, in the GD update rule we need the gradient of
.
Taking the gradient of the finite sum:
To compute this, we must compute
for every single data point
,
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
.
12.4.0.1 Two complexity measures
We saw iteration complexity: the number of GD steps to achieve
-error:
This does not depend on
,
only counts steps.
There is also total complexity: total number of accesses to individual
component gradients
to achieve
-error:
This scales with
because each GD step requires computing
individual gradients.
12.5 Stochastic Gradient Descent (SGD)
SGD is the direct solution to the scaling problem of GD. Instead of
computing the gradient over all
data points at every step, SGD approximates the gradient using just one
randomly picked data point per step. This makes each step
times cheaper.
The standard GD update step is:
Now the SGD update is:
The only difference is that SGD uses one randomly sampled gradient
instead of the average of all
gradients.
The stochastic gradient is a valid substitute for the full gradient
because it is an unbiased estimator of it:
Since
is drawn uniformly from
,
the expected value of any single
is exactly the average over all
gradients, which is
.
So SGD is the same as GD in expectation at every step:
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 | ||||
For GD, each step accesses all
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:
SGD needs more iterations than GD because each step is noisy. There are
two terms:
: same as GD, this is the base number of steps needed.
: extra steps needed because of the noise from using only one gradient per step. measures how different individual gradients are from each other. If individual gradients vary widly, t he higher the variance , the noisier the steps, hence more steps SGD needs to compensate.
For large
,
SGD’s total complexity is free of
,
compared to GD’s total complexity which scales with
.
SGD can perform
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
.
The step size for SGD is more carefully chosen:
The extra term to consider keeps the step size small enough to control
the noise from the variance
.
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
is used for SGD as the exact complexity involves some hidden
logaorithmic factors, but is basically the same as
.
13 Sampling
13.1 Monte-Carlo Integration
Under sampling, we want to estimate expectations of functions under
some probability distribution.
Given a probability distribution
and a function
,
we want to compute:
i.e. the values of
weighted by how probable each
is.
However, this integral is often intractable, meaning there is no closed
form solution.
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.
Step 1: Draw random samples from :
Step 2: Approximate the expectation by averaging over the samples:
If
are i.i.d, samples from
,
then by Law of Large Numbers, the sample average converges to the true
expectation as
.
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
.
In practice this may be hard because:
may only be known up to a normalizing constant.
may be a complex high dimensional distribution like a posterior in Bayesian inference.
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
,
the training data (outputs)
we update our belief about
using Bayes’ theorem:
The posterior
combines the likelihood
of
independent training examples and the prior
.
Predictive distribution
Given a new input
,
we want to predict new output
.
Instead of plugging in the best
like in standard regression, we need to average the prediction over all
possible values of
,
weighted by how probable each
is under the posterior:
This is an expection of
under the posterior distribution
.
Monte-Carlo approximates the predictive distribution integral above by
drawing samples
from the posterior
and averaging:
13.3 Langevin Monte-Carlo (LMC)
So we need to draw samples from the posterior
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:
The LMC update is:
The gradient term
()
is positive, because we want to maximise the log probability, moving
towards regions of high probability.
There is an extra noise term
,
which is a random Gaussian pertubation added at every step.
Without the noise term, LMC would just be gradient ascent on , converging to a single point - the mode of the distribution. That is MAP estimation, not sampling.
Exploration: the random perturbation prevents the chain from getting stuck at a single point. It forces the algorithm to explore the full distribution, not just climb to the peak.
Correct distribution: the specific scaling is chosen so that the sequence of points asymptotically follows the target distribution . So the noise and gradient terms together produce the right balance so that regions of high probability are visited proportionally more often.
2 issues with LMC:
Burn-in period: The sequence starts from some arbitrary point , 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.Sample correlation: Consecutive samples and 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 -th sample, discarding the intermediate ones. This reduces correlation between retained samples.
Note: LMC draws samples
from
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
,
and MC integration approximates the predictive distribution
.
13.4 Bayesian Inference with LMC
To perform Bayesian Inference, the LMC update rule becomes:
where the gradient of the log posterior is:
The posterior distribution
is the target PDF
.
We want to sample from this posterior distribution.
is the gradient of the log likelihood, summed over all training examples. This is the data-driven term, pushing toward parameters that explain the data well.
is the gradient of the log prior. For the Gaussian prior , this equals , pulling back to zero.
These two terms together balance fitting the data and staying close to the prior, which is the same tension as regularised ERM.