A support ticket says, "I cannot log into the application." A model could predict how many hours the ticket will take to resolve, whether it is urgent, or which team should handle it. Those are three different questions, so the same prediction error cannot mean the same thing in all three cases.
A loss function takes a model's prediction and the correct target, then returns a single scalar number that measures their disagreement. During training, automatic differentiation works out how that loss number shifts when every weight nudges slightly, and an optimizer updates the parameters in the direction that shrinks it. The loss is not just a grade handed back after the prediction. It defines what the model is actually being asked to improve.
We will follow the support ticket through three tasks: predicting resolution hours, deciding whether it is urgent, and choosing one team from billing, login, bug, or feature. First, we see why raw signed errors cancel out. Then we build losses tailored to continuous values, yes-or-no probabilities, and competing multiclass choices.
Why raw errors do not work
For a numerical target, call the correct resolution time y and the model's prediction y_hat (read y-hat). Define the signed error as prediction minus target: e = y_hat - y. If the ticket actually takes 30 hours and the model predicts 10, then e = 10 - 30 = -20. The negative sign tells us the prediction came in too low. A prediction of 50 hours gives e = 50 - 30 = +20, meaning it came in too high.
That sign helps identify direction, yet it breaks as soon as we average errors across examples. Averaging -20 and +20 produces (-20 + 20) / 2 = 0.0. A plain average claims perfection even though both predictions missed by twenty hours! Positive and negative misses cancel out unless every error becomes non-negative before averaging. Squaring (e^2) and taking absolute value (|e|) are the two standard ways to strip that sign cleanly:
Mean squared error makes large misses count more
Mean squared error, or MSE, squares each prediction error, sums the squares, and divides by the batch size N. Squaring removes negative signs and maps exact predictions (e = 0) cleanly to 0. Across N examples indexed by i, with target y_i and prediction y_hat_i:
Trace three ticket errors: -2, 1, and 3 hours. Squaring turns them into 4, 1, and 9. Summing gives 14, and dividing by 3 yields an MSE of 14 / 3 ≈ 4.67. Notice the units as well: if targets sit in hours, MSE sits in hours squared, which drives gradient updates cleanly even though it reads differently from raw hours.
More importantly, squaring curves upward smoothly on both sides of zero so bigger misses rapidly carry heavier weight. An error of 2 adds 4, an error of 5 adds 25, and doubling 5 to 10 quadruples its squared cost from 25 to 100. Calculus explains why learning reacts proportionally too: the derivative of e^2 with respect to e is 2e. Twice the error produces twice the slope pushing weights back toward zero (divided by N across a batch average):
Evaluated for single-example squared error e^2 from e = -5 to +5
MSE rises in a smooth symmetric parabola centered at e = 0: small errors near zero feel almost flat slopes (2e), while large errors face steep slopes pushing parameters strongly.
| signed prediction error e (y_hat - y) | Squared error: e^2 |
|---|---|
| -5 | 25 |
| -4 | 16 |
| -3 | 9 |
| -2 | 4 |
| -1 | 1 |
| 0 | 0 |
| 1 | 1 |
| 2 | 4 |
| 3 | 9 |
| 4 | 16 |
| 5 | 25 |
That steep parabolic push helps when large mistakes must dominate training, yet it also hands outliers enormous leverage over a mini-batch. Test five ticket errors in hours: 2, -3, 4, -2, and one 100-hour extreme miss. The first four squares sum to 4 + 9 + 16 + 4 = 33, giving a baseline MSE of 33 / 4 = 8.25. Appending that single outlier adds 100^2 = 10,000, jumping the batch mean to 10,033 / 5 = 2,006.6 (243x larger from one data point!).
Mean absolute error limits an outlier's influence
Mean absolute error, or MAE, strips the sign without amplifying distance. Every error contributes directly in original units: -5 and +5 both contribute 5:
Check the exact same five errors (2, -3, 4, -2, 100). Before the outlier, absolute errors sum to 2 + 3 + 4 + 2 = 11, giving MAE 11 / 4 = 2.75 hours. Including 100 raises the average linearly to (11 + 100) / 5 = 22.2 hours (8.1x rather than 243x). Look at the slope to see why MAE resists extreme points: for |e|, the derivative away from zero is fixed at +1 when e > 0 and -1 when e < 0. Even a 100-hour error exerts the exact same step-size push (1/N) as a 2-hour error! Right at e = 0, the V-shape has a sharp corner with no classical derivative, so automatic differentiation uses a standard subgradient value (0 by convention at zero).
| Errors included | MSE | MAE |
|---|---|---|
| First four: 2, -3, 4, -2 | 8.25 | 2.75 |
| All five, including 100 | 2,006.6 | 22.2 |
Binary cross entropy scores the probability of the true label
Now shift the question from "how many hours?" to "is the ticket urgent?" Let the target y equal 1 for urgent and 0 for normal, while the model predicts a probability p inside (0, 1) that the ticket is urgent. Squared error fits badly on probability confidence near the boundary. Instead, cross entropy asks one pointed question: how much probability q did the model place on the answer that actually happened?
When the ticket is truly urgent (y = 1), the true answer's probability is q = p. When it is normal (y = 0), the true answer's probability is q = 1 - p. Cross entropy turns q into a loss with -ln(q) (the negative natural logarithm, base e). At q = 1.0, -ln(1) = 0, so confident right answers cost nothing. At 50/50 uncertainty (q = 0.5), -ln(0.5) ≈ 0.693. Slide q down toward 0, and -ln(q) climbs steeply (2.303 at 0.1, 4.605 at 0.01) without any upper ceiling:
Computed from q = 0.01 (confident mistake) to q = 1.0 (certain match)
Why classifiers strongly avoid overconfident mistakes: dropping true-class probability from 0.9 to 0.5 nudges loss from 0.105 to 0.693, whereas dropping to 0.01 spikes penalty up to 4.605.
| probability q given to true label | Negative log loss: -ln(q) |
|---|---|
| 0.01 | 4.605 |
| 0.05 | 2.996 |
| 0.1 | 2.303 |
| 0.2 | 1.609 |
| 0.3 | 1.204 |
| 0.4 | 0.916 |
| 0.5 | 0.693 |
| 0.6 | 0.511 |
| 0.7 | 0.357 |
| 0.8 | 0.223 |
| 0.9 | 0.105 |
| 1 | 0 |
Rather than writing an if / else branch to swap between -ln(p) and -ln(1 - p), binary cross entropy packs both branches into a smooth algebraic switch controlled by y:
Plug in y = 1: (1 - y) equals zero, canceling the right term and leaving -ln(p). Plug in y = 0: y vanishes, leaving -ln(1 - p). On an urgent ticket predicted with p = 0.9, true-label probability is 0.9, so loss is 0.105. On a normal ticket with that same urgent probability p = 0.9, true-label probability shrinks to 1 - 0.9 = 0.1, pushing loss up more than twenty-fold to 2.303:
| True label | Urgent probability p | Probability of true label | Loss |
|---|---|---|---|
| Urgent (1) | 0.9 | 0.9 | 0.105 |
| Urgent (1) | 0.01 | 0.01 | 4.605 |
| Normal (0) | 0.1 | 0.9 | 0.105 |
| Normal (0) | 0.9 | 0.1 | 2.303 |
Choosing -ln(q) is not arbitrary either. Suppose two independent tickets receive true-label probabilities 0.9 and 0.8: the joint probability of predicting both right is their product 0.9 * 0.8 = 0.72. Across a thousand tickets, multiplying probabilities underflows near zero. Taking -ln converts that product cleanly into a sum of losses (-(ln 0.9 + ln 0.8) = 0.105 + 0.223 = 0.329), turning maximum likelihood estimation into simple gradient minimization. We will unpack that likelihood and KL-divergence view closely in Part 6.
Why binary classification should pass logits to the loss
Recall from Part 3 and Part 4 that a classifier's final Linear layer emits an unrestricted logit z, and sigmoid maps it into (0, 1) via p = sigma(z) = 1 / (1 + e^(-z)) (for instance, z ≈ 2.2 gives p ≈ 0.9). Passing logits through sigmoid is perfect for displaying a probability at inference. During training, computing sigmoid first and feeding p into a separate log loss breaks at extreme confidence.
Trace an urgent ticket (y = 1) where the model emits a terribly confident wrong logit z = -1000. Evaluating sigmoid(-1000) in 32-bit floating-point rounds the minuscule probability (~10^-434) flatly down to 0.0. Feeding 0.0 into a standalone logarithm produces ln(0) = -infinity, so PyTorch's probability-based nn.BCELoss clamps its log output at -100 and reports a capped loss of 100.0 (with zero useful slope left to pull z back up!) even though the true mathematical loss is about 1000.0.
How does PyTorch avoid both 0.0 underflow AND e^(+1000) overflow inside Softplus? Substitute p = 1 / (1 + e^(-z)) directly into -ln(p) for y = 1: reciprocal turns -ln(1 / (1 + e^(-z))) cleanly into ln(1 + e^(-z)) = softplus(-z). Then factor out the larger magnitude cleanly with softplus(x) = max(x, 0) + ln(1 + e^(-|x|)). At z = -1000 (x = +1000), that computes 1000 + ln(1 + e^(-1000)) ≈ 1000.0 directly without ever forming e^(+1000) or rounding sigmoid to zero:
Extending the same identity to both y = 1 and y = 0 yields softplus(z) - y * z (equivalently max(z, 0) - z * y + ln(1 + e^(-|z|))). Give PyTorch's nn.BCEWithLogitsLoss() the raw logit z during training, and apply torch.sigmoid(z) only when inspecting probabilities for decisions or charts.
Multiclass cross entropy scores the correct class
Now move to the third ticket question: choosing which one of four mutually exclusive categories handles this issue (billing, login, bug, or feature). The final linear layer emits four unbounded logits, say [1.2, 3.7, 0.4, -0.8]. Here index 1 (login, logit 3.7) sits highest, yet raw logits can be negative and need not sum to 1.
Softmax exponentiates each score z_k ([3.320, 40.447, 1.492, 0.449]) and divides by their total (45.709), turning those four logits into probabilities [0.073, 0.885, 0.033, 0.010]. Because the true category is login (0.885), multiclass cross entropy applies the exact same -ln(q) rule to p_correct:
Since p_login = 0.885, the ticket's cross-entropy loss is -ln(0.885) ≈ 0.122. Just as in the binary case, 0.99 yields 0.010, 0.5 yields 0.693, and 0.01 jumps to 4.605. Binary cross entropy is simply the two-outcome case of the exact same -ln(probability of truth) principle.
Log-softmax explains PyTorch's cross-entropy contract
Look inside p_k = e^(z_k) / sum_j e^(z_j) when you take ln(p_k). Division inside a logarithm splits into subtraction, and ln cancels e in the numerator directly: ln(p_k) = z_k - ln(sum_j e^(z_j)). That operation is log-softmax. For our login ticket, ln(45.709) ≈ 3.822, so ln(p_login) = 3.7 - 3.822 = -0.122, and negating it recovers the exact cross-entropy loss +0.122.
In PyTorch, negative log likelihood loss (NLLLoss) expects those negative log-probabilities directly, indexes out the target class entry, and flips the sign. That makes nn.CrossEntropyLoss() strictly equivalent to LogSoftmax + NLLLoss fused cleanly together (using the max-shift trick m = max(z) inside ln(sum e^(z_j - m)) + m as derived in Part 4 so huge logits never overflow).
That fused architecture also explains why never calling Softmax before nn.CrossEntropyLoss() matters so much. Feed [0.073, 0.885, 0.033, 0.010] into CrossEntropyLoss, and PyTorch normalizes a second time inside (0, 1), compressing p_login down to 0.437 and reporting a distorted loss of 0.827 (~0.83) instead of 0.122! Raw logits go into CrossEntropyLoss:
Put the right values into each PyTorch loss
Every PyTorch loss module enforces a strict model-output and target contract shaped directly by the prediction task you are solving:
| PyTorch loss | Model output | Target |
|---|---|---|
MSELoss | Predicted continuous value | Floating-point value with matching shape |
L1Loss | Predicted continuous value | Floating-point value with matching shape |
BCEWithLogitsLoss | One raw logit per binary label | Floating-point 0 or 1, matching shape |
CrossEntropyLoss | One raw logit per class | Integer class index |
NLLLoss | Log-probability per class | Integer class index |
Notice how clearly the API names document those contracts: MSELoss expects predictions and floating-point targets of matching shape, L1Loss is PyTorch's name for MAE, BCEWithLogitsLoss explicitly names the raw-logit input, and CrossEntropyLoss runs LogSoftmax + NLLLoss inside a single logit-taking module (leaving NLLLoss for models whose forward pass already returns LogSoftmax).
import torch.nn as nn# Regression: prediction and floating-point target share a shaperegression_loss = nn.MSELoss() # or nn.L1Loss()loss = regression_loss(predicted_hours, target_hours)# Binary: raw logits and float targets containing 0 or 1binary_loss = nn.BCEWithLogitsLoss()loss = binary_loss(urgent_logit, urgent_target)# Multiclass: raw logits and integer class indicesclass_loss = nn.CrossEntropyLoss()loss = class_loss(category_logits, category_index)
Try changing the errors and logits
Run this browser-side Python lab using only the standard library. Try switching the final ticket error between 4 and 100 to watch MSE explode while MAE climbs steadily, pass z = -1000.0 into the stable softplus binary form (1000.000 with zero overflow), and compare correct multiclass cross-entropy (0.122) against the double-softmax bug (0.827):
from math import exp, log, log1pdef softplus(x):# Stable form of log(1 + exp(x)) avoiding overflow for large |x|return max(x, 0.0) + log1p(exp(-abs(x)))# Edit this last error to see outlier sensitivity.errors = [2.0, -3.0, 4.0, -2.0, 100.0]mse = sum(error * error for error in errors) / len(errors)mae = sum(abs(error) for error in errors) / len(errors)print(f"MSE across five tickets: {mse:.2f}")print(f"MAE across five tickets: {mae:.2f}")# Binary classification: y=1 means urgent. Try z=-1000.0!z, y = -2.0, 1.0binary_loss = softplus(z) - y * zprint(f"Binary loss for logit {z:g}, target {y:g}: {binary_loss:.3f}")# Multiclass: class 1 (login) is correct. Compare raw logits vs double-softmax mistake.logits, target = [1.2, 3.7, 0.4, -0.8], 1largest = max(logits)exps = [exp(value - largest) for value in logits]denom = sum(exps)probs = [e / denom for e in exps]log_sum_exp = largest + log(denom)cross_entropy = log_sum_exp - logits[target]exps2 = [exp(p) for p in probs]double_softmax_loss = -log(exps2[target] / sum(exps2))print(f"Login cross-entropy (raw logits): {cross_entropy:.3f}")print(f"Double-softmax trap (probs passed): {double_softmax_loss:.3f}")
Every loss function encodes what kinds of mistakes deserve the strongest correction. Squaring amplifies large numerical errors (slope = 2e), absolute value paces error linearly (slope = ±1), and cross entropy penalizes -ln(q) directly against the probability assigned to truth while relying on logit-based PyTorch implementations to preserve gradients cleanly across extreme values.
Once the prediction task is clear, selecting the starter loss becomes automatic: MSE or MAE for continuous targets, binary cross entropy (BCEWithLogitsLoss) for yes-or-no decisions, and multiclass cross entropy (CrossEntropyLoss) for one choice among exclusive categories. In Part 6 of this series, we open the hood on why classification losses use the natural logarithm, how the log-sum-exp trick prevents floating-point overflow, and how KL divergence generalizes cross-entropy to full probability distributions.
References
- [1]MSELoss · PyTorch documentationDefinition, reductions, and input and target shapes.
- [2]L1Loss · PyTorch documentationAbsolute-error definition and reduction behavior.
- [3]BCEWithLogitsLoss · PyTorch documentationBinary cross entropy combined with sigmoid for numerical stability.
- [4]BCELoss · PyTorch documentationProbability-based binary cross entropy and its log-output clamp.
- [5]CrossEntropyLoss · PyTorch documentationRaw logits and class-index targets for multiclass classification.
- [6]NLLLoss · PyTorch documentationNegative log likelihood expects log-probabilities.







