Loss functions
Loss functions measure how well a model's predictions match target values; choosing and deriving the right loss ties the model to probabilistic assumptions and determines gradients used in training.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Loss functions are the numerical criteria that guide training of neural networks. An engineer uses them to convert a prediction task (regression or classification) into a differentiable objective to minimise during optimisation and to choose a loss consistent with the assumed noise or label process (Gaussian, Laplace, Bernoulli, multinomial, etc.).
Key ideas
Negative log-likelihood (NLL) and Maximum Likelihood Estimation (MLE): If we assume a probabilistic model p(y | x; θ), the log-likelihood for data is ℓ(θ)= Σ_i log p(y_i | x_i; θ). MLE maximises ℓ(θ), equivalently minimises the negative log-likelihood: -ℓ(θ). Many common loss functions are NLLs arising from specific noise models.
Regression losses and noise assumptions (derivations commonly asked):
- If we assume the conditional target distribution is Gaussian with fixed variance σ^2 and mean equal to model output ŷ, p(y | x) = N(ŷ, σ^2), then the negative log-likelihood (up to additive constants) is proportional to the mean squared error (MSE). Step-by-step derivation: write Gaussian density, take negative log, drop constants independent of θ, obtain (1/2σ^2)(y - ŷ)^2; with fixed σ^2 constant, minimising gives same minimiser as minimising (y - ŷ)^2 (MSE).
- If we assume a Laplace (double-exponential) noise model p(y | x) ∝ exp(-|y - ŷ|/b), the NLL is proportional to mean absolute error (MAE). This is why MAE is robust to outliers (heavy-tailed noise).
Classification losses from discrete distributions:
- For binary labels y ∈ {0,1} with Bernoulli distribution parameter p=ŷ, the NLL is the binary cross-entropy: -[y log ŷ + (1-y) log(1-ŷ)]. This is often written as binary logistic loss.
- For multiclass labels with one-hot y and model logits z_j (scores before normalisation), apply softmax to get probabilities p_j = exp(z_j)/Σ_k exp(z_k). The NLL becomes categorical cross-entropy: -Σ_j y_j log p_j. This is the standard loss for multi-class classification.
Cross-entropy and Kullback–Leibler (KL) divergence: Given true distribution q and model p, cross-entropy H(q,p) = -Σ q log p. KL divergence D_{KL}(q || p) = Σ q log(q/p) = H(q,p) - H(q), so minimising cross-entropy over p is equivalent to minimising D_{KL}(q||p) when q (true) is fixed. In supervised learning with one-hot labels, H(q) is constant so categorical cross-entropy minimises KL.
Hinge loss: used in SVMs, defined for binary labels y ∈ {−1, +1} and score s as max(0, 1 - y·s). It is a margin-based loss and not probabilistic (not NLL), but often used as a convex surrogate for zero-one loss.
Huber loss: a robust loss that behaves like MSE near zero error and like MAE for large error. It is differentiable at zero and used when we want robustness but smooth gradients.
Surrogate loss: many losses are used as proxies for the non-differentiable 0–1 classification error; cross-entropy is smooth (differentiable), while hinge is convex but non-differentiable at the margin. For linear models these act as convex surrogates; training uses such losses because they provide useful (sub)gradients.
What to draw in exam answers (diagrams):
- Plot loss vs. error e = y - ŷ for MSE (parabola), MAE (V-shape), and Huber (quadratic near 0, linear outside). For hinge loss, plot vs. the margin m = y·s (zero/flat for m ≥ 1, linear when m < 1). Label axes accordingly and mark the transition point δ for Huber loss.
Assumptions to state in derivations:
- For MSE ← Gaussian derivation: assume i.i.d. samples, conditional Gaussian noise with fixed variance.
- For cross-entropy ← Bernoulli/multinomial derivation: assume conditionally independent labels drawn from Bernoulli/multinomial with probabilities given by softmax/sigmoid outputs.
Formulas
R(θ) = (1/N) Σ_{i=1}^N L(y_i, ŷ_i(θ)) — R(θ): empirical risk (same units as the loss L), N: number of samples, y_i: true target, ŷ_i: model prediction; applies in all supervised training.
MSE = (1/N) Σ_{i=1}^N (y_i - ŷ_i)^2 — Mean squared error, unit is square of target units (e.g., m^2 if y in metres); applies for regression; arises from Gaussian noise assumption.
MAE = (1/N) Σ_{i=1}^N |y_i - ŷ_i| — Mean absolute error, units same as target (e.g., m); applies for regression with Laplace noise.
BinaryCrossEntropy = -(1/N) Σ_{i=1}^N [ y_i log p_i + (1 - y_i) log(1 - p_i) ] — p_i ∈ (0,1) is predicted probability for class 1; unit: nats (if natural logs) or bits (if log base 2); commonly treated unitless; applies for binary classification with Bernoulli likelihood.
Softmax: p_j = exp(z_j) / Σ_k exp(z_k) — p_j: predicted probability for class j, z_j: logit score (unitless); applies in multiclass classification final layer.
CategoricalCrossEntropy = -(1/N) Σ_{i=1}^N Σ_j y_{i,j} log p_{i,j} — y_{i,j} is one-hot (0 or 1); unit: nats; applies for multiclass classification. Also, for a single sample with softmax outputs p_j, the gradient w.r.t. logits is ∂L/∂z_j = p_j - y_j.
Hinge(y, s) = max(0, 1 - y·s) — y ∈ {−1,+1}, s is score; unitless; used in margin classifiers like SVM.
Huber_δ(e) = { 0.5 e^2 if |e| ≤ δ; δ(|e| - 0.5δ) otherwise } — e = y - ŷ; δ > 0 is threshold; units: square of the target units (δ has the same units as e, so both branches have squared units).
D_{KL}(q || p) = Σ_x q(x) log (q(x)/p(x)) — KL divergence, unit: nats; applies comparing two discrete distributions q and p.
∂(MSE)/∂ŷ_i = -(2/N) (y_i - ŷ_i) — gradient of MSE wrt prediction; units: same as the target; used in backprop.
∂(BinaryCrossEntropy)/∂z = p - y when p = sigmoid(z) — derivative of binary cross-entropy wrt logit z; used in efficient gradient computation.
Notes: log means natural logarithm unless stated otherwise.
Worked examples
Example 1 — Regression MSE and gradient (numerical): Data (units: metres): x values omitted (not needed); true y: [1.0 m, 2.0 m, 4.0 m]; model predictions ŷ: [0.8 m, 2.5 m, 3.6 m]. N = 3. Step 1: compute errors e_i = y_i - ŷ_i: [0.2, -0.5, 0.4] m. Step 2: square errors: [0.04, 0.25, 0.16] m^2. Step 3: MSE = (1/3)(0.04 + 0.25 + 0.16) = (1/3)(0.45) = 0.15 m^2. Bold final: MSE = 0.15 m^2. Step 4: gradient wrt predictions: ∂MSE/∂ŷ_i = -(2/N) e_i = -(2/3) e_i: values = [-(2/3)0.2, -(2/3)(-0.5), -(2/3)*0.4] = [-0.133333..., +0.333333..., -0.266666...]. These are the per-sample gradients (units: same as the target, here m).
Example 2 — Binary cross-entropy (numerical): Two samples: true labels y = [1, 0]. Model outputs logits z = [2.0, -1.0]. Use sigmoid p = 1/(1+exp(-z)). Compute p_1 = sigmoid(2.0) ≈ 0.880797; p_2 = sigmoid(-1.0) ≈ 0.268941. Binary cross-entropy per sample: L1 = -[1·log(0.880797) + 0·log(1-0.880797)] = -log(0.880797) ≈ 0.126928; L2 = -[0·log(0.268941) + 1·log(1-0.268941)] = -log(0.731059) ≈ 0.313262. Average BCE = (0.126928 + 0.313262)/2 = 0.220095. Bold final: Binary cross-entropy = 0.220095 (nats). Also gradient wrt logits z: ∂L/∂z = p - y → for sample1: 0.880797 - 1 = -0.119203; sample2: 0.268941 - 0 = 0.268941.
Example 3 — Derivation model answer (theory): derive MSE from Gaussian MLE. Assume y_i | x_i ~ N(ŷ_i, σ^2) independent. Likelihood for one sample: p(y_i | x_i; θ) = (1/√(2πσ^2)) exp(-(y_i - ŷ_i)^2/(2σ^2)). Log-likelihood: log p = -0.5 log(2πσ^2) - (y_i - ŷ_i)^2/(2σ^2). For N samples, sum. Negative log-likelihood (drop constant term independent of θ): (1/(2σ^2)) Σ_i (y_i - ŷ_i)^2. Minimising w.r.t θ equivalent to minimising Σ (y_i - ŷ_i)^2, i.e., MSE. State assumptions: σ^2 known/fixed, i.i.d. samples.
Common mistakes
- Numerically unstable cross-entropy implementation: directly computing log(sigmoid(z)) can underflow/overflow; prefer stable formulations (use log-sum-exp trick) — mention but do not implement here.
- Using MAE without considering its optimisation properties — MAE has an undefined derivative at 0 and a constant-magnitude subgradient (±1) elsewhere, providing no curvature and often converging slower than MSE.
- Mixing label encodings: for categorical cross-entropy, using one-hot vectors; applying softmax to logits, not to probabilities.
- Forgetting to average or sum consistently (different libraries use sum or mean) — always state which you use in exam answers.
For your exam
Types of questions:
- Definitions: define loss, cost/empirical risk, NLL, MLE, cross-entropy, KL divergence.
- Short notes: compare MSE vs MAE vs Huber; when to use hinge loss.
- Derivations: show MSE arises from Gaussian MLE; derive binary cross-entropy from Bernoulli likelihood; derive gradient of cross-entropy combined with softmax.
- Numericals: compute MSE, MAE, BCE for small datasets, report units and gradients.
- Diagrams: plot loss vs error for MSE/MAE/Huber/hinge and label transitions.
What a full-marks answer includes:
- Clear statement of assumptions (i.i.d., noise model, domain of labels).
- Exact definitions with formulas and brief explanation of why the loss is chosen (e.g., robustness, convexity, probabilistic interpretation).
- Step-by-step algebra in derivations, dropping only terms independent of parameters and justifying it.
- Units where applicable and explanation of gradient direction (minimisation vs maximisation of likelihood).
Quick check
- Which noise assumption gives MSE as NLL? 2. Write the binary cross-entropy for a single sample with label y ∈ {0,1} and predicted probability p. 3. What is the derivative of categorical cross-entropy combined with softmax wrt logits z_j for a single sample? Answers: 1) Gaussian (normal) noise with fixed variance. 2) -[y log p + (1-y) log(1-p)]. 3) p_j - y_j (where p_j = softmax(z)_j).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?