Foundations to Frontier
Tests
A. Mathematical Foundations › A3 Calculus and Analysis › Matrix and vector calculus

Gradients of Common ML Losses (MSE, Cross-Entropy, Softmax)

Every training loop starts with the gradient of a loss. MSE, cross-entropy and softmax cross-entropy all reduce to prediction minus target at the logit level. Know their gradients, why cross-entropy beats MSE for classification, and how the same pattern powers contrastive learning and uncertainty-aware robot models.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A mistake score

To teach a model, give it a loss: one number that says how wrong it is. Then ask, for each of the model’s predictions, “which way should I nudge this to be less wrong, and how hard?” That’s the gradient of the loss.

For many popular losses the answer is surprisingly simple: nudge by (prediction − target). If you guessed 7 and the answer was 4, push down by 3.

Loss functions and their gradients
true class:
class 1class 2class 3
p = (0.786, 0.175, 0.039) · loss −log p3 = 3.241 · ∂L/∂z = p − y = (0.786, 0.175, -0.961)
Blue = predicted probability, green = target (one-hot), orange = gradient p − y. A gradient-descent step lowers wrong logits in proportion to their probability and raises the true one by 1 − p. The gradients always sum to 0.
Why engineers care

A robot learning to grasp gets a loss for every failed attempt, and a navigation model gets one for every wrong turn it predicts. The gradient of that loss is the only signal that tells millions of numbers inside the model how to change.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A loss is…
  2. 2. Predicted 7, target 4. The error (prediction − target) is…
  3. 3. To reduce that error, nudge the prediction…

Level 1: Beginner

★★☆☆☆ Basic⏱ 15 minSecondary-school mathematics: arithmetic and elementary algebra.

Three losses, three gradients

Loss Formula (one example) Gradient
mean squared error 12(y^−y)2\tfrac12(\hat y - y)^2 ∂L/∂y^=y^−y\partial L/\partial\hat y = \hat y - y
binary cross-entropy on a logit zz −ylog⁡σ(z)−(1−y)log⁡(1−σ(z))-y\log\sigma(z) - (1-y)\log(1-\sigma(z)) ∂L/∂z=σ(z)−y\partial L/\partial z = \sigma(z) - y
softmax cross-entropy on logits z\mathbf z −log⁡softmax⁡(z)c-\log\operatorname{softmax}(\mathbf z)_c ∂L/∂z=p−y\partial L/\partial\mathbf z = \mathbf p - \mathbf y

All three have the form prediction − target, measured at the right place (the value, the probability, or the probability vector).

Example. Logits (2,0.5,−1)(2, 0.5, -1) give p≈(0.79,0.18,0.04)\mathbf p\approx(0.79, 0.18, 0.04). If the true class is the third, the gradient is (0.79,0.18,−0.96)(0.79, 0.18, -0.96). Descent lowers the first two logits and raises the third.

📝 Quick check (Level 1)
0/3 answered
  1. 1. MSE gradient for ŷ = 5, y = 2?
  2. 2. BCE gradient at z = 0 with y = 1?
  3. 3. Softmax-CE gradient for the true class with p = 0.8?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

More losses

Loss Gradient w.r.t. prediction Behaviour
MSE r=y^−yr = \hat y - y outliers dominate
MAE ∣r∣\lvert r\rvert sign⁡(r)\operatorname{sign}(r) robust, but not smooth at 0
Huber (δ\delta) rr if ∣r∣≤δ\lvert r\rvert\le\delta, else δsign⁡(r)\delta\operatorname{sign}(r) best of both (Huber, 1964)
Gaussian NLL (a−μ)22σ2+log⁡σ\frac{(a-\mu)^2}{2\sigma^2} + \log\sigma ∂μ=(μ−a)/σ2\partial_\mu = (\mu - a)/\sigma^2, ∂log⁡σ=1−(a−μ)2/σ2\partial_{\log\sigma} = 1 - (a-\mu)^2/\sigma^2 learns its own uncertainty

Over a whole dataset (vectorized)

  • Linear regression: L=12n∥Xw−y∥2L = \frac1{2n}\lVert X\mathbf w - \mathbf y\rVert^2 gives ∇w=1nX⊤(Xw−y)\nabla_{\mathbf w} = \frac1nX^\top(X\mathbf w - \mathbf y).
  • Logistic regression: ∇w=1nX⊤(σ(Xw)−y)\nabla_{\mathbf w} = \frac1nX^\top(\sigma(X\mathbf w) - \mathbf y).
  • Softmax regression: ∇W=1nX⊤(P−Y)\nabla_W = \frac1nX^\top(P - Y).

They share the same structure: the data matrix transposed, times prediction minus target (A3.3-2).

Implement them stably

Use logaddexp(0, z) - y·z for BCE, subtract the max inside softmax, and compute log⁡softmax⁡\log\operatorname{softmax} directly. Never take log⁡\log of a probability that may have rounded to 0 (A3.1-3).

🐍 Exercise 1: losses and their gradients
Implement mean MSE, stable BCE-with-logits and softmax cross-entropy, each returning (loss, gradient). Gradient-check them all, and test huge logits.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The MAE gradient for ŷ = 1, y = 4?
  2. 2. The softmax-CE gradients over all logits sum to…
  3. 3. Logistic regression: ∇w = ?

Level 3: Advanced

★★★★☆ Advanced⏱ 40 minGraduate level, with full derivations and proofs.

Deriving p − y

Softmax has Jacobian ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j = p_i(\delta_{ij} - p_j), i.e. J=diag⁡(p)−pp⊤J = \operatorname{diag}(\mathbf p) - \mathbf p\mathbf p^\top. For L=−∑iyilog⁡piL = -\sum_iy_i\log p_i:

∂L∂zj=−∑iyipipi(δij−pj)=−yj+pj∑iyi=pj−yj\frac{\partial L}{\partial z_j} = -\sum_i\frac{y_i}{p_i}p_i(\delta_{ij} - p_j) = -y_j + p_j\sum_iy_i = p_j - y_j

∎ The same simplification holds for every canonical link in a generalized linear model. The gradient of the log-partition function is the mean, so the negative log-likelihood’s gradient is “mean − observation” (McCullagh and Nelder, 1989).

Why cross-entropy for classifiers

With MSE on a sigmoid, ∂L/∂z=(σ(z)−y)σ(z)(1−σ(z))\partial L/\partial z = (\sigma(z) - y)\sigma(z)(1-\sigma(z)). The extra σ′\sigma' factor is tiny when ∣z∣\lvert z\rvert is large, so a confidently wrong model barely learns. Cross-entropy cancels that factor exactly. It’s also the maximum-likelihood loss for a Bernoulli or categorical model.

Convexity

The logistic loss is convex in w\mathbf w, with Hessian 1nX⊤diag⁡(pi(1−pi))X⪰0\frac1nX^\top\operatorname{diag}(p_i(1-p_i))X\succeq0. So logistic and softmax regression have a single global optimum (A3.2-6). Deep networks lose this property through their hidden layers, not through the loss.

Exercise 3.1: Show the BCE-with-logits gradient is σ(z) − y

L=log⁡(1+ez)−yzL = \log(1 + e^z) - yz. Then L′=ez1+ez−y=σ(z)−yL' = \frac{e^z}{1 + e^z} - y = \sigma(z) - y.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The MSE-on-sigmoid gradient at z = 0, y = 1?
  2. 2. Cross-entropy is preferred for classification because…
  3. 3. The logistic-regression loss is…

Level 4: Expert

★★★★★ Expert⏱ 45 minResearchers: original papers and open problems.

Losses that model uncertainty

A robot policy or perception model can predict a mean and a variance, and train with the Gaussian negative log-likelihood (Kendall and Gal, 2017; Lakshminarayanan, Pritzel and Blundell, 2017). Its gradient automatically down-weights noisy examples (1/σ21/\sigma^2) and grows σ\sigma where errors are large. Plain gradient descent on it is unstable, because steps on μ\mu scale like 1/σ21/\sigma^2. Fisher-preconditioned (natural-gradient) steps fix this, as do practical tricks like the “β-NLL” (Seitzer et al., 2022).

🐍 Exercise 2 (research): learn a sensor's noise level from data
Derive the Gaussian-NLL gradients for μ and log σ, and gradient-check them. Then fit μ(x) and log σ(x) to a sensor whose noise grows with distance, using Fisher-preconditioned steps.

The same pattern everywhere

  • Contrastive learning. InfoNCE (Oord, Li and Vinyals, 2018; CLIP, Radford et al., 2021) is softmax cross-entropy over similarities, with gradient (p−e+)/τ(\mathbf p - \mathbf e_+)/\tau. It pulls the positive pair together and pushes hard negatives away hardest (Practice Code 5).
  • Policy gradients. For a softmax policy, ∇zlog⁡π(a)=ea−p\nabla_{\mathbf z}\log\pi(a) = \mathbf e_a - \mathbf p, scaled by the advantage. It is the same “target − prediction” shape, which is why RL updates look like weighted classification.
  • Focal loss (Lin et al., 2017) multiplies cross-entropy by (1−pt)γ(1 - p_t)^\gamma to focus on hard examples, improving detectors with heavy class imbalance (like rare obstacles).
  • Knowledge distillation uses a soft target vector, giving gradient pstudent−pteacher\mathbf p_{\text{student}} - \mathbf p_{\text{teacher}} (Hinton, Vinyals and Dean, 2015).

References

  1. P. Huber (1964). “Robust estimation of a location parameter.” Annals of Mathematical Statistics, 35(1).
  2. P. McCullagh, J. Nelder (1989). Generalized Linear Models, 2nd ed. Chapman & Hall.
  3. G. Hinton, O. Vinyals, J. Dean (2015). “Distilling the knowledge in a neural network.” NeurIPS Deep Learning Workshop.
  4. A. Kendall, Y. Gal (2017). “What uncertainties do we need in Bayesian deep learning for computer vision?” NeurIPS.
  5. B. Lakshminarayanan, A. Pritzel, C. Blundell (2017). “Simple and scalable predictive uncertainty estimation using deep ensembles.” NeurIPS.
  6. T.-Y. Lin, P. Goyal, R. Girshick, K. He, P. Dollár (2017). “Focal loss for dense object detection.” ICCV.
  7. A. van den Oord, Y. Li, O. Vinyals (2018). “Representation learning with contrastive predictive coding.” arXiv:1807.03748.
  8. A. Radford et al. (2021). “Learning transferable visual models from natural language supervision.” ICML.
  9. M. Seitzer, A. Tavakoli, D. Antic, G. Martius (2022). “On the pitfalls of heteroscedastic uncertainty estimation with probabilistic neural networks.” ICLR.