Deep Learning Loss Function Design

A regression model trained to minimize squared error can make different predictions from the same model trained to minimize absolute error. The loss specifies which errors training penalizes and how strongly. This article follows those choices through regression, classification, class weighting, label smoothing, and objectives with several terms. Architecture, sampling, and regularization also shape the result.

Loss, cost, and objective

Here, loss \(\mathcal L(\hat y,y)\) refers to one example, cost \(J\) to its aggregate over a batch or dataset, and objective to the quantity optimized, including any regularization. Terminology varies across libraries: a function named โ€œlossโ€ may already return a batch mean. Check its reduction before adding another average.

For \(m\) examples, \(J_{\rm mean}=m^{-1}\sum_i\mathcal L_i\) and \(J_{\rm sum}=\sum_i\mathcal L_i\), so their data-loss gradients differ by a factor of \(m\). With plain gradient descent and no other changes, summing is equivalent to multiplying the learning rate by \(m\). This equivalence does not generally extend to adaptive optimizers or gradient clipping, and an unchanged regularization term changes its strength relative to the data loss.

For outputs with several elements, also check what is averaged. Squared errors \([1,9]\) and \([4,16]\) for two examples give 7.5 when averaged over all four elements, but 15 when summed within each example and then averaged across examples. For padded sequences, exclude padding from both the loss sum and its denominator; averaging tokens weights long sequences more than averaging each sequence first.

The binary and multiclass cross-entropy derivations are in Logistic Regression and Softmax and Multiclass Classification. Here we use their gradients to compare objective choices.

Regression losses and their sensitivity to outliers

Let \(e=\hat y-y\) be the scalar prediction error. Squared error \(\mathcal L=e^2\), averaged to form MSE, has derivative \(2e\) with respect to \(\hat y\). A residual of 100 gives derivative 200; a residual of 1 gives 2. Parameter gradients also multiply by \(\nabla_\theta\hat y\), where \(\theta\) denotes the model parameters, so the comparison does not by itself tell us how much each example changes the weights.

Absolute error \(\mathcal L=|e|\), averaged to form MAE, has derivative \(\operatorname{sign}(e)\) for nonzero \(e\): +1 for positive residuals and โˆ’1 for negative ones. At zero it has no ordinary derivative; a subgradient can be chosen from \([-1,1]\), commonly zero. Increasing an already large residual does not increase this output derivative. Fixed-step subgradient updates can oscillate near a minimum, although smaller steps or other optimization methods can address this.

These losses target different population quantities. At a fixed input \(x\), the conditional expected squared error is minimized by \(\mathbb E[Y\mid X=x]\) when the conditional second moment is finite. Expected absolute error is minimized by any conditional median when the first absolute moment is finite. A restricted network fitted to finite data need not recover either exactly. For a constant fit to \([1,2,9]\), squared error chooses the sample mean 4 and absolute error chooses the median 2.

Huber loss is quadratic for \(|e|\le\delta\) and linear outside, with a positive threshold \(\delta\) in the target’s units:

\[\mathcal{L}_\delta(e)=\begin{cases}\tfrac{1}{2}e^2 & |e|\le\delta\\ \delta(|e|-\tfrac{1}{2}\delta) & |e|>\delta\end{cases}\]

The derivative is \(e\) inside the interval and \(\delta\operatorname{sign}(e)\) outside. Thus Huber caps the output derivative at magnitude \(\delta\); its loss still grows for large errors. A target measured in cents needs a correspondingly different threshold from one measured in dollars. In PyTorch, Smooth L1 with \(\beta=\delta>0\) is Huber divided by \(\delta\); the losses coincide when both thresholds are 1.

import numpy as np

def huber_grad(e, delta=1.0):
    return np.where(np.abs(e) <= delta, e, delta * np.sign(e))

e = np.array([-5.0, -0.5, 0.5, 5.0])
print("MSE", 2 * e)
print("MAE", np.sign(e))
print("Huber", huber_grad(e))
# MSE [-10.  -1.   1.  10.]
# MAE [-1. -1.  1.  1.]
# Huber [-1.  -0.5  0.5  1. ]

The rows compare output derivatives at the same residuals. Huber limits the contribution from residual size while retaining smaller derivatives near zero. A large derivative of the prediction with respect to a parameter can still produce a large parameter gradient.

Squared error and cross-entropy for classification

For a binary label, let \(a=\sigma(z)\) be the predicted positive-class probability. Squared error gives \(d\mathcal L/dz=2(a-y)a(1-a)\). For a confidently wrong prediction, \(|a-y|\) is large but \(a(1-a)\) is small, reducing this logit derivative. BCE gives \(a-y\). At \(z=-6,y=1\), the derivatives are about โˆ’0.00492 and โˆ’0.99753 respectively. Both encourage a higher score, but their magnitudes differ greatly. The resulting parameter update also depends on the derivative of the score with respect to the parameters.

For a sigmoid applied to an affine score, BCE is convex in the weights and bias, while squared error can be nonconvex. BCE is generally not convex in the parameters of a deep network. Squared error on binary probabilities is also a proper scoring rule, meaning its conditional expected value is minimized by the true class probability; the sigmoid optimization issue does not make it invalid for classification.

For categorical probabilities \(q_c\) and true distribution \(p_c\), expected cross-entropy is \(H(p,q)=-\sum_c p_c\log q_c=H(p)+D_{\rm KL}(p\Vert q)\). Cross-entropy is the total expected coding cost; the KL term is the excess over using \(p\). Natural logarithms give nats, and base-2 logarithms give bits. Unrestricted expected cross-entropy is minimized at \(q=p\); a training loss on finite data does not establish calibrated predictions on new data. Use logits-based library losses to avoid taking logarithms of rounded probabilities.

Class imbalance: weighting and focal loss

A large majority class can dominate the aggregate loss or gradient, but its count alone does not establish that it does. Already confident examples can contribute very little. Compare per-class errors and gradient contributions before choosing a weighting rule.

Class weighting multiplies losses by positive class-specific constants, for example inverse training frequencies or weights chosen to reflect error costs. Equalizing total class weights does not equalize their gradients or guarantee better validation performance. The multiplier is shared within a class, while the underlying loss still depends on each prediction.

Weighting also changes the probability target. If \(p=P(Y=1\mid x)\), the conditional expected weighted loss is \(-\alpha_1p\log q-\alpha_0(1-p)\log(1-q)\), with \(\alpha_1\) and \(\alpha_0\) the positive and negative class weights. It is minimized over \(q\) by \(q^*=\alpha_1p/[\alpha_1p+\alpha_0(1-p)]\). For \(p=0.1,\alpha_1=9,\alpha_0=1\), this gives 0.5. A weighted model’s raw output therefore need not estimate the original conditional probability. Evaluate probability quality and decision thresholds on representative validation data. For simple decision costs, changing a threshold on a suitable probability model is another option.

Focal loss adds a prediction-dependent factor: \(\mathcal L=-\alpha_t(1-p_t)^\gamma\log p_t\), where \(p_t\) is the probability assigned to the true class, \(\alpha_t>0\) is its class weight, and \(\gamma\ge0\) controls downweighting. With \(\gamma=0\), this is weighted cross-entropy. At \(p_t=0.99,\gamma=2\), the loss value is multiplied by \(10^{-4}\). The gradient must also differentiate that multiplier; it is not simply the CE gradient times \(10^{-4}\).

def focal_factor(p_true, gamma=2.0):
    return (1 - p_true) ** gamma

for p in [0.99, 0.90, 0.50, 0.10]:
    print(p, round(focal_factor(p), 4))
# 0.99 0.0001
# 0.9  0.01
# 0.5  0.25
# 0.1  0.81

The factor table describes losses, not gradients. For a positive binary example with \(p=\sigma(z)\) and \(\alpha_t=1\), differentiating both factors gives the logit-gradient magnitude \((1-p)^\gamma[(1-p)-\gamma p\log p]\). Its benefit is task-dependent; emphasizing hard cases can also emphasize mislabeled ones.

Label smoothing

For one example whose logits can vary freely, one-hot cross-entropy approaches zero as the true-class score exceeds the others without bound. Shared parameters, conflicting labels, or regularization may prevent that limit during training. Label smoothing replaces the one-hot vector \(y\) with a soft target. We use the uniform-mixture convention \(q_c=(1-\varepsilon)y_c+\varepsilon/C\), with \(0<\varepsilon<1\). For four classes, \(\varepsilon=0.1\), and class 0 as the target, this gives \([0.925,0.025,0.025,0.025]\).

Soft-target cross-entropy is \(-\sum_c q_c\log a_c\), with logit gradient \(a_c-q_c\). If an example’s logits are unconstrained, the minimum occurs at \(a=q\), giving a true-to-other logit gap of \(\log(0.925/0.025)\approx3.611\) in this example. Another convention assigns \(1-\varepsilon\) to the true class and \(\varepsilon/(C-1)\) to the others; it is not the same target. PyTorch’s cross-entropy uses the uniform-mixture convention.

Smoothing can reduce overconfidence, but improved calibration is an empirical outcome, not a guarantee. In the unrestricted population problem, the uniform-mixture target moves the optimum from \(p_c(x)\) to \((1-\varepsilon)p_c(x)+\varepsilon/C\). Mรผller et al. observed improved calibration and impaired teacher-to-student distillation in their experiments. Validate the smoothing strength for the use you intend.

A selection table

Prediction neededModel outputStarting objective
Conditional mean of a numeric targetscalar, often unrestrictedMSE
Conditional median of a numeric targetscalar, often unrestrictedMAE
Location estimate with limited sensitivity to large residualsscalarHuber; choose a scale-aware threshold
Binary probabilityone logit; sigmoid for probabilityBCE from logits
One label out of \(C\)\(C\) logits; softmax for probabilitiesCategorical CE from logits
Several labels may apply\(C\) logits; a sigmoid per labelSum or mean of per-label BCE terms
Imbalanced classificationbinary or categorical scoresCompare ordinary CE, class weighting, or focal loss against the intended validation metric

The table lists starting points, not mandatory pairings. Per-label BCE targets each labelโ€™s conditional probability; the outputs need not sum to one and do not alone specify their joint dependence. For fused classification losses, pass logits directly and let the loss handle sigmoid or log-softmax internally.

Combining multiple losses

Multi-task models often minimize \(J=\sum_k\lambda_k J_k\), where \(J_k\) is one task’s loss and the nonnegative \(\lambda_k\) are tuning parameters. Units and reductions affect their relative sizes: changing a coordinate target from meters to centimeters multiplies its squared errors by 10,000 for correspondingly rescaled predictions. Log each component and its validation metric separately. One term can increase while the weighted total decreases; whether that tradeoff is acceptable depends on the task requirements.

Equal loss values do not imply equal effects on training: the shared-parameter gradient is \(\nabla_\theta J=\sum_k\lambda_k\nabla_\theta J_k\). For \(J_1=100+\theta^2\) and \(J_2=(1+\theta^2)/2\) at \(\theta=1\), the values are 101 and 1 but the derivatives are 2 and 1. The constant 100 affects no update. Inspect reductions, gradient magnitudes, and opposing gradient directions alongside validation performance when tuning weights. Matching initial loss magnitudes alone can mislead.

Training and validation curves, along with regularization choices, are discussed in Diagnosing and Preventing Overfitting in Deep Learning.

The loss is not the metric

Gradient-based training needs usable derivatives or subgradients; MAE already shows that differentiability everywhere is unnecessary. Thresholded accuracy and F1 do not provide useful gradients for most parameter changes. Cross-entropy gives a tractable training objective, while the deployment metric evaluates a different property. They can improve or worsen independently.

Track the loss and the metric selected for deployment. A rise in validation cross-entropy alongside accuracy means the average log score worsened while more labels were correct at the chosen decision rule. It does not identify calibration as the cause. Select the stopping criterion in advance: accuracy may be appropriate when mistakes have equal costs, while asymmetric costs, recall constraints, or probability quality call for other criteria. Use validation data for this choice and keep the test set for final evaluation.

The connection between likelihood models and losses is developed in Probability and Information Theory for Deep Learning.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.