Loss, in perspective.
All five chapters, including worked answers and static lab comparisons. This edition loads no JavaScript.
01
Errors into a number
A prediction can miss in many ways. A loss function decides how those misses count.
Three points. One imperfect line.
A model predicts 2 when the target is −1. On another example, it predicts 2.5 instead of 1. On a third, it gets 3 exactly right. Before we can improve the model, we need a consistent answer to a deceptively simple question: how bad is this set of predictions?
Our running example uses three invented, noiseless data points: A is , B is , and C is . In each pair, the first number is the input and the second is the target . We predict with a line:
The hat marks a prediction. The parameter controls the line's slope; , its intercept. Start with and . These choices produce the three predictions above. They are hand-picked teaching values, not the result of training.
Invented data, exact calculation (CL-005). Filled dots are targets; hollow dots are predictions. The line is ŷ = 0.5x + 2.5. Error means prediction minus target, so these gaps are nonnegative.
Measure the miss, then assign a penalty
Define the residual as prediction minus target:
The subscript identifies an example. A positive residual means overprediction under this sign convention; a negative one means underprediction. The residuals here are 3, 1.5, and 0. Simply adding signed residuals could let opposite mistakes cancel.
A per-example loss assigns a penalty to a prediction and its target. Squared loss uses , making either sign of error count positively. Our three penalties are therefore 9, 2.25, and 0.
Combine them with a mean to obtain mean squared error, or MSE. With scalar-output examples:
This is the squared-loss mean convention used throughout this guide: no extra factor of one half and no regularization term. The summation symbol says to add the penalties before dividing by the number of examples.
The reduction is part of the definition
A reduction is the rule that combines individual penalties. The sum here is 11.25; the mean is 3.75. Neither number is wrong, but they are not interchangeable. Duplicate every unchanged example and the sum doubles, while the mean stays 3.75.
We will use for an individual penalty and for the combined objective. In practice, “loss” often names either, so check the definition before comparing reported values. You now know where one loss number comes from. Next: why square the errors at all?
02
Different penalties
The same residual can receive very different penalties. That choice changes what improvement means.
How fast should a mistake grow?
An error of magnitude 3 receives squared loss 9. An error of magnitude 1 receives squared loss 1. Tripling the miss makes its penalty nine times as large. Squared loss makes large residuals contribute disproportionately to the total.
A different choice is absolute loss, . The vertical bars mean magnitude, ignoring sign. Errors of magnitude 3 and 1 receive penalties 3 and 1. Averaging absolute penalties gives mean absolute error, or MAE. See the absolute-loss definition and reductions.
Both losses treat +3 and −3 equally. Their difference is how the penalty grows with magnitude. If every residual doubles, MAE doubles but MSE quadruples. That is a property of the formulas, not evidence that one model suddenly became four times less useful.
A quadratic center, linear tails
Huber loss joins two behaviors: a quadratic penalty close to zero and a linear penalty farther away. Its threshold marks the change. Set for this comparison:
The one-half factor is intentional; our MSE does not have it. At either join, both branches give 0.5, and their slopes agree. Beyond the threshold, the penalty grows linearly instead of quadratically, making Huber less sensitive to large residuals than squared loss. This is the documented Huber definition at a specific threshold.
Solid: squared (at e=3: 9). Dashed: absolute (3). Dotted: Huber, δ=1 (2.5). These are analytic penalty shapes, not measured model performance. Different scales are part of the definitions; a lower line is not a better model.
Absolute loss has a sharp corner at zero: its ordinary derivative is undefined there. Huber has a smooth join in its first derivative. A corner does not mean a loss cannot be optimized; it means the optimizer must handle that boundary appropriately.
Smaller numbers are not a quality ranking
At residual 3, the plotted penalties are 9, 3, and 2.5. Huber's lower number does not make the unchanged prediction better. We have changed the measuring rule.
Before comparing loss values, match the definition, reduction, target scale, and evaluated examples. If a target carries physical units, absolute loss has those units and squared loss has their square. Choosing a penalty means choosing which error patterns to emphasize; no curve here establishes a universally best choice.
The horizontal axis so far has been the residual. We have asked what penalty an error earns. A model has a different question: which parameter choices produce smaller errors? That change of axes creates a loss landscape.
03
A landscape of choices
Two parameters choose the predictions. Their mean loss becomes the height of a surface.
Change the axes, keep the data
Return to our three fixed points and squared loss. Every pair defines a different line, three predictions, and one mean loss. Place on one horizontal axis and on the other. Put the resulting above that location. The collection of heights is a loss surface.
Expanding the three residuals and averaging their squares gives this exact expression for our invented example:
The lowest point is , where both squared terms vanish. This particular line passes through all three targets. The surface is an analytic calculation—not a measured neural-network landscape or a history of training.
Move the model, not just the camera
The 3D view makes both parameter directions visible. The linked 2D plot cuts through the same surface at the current , showing loss as varies. Use that flat slice and the numerical table for precise comparisons; depth and viewing angle can make heights harder to judge.
Changing a parameter recomputes the predictions and losses. Changing the view angle only rotates the projection: it cannot improve the model. The mesh samples the exact formula above, with a fixed height scale. These controls do not train a network.
Two parameters, one height.
Three invented points. Exact mean squared error. A sampled 3D projection—not a measured neural-network landscape.
Make a prediction first (optional)
Mean squared error
Hold bias fixed. Vary only weight.
Weight 0.5, bias 2.5: mean loss 3.750. With this bias held fixed, the lowest possible loss is 2.250, at weight 2. View angle 45° changes only the projection.
| Point / x | Target y | Prediction | Error e | Squared e² |
|---|---|---|---|---|
| A / -1 | -1 | 2.000 | 3.000 | 9.000 |
| B / 0 | 1 | 2.500 | 1.500 | 2.250 |
| C / 1 | 3 | 3.000 | 0.000 | 0.000 |
| Mean of the three squared errors | 3.750 | |||
The mesh samples a smooth mathematical surface. Perspective can obscure heights; the flat slice and numbers provide the exact reading. Heights use one fixed scale, 0 to 6.667, throughout this control window. No optimizer runs when you move a slider.
Compare three fixed states
| Weight | Bias | Mean loss | What changed? |
|---|---|---|---|
| 0.5 | 2.5 | 3.750 | Starting model |
| 2 | 2.5 | 2.250 | Best weight at this bias |
| 2 | 1 | 0.000 | Both parameters fit the toy |
The first move removes the weight error. The remaining bias error still costs 2.25. Only the final state fits all three points.
A slice has its own floor
At the defaults, and , loss is 3.75. Change only to 2. Loss falls to 2.25, but stops short of zero: the remaining term is . Then change to 1 and both terms disappear.
More generally, a fixed bias leaves a floor of , reached at . Try a changed case: if you fix , what is the lowest loss achievable by varying weight?
Check the changed-bias case
The best weight is still , but the remaining bias term is . The surface's global minimum and a slice's minimum are different ideas.
Where did the simple landscape formula come from?
Let and . The three residuals become , , and . Their cross terms cancel:
This clean separation follows from these particular inputs and targets. It is not a formula for every regression dataset.
Our bowl has one minimum. Do not generalize its shape to neural networks: their objectives can be nonconvex, as discussed in Deep Learning, §8.2.2. Even on this simple surface, finding a direction and choosing how far to move are separate decisions.
04
Following the slope
A gradient describes local change. A learning rate decides how far to trust that direction.
Read the local slope
A derivative describes how quickly a quantity changes near the current input. With two parameters, a partial derivative varies one while holding the other fixed. The gradient collects these partial derivatives into a vector.
Differentiate our MSE expression with respect to and :
At the starting point , the gradient is . A small increase in lowers loss locally; a small increase in raises it. The negative gradient therefore points toward increasing and decreasing .
Direction is not distance
Gradient descent proposes a step opposite the gradient. Write all parameters together as and choose a positive learning rate :
The gradient describes local slope, not the entire path ahead. A finite step can go too far and raise loss. See the update and curvature discussion in Deep Learning, §4.3.
Try two independent single steps from the same starting point. With :
The new loss is , down from 3.75. But produces , with loss 4.95—higher than the starting value.
Derived from the same toy, always starting at w=0.5, b=2.5 (CL-009). Each point is a separate one-step experiment, not the next step in a training history. The larger-rate example is evaluated without clipping parameters to the lab window.
The horizontal axis is the candidate step size. Every plotted point starts from the same parameters and takes one step; these are not successive updates or epochs. The second bias, −1.1, is outside the interactive surface's viewing window. The mathematical calculation is not clamped to that window.
Reproduce one step
The canonical JavaScript module computes losses directly from the three data rows. With Node.js and the local companion module in the same folder, this focused excerpt reproduces the smaller step:
import { gradientStep } from './model.mjs';
const next = gradientStep({
weight: 0.5, bias: 2.5, rate: 0.25
});
console.log(next.loss.toFixed(3)); // 1.229
The displayed value is deterministic toy arithmetic, rounded to three decimals. There is no network, random initialization, or training dataset download. The rate is a demonstration choice, not a recommendation for another model.
A training-loss curve would instead place update number or epoch on its horizontal axis and record the losses encountered during optimization. Always read the axes before interpreting a “loss curve.” And even a well-behaved downward curve leaves another question: is its loss measuring the task we care about?
05
Probabilities and purpose
A loss can reward better probability assignments without matching a thresholded score—or proving generalization.
A different kind of prediction
Leave the line-fitting example. In binary classification, the target is either 0 or 1. Suppose a model predicts a probability for class 1. This is not an unrestricted real-valued prediction or a raw logit: lies between 0 and 1.
Binary cross-entropy, also called binary log loss, evaluates the probability assigned to the observed label. With natural logarithm , for :
If , this becomes . If , it becomes . In either case, assigning more probability to the observed label lowers the penalty. The binary formula and natural-log convention make the meaning precise.
Analytic −ln(p), with true label y=1. The plotted curve starts at p=0.01; it continues upward without bound as p approaches 0. Natural logs, no probability clipping; not a replica of a library's numerical safeguards.
For a positive target, probabilities 0.1, 0.5, and 0.9 produce losses about 2.303, 0.693, and 0.105. The theoretical loss approaches infinity as approaches zero, and is zero at . The finite plot begins at 0.01; it does not turn that infinite boundary into a finite penalty.
Mathematical endpoints versus library safeguards
The companion uses the theoretical limits: a perfectly correct endpoint has loss zero; a confidently wrong endpoint has infinite loss. Actual APIs may protect numerical calculations. PyTorch 2.8 BCELoss clamps logarithm outputs, while scikit-learn's log_loss clips probabilities. Our helper does not reproduce those endpoint safeguards.
Same loss, different decisions
Try a new, invented case. The true labels are . Model A predicts positive-class probabilities ; model B predicts . Predict class 1 whenever , otherwise class 0.
Which model has lower mean binary cross-entropy? Which has higher accuracy—the fraction of labels predicted correctly? Work out both before revealing the answer.
Compare the two answers
A assigns probabilities 0.9 and 0.4 to the correct labels. B assigns 0.6 and 0.6. Both products are 0.36:
But A's predicted labels are , so it gets one of two right. B predicts , getting both right. Equal mean loss does not imply equal accuracy. Accuracy counts decisions, while log loss also responds to the probabilities behind them. The fraction-correct definition is documented in accuracy_score.
The objective is not the whole task
A low training loss describes fit to training examples; it does not by itself establish performance on unseen data. Validation data can inform model choices, while a separate test set supports evaluation without tuning those choices to it. The cross-validation guide explains why reusing training or test data for the wrong role can mislead.
Our line achieved zero loss on three invented points. We supplied no held-out examples, so that result says nothing about generalization. Even a real holdout gives evidence under its sampling conditions, not a guarantee for every deployment setting.
Keep three questions separate: what does each error cost, how are those costs combined, and what evidence shows the resulting model serves the task? A loss function answers the first two. Good evaluation is still needed for the third.
Glossary
- Prediction
- A model's proposed output. In the regression toy, .
- Target
- The output against which a prediction is evaluated. The regression targets are invented scalar values; the classification targets are labels 0 or 1.
- Residual
- Prediction minus target in this guide. Squared and absolute losses ignore its sign, but other formulas may not.
- Per-example loss
- A penalty assigned to one prediction and its target.
- Reduction
- The operation combining individual losses, such as their sum or mean. A different reduction changes the numeric scale.
- Objective
- The scalar being minimized. Here it is the mean of per-example losses, without an additional regularization term.
- MSE
- Mean squared error: for the scalar-output examples used here. There is no one-half factor in this guide's convention.
- MAE
- Mean absolute error: .
- Huber loss
- A penalty with a quadratic center and linear tails. At threshold , the center is and the tails are .
- Parameters
- The slope and intercept of the toy prediction line. Unlike inputs and targets, these are the choices being varied to change its loss.
- Loss surface
- Loss as a function of parameter choices with the evaluated data fixed. Our 3D rendering uses two parameter axes and loss as height.
- Parameter slice
- A view of loss with one parameter held fixed while another varies. Here a fixed bias leaves a minimum slice loss of .
- Gradient
- The vector of partial derivatives of loss with respect to the parameters, describing local sensitivity.
- Learning rate
- The step-size multiplier in a gradient update. An overly large step can increase loss.
- Training-loss curve
- A record of loss over optimization updates or epochs. Its horizontal axis is not the same as a residual axis, parameter axis, or candidate learning-rate axis.
- Binary cross-entropy
- The negative natural logarithm of the probability assigned to the observed binary label. The guide uses the theoretical scalar formula and endpoint limits.
- Accuracy
- The fraction of predicted labels that match the targets. A probability-to-label decision rule must be specified separately.
- Generalization
- Performance beyond the training examples. Training loss alone is insufficient evidence; held-out evaluation has its own sampling and use assumptions.
Sources
- PyTorch 2.8 — MSELoss
Squared-loss definition and mean/sum reductions. Our scalar-output toy uses a mean with no half factor; this is a pinned version, not a claim about the latest release.
- PyTorch 2.8 — L1Loss
Absolute-loss definition and reductions. The discussion of the corner and slopes follows directly from its absolute-value formula.
- PyTorch 2.8 — HuberLoss
Piecewise loss and threshold parameter. Our comparison sets delta to 1 and preserves the quadratic branch’s one-half factor.
- Deep Learning — Chapter 4: Numerical Computation
Goodfellow, Bengio, and Courville (2016), §4.3, equation 4.5, figure 4.4, and equation 4.9. Gradient descent, step size, and local curvature; no universal learning-rate recommendation is inferred.
- Deep Learning — Chapter 8: Optimization for Training Deep Models
§8.1 separates the per-example loss, empirical objective, and generalization concerns; §8.2.2 discusses nonconvex neural-network objectives. The toy bowl is not presented as a generic network landscape.
- scikit-learn 1.7.2 — log_loss
Binary log-loss formula and natural-log convention. The documented API clips probabilities; the companion instead preserves theoretical endpoint limits.
- PyTorch 2.8 — BCELoss
Discussion of logarithmic endpoints and log-output clamping. This distinction prevents confusing the guide’s infinite theoretical endpoint with a library safeguard.
- scikit-learn 1.7.2 — accuracy_score
Fraction-correct accuracy definition. The transfer example supplies its own explicit positive-probability threshold of 0.5.
- scikit-learn 1.7.2 — Cross-validation: evaluating estimator performance
Opening discussion of overfitting, validation, and a separate test set. The guide contains no measured generalization result.