TExcelTAD
Home › Math for Deep Learning & LLMs › Loss Functions and Output Units

Loss Functions and Their Gradients

The loss turns "how wrong is the network" into a single number, and its gradient is the very first signal backpropagation sends through the network. Choosing a loss is choosing what errors cost. This lesson compares the common losses side by side, with the gradients that backprop starts from.

Regression losses

Loss ℓ(r)\ell(r) for residual r=f−yr = f - y ∂ℓ/∂f\partial\ell/\partial f Behaviour
squared (MSE) r2r^2 2r2r punishes outliers heavily; gives the mean
absolute (MAE) ∣r∣\lvert r \rvert sign⁡(r)\operatorname{sign}(r) robust; gives the median
Huber (δ\delta) 12r2\frac{1}{2}r^2 if ∣r∣≤δ\lvert r \rvert \le \delta, else δ(∣r∣−δ2)\delta(\lvert r \rvert - \frac{\delta}{2}) rr clipped to [−δ,δ][-\delta, \delta] quadratic near 0, linear far away

The Huber loss has a bounded gradient, so one wild outlier cannot dominate an update. A neat consequence: the best constant prediction under MSE is the mean of the targets, under MAE the median.

python · try it yourself
import numpy as np

y = np.array([1.0, 2.0, 2.5, 3.0, 50.0])                 # one outlier
cands = np.linspace(0, 20, 20001)
mse = [np.mean((c - y)**2) for c in cands]
mae = [np.mean(np.abs(c - y)) for c in cands]
def huber(r, d=1.0): return np.where(np.abs(r) <= d, 0.5 * r**2, d * (np.abs(r) - d / 2))
hub = [np.mean(huber(c - y)) for c in cands]
print("best constant under MSE:", round(cands[np.argmin(mse)], 3), " mean:", y.mean())
print("best constant under MAE:", round(cands[np.argmin(mae)], 3), " median:", np.median(y))
print("best constant under Huber:", round(cands[np.argmin(hub)], 3))
best constant under MSE: 11.7  mean: 11.7
best constant under MAE: 2.5  median: 2.5
best constant under Huber: 2.5

Classification losses

For a binary label y∈{−1,+1}y \in \{-1, +1\} and a score ss, the margin m=ysm = ys is positive when the prediction is correct. Losses are functions of the margin:

ℓ0-1=[m≤0],ℓlogistic=log⁡(1+e−m),ℓhinge=max⁡(0,1−m)\ell_{\text{0-1}} = [m \le 0], \qquad \ell_{\text{logistic}} = \log(1 + e^{-m}), \qquad \ell_{\text{hinge}} = \max(0, 1 - m)

The 0-1 loss is what we care about but has zero gradient almost everywhere; logistic (= binary cross-entropy) and hinge (SVMs, see Soft Margin) are convex surrogates that upper-bound it (logistic in base 2).

For KK classes, the softmax cross-entropy has the famously simple gradient

∂ℓ∂z=softmax⁡(z)−ey\frac{\partial\ell}{\partial\mathbf{z}} = \operatorname{softmax}(\mathbf{z}) - \mathbf{e}_y

derived in Softmax and Cross-Entropy Gradient.

python · try it yourself
import numpy as np

m = np.array([-2.0, -0.5, 0.0, 0.5, 1.0, 2.0])
print("margin   ", m)
print("0-1      ", (m <= 0).astype(float))
print("logistic2", np.round(np.log2(1 + np.exp(-m)), 3))
print("hinge    ", np.maximum(0, 1 - m))
print("logistic gradient dl/dm:", np.round(-1 / (1 + np.exp(m)), 3))
margin    [-2.  -0.5  0.   0.5  1.   2. ]
0-1       [1. 1. 1. 0. 0. 0.]
logistic2 [3.069 1.405 1.    0.684 0.452 0.183]
hinge     [3.  1.5 1.  0.5 0.  0. ]
logistic gradient dl/dm: [-0.881 -0.622 -0.5   -0.378 -0.269 -0.119]

Losses beyond labels

  • Contrastive (InfoNCE): a softmax cross-entropy over similarities, where the "class" is the matching pair in the batch. It trains CLIP and many embedding models (Embeddings).
  • KL divergence: for distillation and VAEs (Entropy and KL).
  • Focal loss −(1−py)γlog⁡py-(1 - p_y)^\gamma\log p_y down-weights easy examples in highly imbalanced detection tasks.

In software

  • nn.HuberLoss/nn.SmoothL1Loss, nn.L1Loss, nn.MSELoss, nn.MultiMarginLoss, nn.CrossEntropyLoss(label_smoothing=…).
  • The reduction argument (mean, sum, none) changes gradient scale: with sum, the effective learning rate grows with the batch size.
  • Class weights in the cross-entropy rebalance rare classes.

Exercises

Exercise 1: Huber gradient

With δ=1\delta = 1, what is the Huber gradient for residuals 0.30.3, −2-2 and 1010?

Answer

0.30.3, −1-1 and 11.

Solution

Inside [−δ,δ][-\delta, \delta] the gradient is the residual; outside it is δsign⁡(r)\delta\operatorname{sign}(r).

Exercise 2: Hinge versus logistic at large margin

At margin m=3m = 3, compare the hinge loss and the logistic loss (natural log).

Answer

Hinge 0; logistic about 0.04860.0486.

Solution

max⁡(0,1−3)=0\max(0, 1 - 3) = 0: hinge stops caring once the margin exceeds 1. ln⁡(1+e−3)=ln⁡1.0498≈0.0486\ln(1 + e^{-3}) = \ln 1.0498 \approx 0.0486: logistic keeps pushing, with a tiny gradient.

Exercise 3: Softmax CE gradient check (code)

Check ∂ℓ/∂z=softmax⁡(z)−ey\partial\ell/\partial\mathbf{z} = \operatorname{softmax}(\mathbf{z}) - \mathbf{e}_y by finite differences for z=(1,2,0.5)\mathbf{z} = (1, 2, 0.5), y=2y = 2.

Answer

Both give about (0.2312,0.6285,−0.8598)(0.2312, 0.6285, -0.8598).

Solution
python · try it yourself
import numpy as np
z, y = np.array([1.0, 2.0, 0.5]), 2
ce = lambda z: np.log(np.sum(np.exp(z))) - z[y]
p = np.exp(z) / np.exp(z).sum()
num = np.array([(ce(z + e) - ce(z - e)) / 2e-6 for e in np.eye(3) * 1e-6])
print(np.round(p - np.eye(3)[y], 4), np.round(num, 4))
[ 0.2312  0.6285 -0.8598] [ 0.2312  0.6285 -0.8598]

Test yourself

The best constant prediction under mean absolute error is the…

  1. mean
  2. median
  3. mode
  4. maximum

Why is the 0-1 loss not used directly for training?

  1. It is too large
  2. Its gradient is zero almost everywhere
  3. It is not defined for two classes
  4. It is always 1

The gradient of softmax cross-entropy with respect to the logits is…

  1. ey\mathbf{e}_y
  2. softmax⁡(z)−ey\operatorname{softmax}(\mathbf{z}) - \mathbf{e}_y
  3. −log⁡softmax⁡(z)-\log\operatorname{softmax}(\mathbf{z})
  4. z−ey\mathbf{z} - \mathbf{e}_y