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 | for residual | Behaviour | |
|---|---|---|---|
| squared (MSE) | punishes outliers heavily; gives the mean | ||
| absolute (MAE) | robust; gives the median | ||
| Huber () | if , else | clipped to | 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.
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 and a score , the margin is positive when the prediction is correct. Losses are functions of the margin:
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 classes, the softmax cross-entropy has the famously simple gradient
derived in Softmax and Cross-Entropy Gradient.
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 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
reductionargument (mean,sum,none) changes gradient scale: withsum, the effective learning rate grows with the batch size. - Class weights in the cross-entropy rebalance rare classes.
Exercises
Exercise 1: Huber gradient
With , what is the Huber gradient for residuals , and ?
Answer
, and .
Solution
Inside the gradient is the residual; outside it is .
Exercise 2: Hinge versus logistic at large margin
At margin , compare the hinge loss and the logistic loss (natural log).
Answer
Hinge 0; logistic about .
Solution
: hinge stops caring once the margin exceeds 1. : logistic keeps pushing, with a tiny gradient.
Exercise 3: Softmax CE gradient check (code)
Check by finite differences for , .
Answer
Both give about .
Solution
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…
- mean
- median
- mode
- maximum
Why is the 0-1 loss not used directly for training?
- It is too large
- Its gradient is zero almost everywhere
- It is not defined for two classes
- It is always 1
The gradient of softmax cross-entropy with respect to the logits is…