Deep LearningLoss Functions and Regression
How do Huber loss and mean squared error (MSE) differ for neural-network regression?
Question 302 of 314 · Updated
On this page
MSE squares every residual, so a few very large errors can dominate the training signal. Huber loss behaves quadratically for small errors and linearly after a configurable threshold, reducing the influence of extreme residuals while keeping a smooth gradient near zero. The right choice depends on whether large errors are noise to resist or important events the model must learn.
This lesson extends Deep Learning Question 72 (mean squared error) into a practical loss-selection decision for neural-network regression. It does not replace the separate evaluation metrics used to judge the final model.
1. What does each loss optimize?#
Let the prediction error for one target be:
e = prediction - target
Mean squared error (MSE) squares every residual:
For a batch with N elements, the usual mean reduction is:
A residual twice as large contributes four times as much loss. Its gradient also grows with the residual magnitude.
Huber loss uses a quadratic region around zero and a linear region outside a threshold :
The parameter determines where the loss changes shape. A smaller threshold makes the loss enter its linear region earlier; a larger threshold makes it behave quadratically over a wider range.
The corresponding per-element gradients with respect to the prediction are:
- MSE:
2e - Huber:
ewhen ; otherwise
With mean reduction, the batch gradient is averaged over the elements. Huber therefore caps the magnitude of the gradient contributed by a large residual at per element, while the MSE gradient continues growing with |e|.
Implementation detail: PyTorch's MSELoss uses the squared residual, while HuberLoss uses the half-squared expression inside the threshold. Their raw loss values are consequently on different scales. Do not compare the numerical loss values as if they were the same metric.
2. The practical differences#
- Sensitivity to outliers: MSE gives extreme residuals quadratic influence. Huber reduces their growth to linear after .
- Gradient behavior: MSE gradients grow without a residual-based cap. Huber gradients are bounded per element outside the threshold.
- Near-zero behavior: MSE and Huber are both smooth and quadratic around zero, although their conventional formulas differ by a factor of two in that region.
- Threshold choice: MSE has no transition parameter. Huber requires a that is meaningful for the scale of the target.
- Statistical assumptions: MSE is a natural choice when squared error is the intended objective and large errors deserve strong penalties. Huber is useful when the residual distribution contains occasional extreme values that should not dominate every update.
- Interpretability: MSE directly optimizes average squared error. Huber optimizes a robust hybrid objective; it is not the same as minimizing MAE or RMSE.
Huber loss is not an automatic outlier-removal mechanism. Large residuals still contribute to the loss and can still affect the model; their influence grows linearly rather than quadratically.
3. Numerical example: one large residual#
Assume a regression batch has three prediction errors:
e = [1, -1, 10]
Use Huber loss with .
MSE calculation
- Error 1:
- Error 2:
- Error 3:
- Mean MSE:
(1 + 1 + 100) / 3 = 34
Huber calculation
Because the first two residuals are inside the threshold, each contributes .
The third residual is outside the threshold:
- Error 1:
0.5 - Error 2:
0.5 - Error 3:
18 - Mean Huber loss:
(0.5 + 0.5 + 18) / 3 = 6.33
Compare the outlier's gradient contribution
For the residual of 10:
- MSE gradient:
- Huber gradient:
The large residual contributes a gradient ten times smaller under this Huber setting. For the full three-element mean, the corresponding contribution is divided by three in both cases.
The lower Huber loss number does not mean the model is automatically better. The two objectives have different scales and shapes. Compare models using the same held-out evaluation metrics and business-relevant error slices.
4. Production example: demand forecasting with sensor spikes#
Illustrative incident: A team trains a neural network to forecast hourly energy demand. Most targets are reliable, but a small number of readings contain extreme spikes caused by a sensor reset. During training, the MSE loss is dominated by those few rows. The model begins spending disproportionate capacity fitting the corrupted observations, while accuracy on ordinary operating hours deteriorates.
The team should not immediately switch to Huber. First it must determine whether the extreme values are corrupted measurements or genuine demand peaks.
Root-cause investigation
- Trace extreme residuals to source records. Join the worst prediction errors to sensor status, ingestion timestamps, device resets, and upstream data-quality flags.
- Separate valid peaks from bad labels. A genuine demand surge is important business behavior; a sensor-reset artifact is not a target the model should imitate.
- Inspect residual distributions by segment. Compare median, 90th, 95th and 99th percentile absolute errors across normal hours, peak hours, sites, and device types.
- Check target scaling. A threshold of 2 means something very different when targets are raw kilowatts versus standardized z-scores.
- Inspect per-example loss and gradient contributions. Confirm that a small number of extreme residuals are dominating updates rather than assuming that from the aggregate loss alone.
- Verify the training pipeline. Check missing-value masks, sample weights, target transformations, reduction settings, and whether training and validation apply the same inverse transformation.
Engineering solution
- Correct or exclude confirmed sensor corruption using an auditable data-quality rule; do not silently remove legitimate peak events.
- Train a controlled MSE baseline and a Huber variant on the same data split, initialization policy, training budget, and optimizer configuration.
- Select using residual distributions on the training data and a validation sweep. Express the threshold in the model's target units.
- Monitor MAE and RMSE, plus peak-hour and high-percentile error slices. Keep the evaluation metrics fixed across experiments even when the training loss changes.
- If large peaks are legitimate and operationally costly, consider event-aware sample weighting, a separate peak model, or a suitable quantile/objective design instead of simply suppressing their influence.
Expected trade-off: Huber can stabilize learning on mostly normal observations when a minority of labels are extreme or noisy. It can also under-emphasize legitimate rare peaks if is too small. The engineering decision must reflect the cost of each error type.
5. How should you choose the Huber threshold?#
The threshold is not a universal constant.
- Start with the target scale. If targets are standardized, document the transformation and interpret in standardized units. If targets are not normalized, the threshold is in the original unit.
- Inspect residuals, not just target values. The transition applies to prediction residuals. Use training residuals and a validation sweep rather than choosing a value from intuition alone.
- Run a small threshold experiment. Compare several plausible values around the residual distribution's central range and inspect both aggregate and tail metrics.
- Check learning dynamics. A threshold that is too small can cap gradients for many examples and slow correction of large but valid errors. A threshold that is too large makes Huber behave more like a quadratic objective for most observations.
- Keep evaluation independent. Select the loss using validation results, then report business-facing metrics such as MAE, RMSE, and peak-period error on an untouched test set.
If target units or target scaling change between model versions, revisit . Reusing the same numeric threshold after a rescaling can silently change the objective.
6. Minimal PyTorch implementation#
PYTHONimport torch import torch.nn as nn # Predictions and targets must have matching shapes. predictions = model(inputs) targets = targets.float() mse_loss_fn = nn.MSELoss(reduction="mean") huber_loss_fn = nn.HuberLoss( delta=2.0, # In the same units as the residuals reduction="mean" ) loss = huber_loss_fn(predictions, targets) optimizer.zero_grad(set_to_none=True) loss.backward() optimizer.step()
For a controlled comparison, change only the loss function and keep the data split, preprocessing, model, optimizer, schedule, and training budget consistent. If targets are standardized, choose delta in that standardized space.
For debugging, inspect unreduced losses:
PYTHONper_element_loss = nn.HuberLoss( delta=2.0, reduction="none" )(predictions, targets) print("mean:", per_element_loss.mean().item()) print("max:", per_element_loss.max().item())
For multi-output regression, remember that reduction="mean" averages over tensor elements, not necessarily over business entities or samples in the way your reporting pipeline expects. Apply masks and sample weights deliberately when targets are missing or examples have different importance.
7. Common mistakes#
- Treating Huber as outlier deletion: It still learns from large residuals; their loss grows linearly.
- Choosing without checking units: The default is a software default, not a universal statistical recommendation.
- Comparing raw training-loss values: MSE and Huber have different scales. Compare validation metrics calculated identically.
- Using Huber to hide data-quality defects: Investigate corrupted labels and sensor failures at their source.
- Suppressing rare but important events: A low threshold may reduce the training signal for valid peaks, faults, or safety-critical extremes.
- Changing loss and optimizer settings together: This makes it difficult to identify why a training run improved or regressed.
- Reporting only aggregate MAE or RMSE: Segment-level and tail errors can reveal failures hidden by an average.
8. Decision guide#
Choose MSE when large errors should receive rapidly increasing penalties, the labels are sufficiently reliable, and squared-error behavior matches the business objective.
Choose Huber when occasional extreme residuals are present, you want to limit their gradient influence, and small residuals should still receive a smooth quadratic penalty.
Neither loss is universally superior. Validate the choice against the distribution of errors and the real cost of under-predicting or over-predicting important cases.
Key takeaway: MSE makes the influence of a residual grow quadratically. Huber changes to linear growth beyond , making neural-network training less dominated by extreme residuals. The threshold must be tuned to the target scale, and valid rare events must remain visible in evaluation.
Semantic deduplication / curriculum positioning: Deep Learning Question 72 already introduces MSE, and Question 64 covers model evaluation. This supplemental comparison is distinct: it explains the Huber transition threshold, gradient behavior, a worked batch calculation, and a production loss-selection/debugging workflow. The general MAE-versus-RMSE comparison already exists in the Machine Learning curriculum, so it was not duplicated on this Deep Learning page.
Sources: PyTorch HuberLoss documentation; PyTorch MSELoss documentation; The Elements of Statistical Learning — discussion of robust loss and Huber loss.
References
- 1.docs.pytorch.org — torch.nn.modules.loss.HuberLossdocs.pytorch.org
- 2.docs.pytorch.org — torch.nn.modules.loss.MSELossdocs.pytorch.org
- 3.hastie.su.domains — ElemStatLearnhastie.su.domains
Related questions
Explore other topics:Machine LearningLarge Language Models