Deep Learning Slides 📂 Introduction · 7 of 18 38 min read

Loss Functions & Optimisation Objectives in ML

The loss function is a model's scoreboard — and training is the relentless push to shrink it. This visual guide covers MSE, cross-entropy, and regularised losses with worked numerical examples, the maximum-likelihood view that unifies them all, gradient descent, and NumPy + scikit-learn code.

Loss Functions & Optimisation Objectives

A model can't improve until it can measure how wrong it is. The loss function is that scoreboard — and the whole of training is one relentless push to make its number smaller. Meet the objectives that steer every model.
MSE & RMSE Cross-Entropy The MLE View Regularisation

Press Next → or use ← → arrow keys

Section 01

The Archery Coach & the Scoreboard

An archer looses an arrow; the scoreboard reports how far it missed. The coach studies that gap and whispers a tiny correction — a little lower, a touch left. Shot after shot, the misses shrink. A neural network trains the same way: the loss function is the scoreboard, and the optimiser is the coach nudging the weights to close the gap.
📏
What a loss function does

It turns "how wrong was that prediction?" into a single number the optimiser can minimise. Lower loss means better predictions — so the whole of learning is just rolling that number downhill.

Section 01

Loss vs Cost vs Objective

Three words that get used loosely but mean precise things. Getting them straight makes everything else click:

🎯
Loss
The error on a single example. How far one prediction ŷ sits from its true target y.
📊
Cost
The average loss over the whole dataset (or mini-batch). This is the number training actually minimises.
🧮
Objective
Cost plus regularisation. The full quantity the optimiser drives down — accuracy and simplicity together.
🧩
Objective = Cost + Penalty

The loss measures fit; the penalty discourages needlessly complex models. Balancing the two is the heart of good training.

Section 02

Mean Squared Error — The Regression Workhorse

Square each error, average them. Squaring kills the sign and punishes big misses far more than small ones — the loss curve is a smooth, convex bowl with a single global minimum.

L = (y − ŷ)² — a convex bowl min error
MSE = 1/n Σ (yᵢ − ŷᵢ
average squared error
RMSE = MSE
back in the target's units
⚠️
Highly sensitive to outliers

Because errors are squared, a single wild miss can dominate the entire loss. Great when large errors truly matter — dangerous on heavy-tailed data.

Section 02

MSE in Action: Predicting Rent

Five flats, predicted vs true monthly rent. Watch how one flat swamps the total:

FlatTrue (£)Predicted (£)ErrorSquared Error
A1,2001,150+502,500
B850900−502,500
C2,0001,700+30090,000
D950940+10100
E1,5001,520−20400
19,100MSE = 95,500 ÷ 5
£138.2RMSE = √19,100
94%of the loss comes from Flat C alone
🔍
One outlier, most of the loss

Flat C's £300 miss contributes 90,000 of the 95,500 total. That's MSE's outlier vulnerability made concrete — the model will bend over backwards to fix C.

Section 03

Binary Cross-Entropy — The Classification Standard

For yes/no problems, we don't measure distance — we measure surprise. Cross-entropy punishes confident wrong answers savagely: as a wrong prediction approaches certainty, the loss shoots toward infinity.

−log(ŷ) when the true label is 1 ŷ→1 (right) ŷ→0 (wrong): loss ∞ ŷ
L = −[y log ŷ + (1−y) log(1−ŷ)]
y ∈ {0,1} · ŷ ∈ (0,1)
💡
Only one term fires

If y = 1, only −log(ŷ) counts; if y = 0, only −log(1−ŷ). The other half zeroes out.

🛡️
Clip before you log

log(0) = −∞. Always clip predictions to [ε, 1−ε] with ε = 1e-15 before computing cross-entropy.

Section 03

Cross-Entropy in Action: Spam Filter

Four emails, each with the model's predicted probability of spam. The one confident mistake dominates:

EmailTrueP(spam)Active termLoss
E1SPAM (1)0.90−log(0.90)0.105
E2HAM (0)0.05−log(0.95)0.051
E3SPAM (1)0.10−log(0.10)2.303
E4HAM (0)0.60−log(0.40)0.916
0.8438Average cost = 3.375 ÷ 4
68%of the cost is E3 alone
2.303E3's penalty — confidently wrong
🚨
Confidence cuts both ways

E3 was 90% sure a spam email was ham — and cross-entropy makes it pay dearly. That harsh signal is exactly what forces the model to fix its most dangerous mistakes first.

Section 04

Categorical Cross-Entropy — Many Classes

When there are 3+ mutually exclusive classes, extend the idea. Labels are one-hot, predictions come from softmax, and only the true class's term survives.

L = −Σ yₖ log(ŷₖ)
yₖ = 1 for the true class, 0 otherwise · ŷₖ = softmax prob for class k
Because the label is one-hot, every term but the true class multiplies by zero. The loss is simply −log(probability assigned to the correct class).
Softmax turns raw scores into a probability distribution; categorical cross-entropy then rewards putting mass on the right class. They're almost always used together.
🧮
Binary is just the 2-class case

Binary cross-entropy is categorical cross-entropy with exactly two classes. Same idea, one formula generalising the other.

Section 05

The Unifying View: Maximum Likelihood

Why do these particular losses work? Because each one is what you get when you assume a noise distribution and maximise likelihood. Choosing a loss is choosing a model of the noise.

Assumed noiseNegative log-likelihoodLoss you get
Gaussian N(ŷ, σ²)Σ(yᵢ − ŷᵢ)²MSE
Laplacian exp(−|y−ŷ|/b)Σ|yᵢ − ŷᵢ|MAE (L1 loss)
Bernoulli ŷʸ(1−ŷ)¹⁻ʸ−Σ[y log ŷ + (1−y)log(1−ŷ)]Binary Cross-Entropy
Categorical Πŷₖʸᵏ−Σ yₖ log ŷₖCategorical Cross-Entropy
🌐
One principle behind them all

Gaussian noise → MSE. Heavy-tailed Laplacian noise → MAE. Binary outcomes → cross-entropy. The loss isn't arbitrary — it encodes your assumption about how the data was generated.

Section 06

Regularised Loss — Penalising Complexity

Add a penalty on the weights themselves and the optimiser is pushed toward simpler models that generalise better. Two classic penalties:

J(θ) = Loss + λ·Σ θᵢ²
Shrinks all weights smoothly toward zero — but never exactly to zero. Spreads influence across features.
J(θ) = Loss + λ·Σ |θᵢ|
Drives many weights to exactly zero — built-in feature selection that discards the irrelevant ones.
🎭
Bureaucrat vs sculptor

L2 is a bureaucrat taxing every weight's effort uniformly. L1 is a sculptor, carving unused weights away entirely until only the essential ones remain.

Section 06

L1 vs L2 — and Tuning λ

PropertyL1 (Lasso)L2 (Ridge)
Sparsity (zero weights)Yes — exact zerosNo — only shrinks
Feature selectionBuilt-inNot built-in
Correlated featuresPicks one, drops restSpreads weight across all
Gradient at zeroUndefined (subgradient)Smooth
Best whenMany irrelevant featuresAll features relevant
λ = 0No penalty → overfitting risk
λ → ∞All weights → 0 → underfitting
CVTune λ by cross-validation, not guessing
🎛️
λ is a hyperparameter

There's a sweet spot between too much and too little regularisation. Find it with GridSearchCV or RidgeCV/LassoCV — never by intuition.

Section 07

Gradient Descent — Rolling Downhill

The optimiser minimises the loss by repeatedly stepping in the direction that lowers it fastest — the negative gradient. Picture a ball rolling to the bottom of the loss valley:

minimum (lowest loss) start
θ θ η · ∂Loss/∂θ
η = learning rate (step size) · repeat until convergence
MLE losses give clean gradients

For MSE, ∂L/∂ŷ = −2(y − ŷ). For cross-entropy with sigmoid/softmax, ∂L/∂ŷ ≈ ŷ − y — literally the prediction error. That elegance is why these losses train so smoothly.

Section 08

Loss Functions From Scratch

Each loss is a few lines of NumPy — note the clip that keeps cross-entropy finite:

import numpy as np

def mse(y, p):     return np.mean((y - p) ** 2)
def rmse(y, p):    return np.sqrt(mse(y, p))

def binary_cross_entropy(y, p):
    eps = 1e-15                          # prevent log(0)
    p = np.clip(p, eps, 1 - eps)
    return -np.mean(y*np.log(p) + (1-y)*np.log(1-p))

def regularised_mse(y, p, w, lam=0.01, mode='l2'):
    pen = lam*np.sum(w**2) if mode=='l2' else lam*np.sum(np.abs(w))
    return mse(y, p) + pen

y = np.array([1200, 850, 2000, 950, 1500])
p = np.array([1150, 900, 1700, 940, 1520])
print(mse(y, p), rmse(y, p))        # 19100.0  138.2

yc = np.array([1, 0, 1, 0]); pc = np.array([.9, .05, .1, .6])
print(binary_cross_entropy(yc, pc))  # 0.8438
🧩
The numbers match our tables

19,100 for the rent MSE, 0.8438 for the spam BCE — the code reproduces the worked examples exactly.

Section 08

L1 vs L2 on Real Data

Two logistic-regression models on the Breast Cancer dataset — same data, different penalty. The trade-off is stark:

from sklearn.linear_model import LogisticRegression

lr_l2 = LogisticRegression(penalty='l2', C=1.0, max_iter=1000)
lr_l1 = LogisticRegression(penalty='l1', C=1.0, solver='liblinear')
# ...fit both on scaled features, then compare...
ModelAccuracyBCE lossZero weights
L2 Ridge0.97370.07910 / 30
L1 Lasso0.96490.102212 / 30
⚖️
Accuracy vs interpretability

L2 keeps all 30 features and edges ahead on accuracy. L1 zeroes 12 of them — a small accuracy cost in exchange for a simpler, more interpretable model using only 18 features.

Section 09

Choosing Your Loss Function

ScenarioLoss function
Regression, Gaussian noiseMSE / RMSE
Regression, outlier-robustMAE or Huber
Binary classificationBinary Cross-Entropy
Multi-class (mutually exclusive)Categorical Cross-Entropy
Overfitting — many featuresL1 penalty (Lasso)
Overfitting — correlated featuresL2 penalty (Ridge)
🧭
Match the loss to the task and the noise

Continuous target with well-behaved errors → MSE. Probabilities → cross-entropy. Too many features → add an L1/L2 penalty. The task decides the loss.

Section 10

6 Golden Rules

  Loss-function cheat-sheet
1Never use MSE for classification. Its gradient misbehaves near 0 and 1 and training stalls — use cross-entropy.
2Clip before log-based losses. log(0) = −∞; always clamp predictions to [ε, 1−ε], ε = 1e-15.
3MSE is outlier-sensitive. Check the target distribution; for heavy tails use Huber or log-transform the target.
4Tune λ with cross-validation, never intuition. It's a hyperparameter like any other.
5Loss ≠ evaluation metric. Train with a differentiable loss; judge with F1 or AUC-ROC.
6Cross-entropy needs calibrated probabilities. Confident-but-wrong outputs blow up the loss — calibrate if needed.
🚀
The compass for every model

Pick the loss that matches your task and your noise, penalise complexity, and let gradient descent do the rest. Choose the objective well and the model learns the right thing.