AI Wiki中文/EN

Neural network loss functions

神经网络损失函数

Connect outputs, labels, and gradients; implement stable binary cross-entropy and masking; and see how reductions change the objective.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two correct classifications can give different training signals

For a binary example with label 1, predictions 0.6 and 0.9 both classify correctly at threshold 0.5. Their negative log losses differ: approximately 0.5108 and 0.1054. A training objective can distinguish predictions that an accuracy count treats as identical.

A loss joins three choices: what the output represents, what a label means, and which errors are costly. Backpropagation differentiates that choice; it cannot repair a mismatch between the chosen loss and the intended task. Changing the loss can change the fitted answer even with the same data and network architecture.

From one prediction to a training objective

A pointwise loss ℓ(y,y^)\ell(y,\hat y) scores one prediction. Averaging those scores produces an empirical objective, often with a separate parameter penalty Ω(θ)\Omega(\theta):

L(θ)=1n∑i=1nℓ(yi,fθ(xi))+λΩ(θ).L(\theta)=\frac1n\sum_{i=1}^{n}\ell(y_i,f_\theta(x_i))+\lambda\Omega(\theta).

Labels and output shape determine what losses make sense. A continuous output can use squared error. A mutually exclusive class output can use categorical negative log probability. Several simultaneously valid labels can use separate binary terms. Applying squared error to arbitrary integer class IDs introduces artificial distances between categories. MML, Section 8.2.2

For a binary label y∈{0,1}y\in\{0,1\} and probability 0<p<10<p<1, the Bernoulli likelihood is py(1−p)1−yp^y(1-p)^{1-y}. Taking its negative logarithm gives:

ℓ(y,p)=−yln⁡p−(1−y)ln⁡(1−p).\ell(y,p)=-y\ln p-(1-y)\ln(1-p).

Networks often output an unconstrained logit zz and convert it with sigmoid p=σ(z)=1/(1+e−z)p=\sigma(z)=1/(1+e^{-z}). Algebraically combining sigmoid and log loss gives a stable expression:

ℓ(y,z)=max⁡(z,0)−yz+ln⁡(1+e−∣z∣),∂ℓ∂z=σ(z)−y.\ell(y,z)=\max(z,0)-yz+\ln(1+e^{-|z|}),\qquad \frac{\partial\ell}{\partial z}=\sigma(z)-y.

Combining the operations avoids first rounding a probability to 0 or 1 and then taking the logarithm of zero. The derivative follows by differentiating the composite expression; its magnitude depends on both the probability and target. For a one-hot categorical label—1 at the correct class and 0 elsewhere—the analogous cross-entropy is −ln⁡pc-\ln p_c for the correct class cc. D2L, Section 4.1.2

Padding positions in a sequence should contribute according to the task’s mask. A mean over valid positions is:

Lvalid=∑imiℓi∑imi,mi∈{0,1},∑imi>0.L_{\mathrm{valid}}=\frac{\sum_i m_i\ell_i}{\sum_i m_i},\qquad m_i\in\{0,1\},\qquad \sum_i m_i>0.

Dividing by the full padded length instead changes the weight of shorter sequences. Token averaging and sequence averaging also weight examples differently. State the intended unit before choosing a reduction.

Stable logits and an explicit denominator

This complete Python program evaluates binary loss, its derivative, and a masked mean. It is a loss component, not a trained classifier. Extreme logits test numerical behavior; moderate logits permit a finite-difference derivative check.

import math

def bce(z, y):
    if not math.isfinite(z) or y not in [0,1]:
        raise ValueError("finite logit and binary target required")
    return max(z,0)-y*z+math.log1p(math.exp(-abs(z)))

def sigmoid(z):
    if z >= 0:
        return 1/(1+math.exp(-z))
    ez = math.exp(z)
    return ez/(1+ez)

def masked_mean(logits, targets, mask):
    if not (len(logits)==len(targets)==len(mask)):
        raise ValueError("shape mismatch")
    if any(type(m) is not bool for m in mask) or not any(mask):
        raise ValueError("boolean mask with a valid position required")
    return sum(bce(z,y) for z,y,m in zip(logits,targets,mask) if m)/sum(mask)

assert math.isclose(bce(0,1), math.log(2))
assert bce(1000,1) == 0 and bce(-1000,1) == 1000
assert bce(-1000,0) == 0 and bce(1000,0) == 1000
z,y,h = .7,1,1e-5
assert abs((bce(z+h,y)-bce(z-h,y))/(2*h)-(sigmoid(z)-y)) < 1e-8
assert math.isclose(masked_mean([0,1000,0],[1,0,0],[True,False,True]), math.log(2))
assert masked_mean([0,1000,0],[1,0,0],[True,True,True]) > 300
try:
    masked_mean([0],[1],[False])
except ValueError:
    pass
else:
    raise AssertionError("all-masked mean must be rejected")

For nn positions, the loss reduction requires O(n)O(n) work and constant additional storage. This excludes computing the network outputs and their gradients, which typically dominate training cost.

The same formula can optimize a different task

Summing losses instead of averaging multiplies the data gradient by the batch size. For a fixed dataset and no other terms, positive constant scaling preserves exact minimizers, but it changes update magnitudes at a fixed learning rate. With a fixed regularization coefficient, changing only the data reduction also changes the balance between fit and penalty. The familiar half factor in squared error is another convention that changes derivatives’ scale. D2L, Section 3.1.1.2

Class weighting can make some mistakes more expensive, but it changes the optimized expectation. Probabilities trained with weighting may need a different interpretation or calibration for the original population. A low weighted loss should be reported with its weights and evaluation conditions.

Confident wrong predictions incur large log loss, including when a label is itself wrong. Label errors, masking bugs, incorrect target encoding, and averaging mistakes can therefore dominate the gradient. An all-masked batch requires an explicit policy; this example raises an error instead of returning an undefined mean.

Trace the numerical consequence

  1. For z=0,y=1z=0,y=1, what are the loss and logit derivative? Answer: ln⁡2\ln2 and −1/2-1/2.
  2. Should a padded token with a large loss affect this masked mean? Answer: no, if its mask is zero and the task excludes padding.
  3. Does unchanged accuracy imply unchanged cross-entropy? Answer: no; 0.6 and 0.9 on a positive label are the opening counterexample.
  4. Is clipping probabilities before a logarithm mathematically identical to evaluating the original logit loss? Answer: no. Clipping changes the objective and can change gradients; a stable combined operation avoids that replacement.

Match optimization signals to evaluation

Surrogate losses supply useful gradients for objectives whose direct metrics may be discrete or difficult to optimize. Ranking, contrastive learning, robust prediction, and structured outputs require additional choices about pairs, negatives, margins, and reductions. For each new loss, identify the output domain, target encoding, optimized expectation, gradient behavior, and final metric before comparing results.

Make a prediction, then check

When averaging loss over valid tokens, what is the correct denominator?

Choose one answer

Learning objectives

  • Choose a loss for the output and target encoding, and derive the binary logit-loss gradient.
  • Implement stable cross-entropy and a masked mean; explain sums, means, and regularization weights.

Prerequisites & connections

Explore related knowledge →

References

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. Dive into Deep Learning — Softmax Regression
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023
  3. Dive into Deep Learning — Linear Regression
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Re-derived binary logit loss and sigmoid(z)−y from likelihood; checked logits ±1000 and ten additional finite-difference gradients.
  • Ran padding masks, mean invariance under batch duplication, and all-masked rejection; checked one-hot meaning, denominators, sums versus means, and relative regularization weights.
  • Compared arguments, modeling assumptions, numbers, and exercise answers across languages; structural checks separately compare display formulas, code, references, and main sections. No independent human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.