Loss functions and output layers
Pair output distributions with losses, implement stable logit-based calculations, and study label smoothing and heteroscedastic regression.
After this lesson you can
- Derive MSE, L1 and binary, categorical and multilabel cross-entropies as negative log-likelihoods.
- Implement stable log-softmax and BCE with logits using log-sum-exp and explain failure of naive versions.
- Compare MSE on sigmoid with cross-entropy gradients and explain saturation of the former.
- Apply label smoothing and calculate its effects on minimum loss and optimal logits.
- Train heteroscedastic regression with Gaussian NLL and diagnose its instability.
Before you start
Output and loss form a pair
A network can produce a very negative number for a positive example and still receive an almost zero correction signal, depending on how output and loss are combined. The choice determines which distribution is fitted and how gradients reach the parameters.
A logit is an unnormalized real score. In binary classification sigmoid converts it to probability; for mutually exclusive classes softmax converts a logit vector to a distribution. It is not itself a probability. The output-loss pair often comes from negative log-likelihood, although useful losses also exist that do not arise from the chosen distribution.
From a distribution to a loss
For conditionally independent observations, maximum likelihood is equivalent to minimizing the sum of negative log-likelihoods. Common pairings, with , are:
| Conditional model | Predicted parameters | NLL per observation, up to fixed constants |
|---|---|---|
| Fixed-variance Gaussian | mean | |
| Fixed-scale Laplace | location | $ |
| Bernoulli | logit , probability | binary cross-entropy |
| Categorical | logits , softmax probabilities | |
| Multiple binary labels | one logit per label | sum or mean of per-label BCE |
For the Gaussian, ; for Laplace, . With fixed scale, minimizing the sum is equivalent respectively to minimizing MSE or L1. The positive factor does change gradient scale and effective learning rate. MSE and L1 also have interpretations as estimators of conditional mean and median under suitable assumptions: see elicited functionals.
Huber loss is quadratic near zero and linear in the tail. For fixed threshold , defines a normalizable density and its NLL is Huber plus a normalization constant. If scale is changed or learned, that constant can depend on it and cannot simply be discarded. Robustness does not mean a model is automatically calibrated.
Exclusive or simultaneous
In binary classification, and ; Bernoulli NLL is . In exclusive multiclass classification, selects one class among and . In multilabel classification, each can be active simultaneously and BCE is applied to each logit. A product of Bernoullis specifies conditional independence as a joint model; the BCE sum can also be interpreted as fitting marginal probabilities without claiming real labels are independent.
Softmax couples classes through a shared denominator: increasing one logit with the others fixed reduces the other probabilities. Two classes cannot simultaneously exceed , though both can have moderate probability. Independent sigmoids need not sum to one. An image with multiple objects therefore requires an explicit decision about the problem, not merely changing output count.
Compute from logits
With , the log-sum-exp trick gives
For finite logits, all shifted exponentials are at most one and at least one equals one. In the binary case, a stable form for is
It equals , but avoids exponentiating a large positive number. Differentiating the equivalent smooth expression gives . A batch mean divides that gradient by batch size; summing or averaging changes its scale.
If you use , then . For and , the BCE gradient approaches while the MSE gradient approaches zero. BCE gives a better signal in that particular case; it does not mean every BCE network avoids vanishing in earlier layers.
In PyTorch, CrossEntropyLoss takes logits without softmax and BCEWithLogitsLoss takes logits without a prior sigmoid. Both combine operations for stability; applying activation beforehand changes the function. Also ensure reduction, weights and label encoding match when comparing implementations.
Smoothed labels
With classes and the PyTorch convention, label smoothing replaces the one-hot label by
By the cross-entropy identity, . KL is nonnegative and vanishes if . For , all components of are positive and a per-example optimum has , with arbitrary . For , the loss infimum is zero, but softmax with finite logits does not produce an exact one-hot distribution. For , all classes have the same optimal logit up to a common constant.
For , the difference between correct and incorrect logits is . It is finite for the free optimum of one example, not an absolute bound on logits or a guarantee that a shared network reaches all such optima simultaneously. Müller and colleagues studied its effects on calibration and distillation; improved calibration is not guaranteed for every distribution.
Predicted mean and variance
For a heteroscedastic Gaussian, the network predicts and . The heteroscedastic NLL, up to constant , is
Predicting makes mathematical variance positive; in floating point, extreme values can still overflow or underflow. If residual is zero, takes this NLL to : a flexible fit can collapse variance. Bounding , using a variance floor or regularizing are modeling decisions that should be disclosed. If noise truly varies, inverse-variance residual weighting may be appropriate; trouble arises when predicted variance reduces the mean signal in an important region the model still fits poorly.
Seitzer and colleagues propose β-NLL as a gradient modification: multiply each NLL by . The weight is treated as constant during differentiation. For example,
With , the mean contribution is that of ; the variance path remains active and can also update a shared trunk. This is not the ordinary product derivative without stopgrad, nor a new standard Gaussian NLL. Evaluate models with comparable metrics, such as RMSE and ordinary Gaussian NLL on held-out data; β-NLL values with different are not directly comparable as log-likelihoods.
One head per task
A network with a shared trunk can have one head per task and sum their losses. Multitask loss balancing matters because a sum combines different units, scales and reductions: a task with more components or larger loss can dominate the shared gradient. Normalizing targets and fixing weights, measuring each task’s metrics separately and tuning weights on validation are explicit choices.
For scalar regression with equal to mean squared residual and learned homoscedastic variance, its NLL is plus constants. If and it is considered fixed, the stationary point satisfies . Term prevents sending weight to zero without cost, but if the NLL can tend to . Kendall, Gal and Cipolla study uncertainty weighting; their classification treatment uses an approximation and should not be interpreted as a universal exact equality. The factor changes with dimension and loss reduction.
Lab: stable losses
The following functions return mean losses and gradients with respect to logits or outputs. Labels for cross_entropy are integer indices. For BCE the mean is over all elements and labels can be soft between zero and one.
import numpy as np
from scipy.special import expit, logsumexp
def log_softmax(z):
z = np.asarray(z, dtype=float)
shifted = z - z.max(axis=-1, keepdims=True)
return shifted - np.log(np.exp(shifted).sum(axis=-1, keepdims=True))
def cross_entropy(z, y):
lp = log_softmax(z)
grad = np.exp(lp)
grad[np.arange(len(y)), y] -= 1
return -lp[np.arange(len(y)), y].mean(), grad / len(y)
def bce_with_logits(z, y):
z, y = np.asarray(z, dtype=float), np.asarray(y, dtype=float)
loss = np.maximum(z, 0) - z*y + np.log1p(np.exp(-np.abs(z)))
return loss.mean(), (expit(z)-y)/z.size
def gaussian_nll(mu, s, y):
residual = mu-y
loss = 0.5*(s + np.exp(-s)*residual**2)
return loss.mean(), np.exp(-s)*residual/mu.size, 0.5*(1-np.exp(-s)*residual**2)/mu.size
Z = np.array([[1000., 999., -1000.], [-1000., 0., 1000.]])
lp = log_softmax(Z)
print('error log-softmax frente a scipy', np.max(np.abs(lp - (Z-logsumexp(Z, axis=1, keepdims=True)))))
print('BCE estable y gradiente', bce_with_logits(np.array([-1000., 1000.]), np.array([1., 0.])))
with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
naive = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)
z_bad = np.array([-1000., 1000.])
p_bad = expit(z_bad)
naive_bce = -np.mean(np.array([1., 0.])*np.log(p_bad) + np.array([0., 1.])*np.log1p(-p_bad))
print('softmax ingenua finita', bool(np.isfinite(naive).all()))
print('BCE ingenua finita', bool(np.isfinite(naive_bce)))z = np.array([[0.2, -0.7, 1.1], [-0.1, 0.5, 0.9]])
y = np.array([2, 1])
loss, grad = cross_entropy(z, y)
eps = 1e-5
zp, zm = z.copy(), z.copy()
zp[0, 1] += eps; zm[0, 1] -= eps
fd = (cross_entropy(zp, y)[0] - cross_entropy(zm, y)[0])/(2*eps)
print('CE: analítica y numérica', grad[0, 1], fd)
zb, yb = np.array([-1.2, 0.7]), np.array([0.3, 1.])
_, gb = bce_with_logits(zb, yb)
zp, zm = zb.copy(), zb.copy()
zp[0] += eps; zm[0] -= eps
print('BCE: analítica y numérica', gb[0], (bce_with_logits(zp, yb)[0]-bce_with_logits(zm, yb)[0])/(2*eps))
mu, s, yg = np.array([0.3, -0.5]), np.array([-0.4, 0.8]), np.array([0.9, 0.2])
loss, gm, gs = gaussian_nll(mu, s, yg)
mup, mum = mu.copy(), mu.copy()
mup[0] += eps; mum[0] -= eps
sp, sm = s.copy(), s.copy()
sp[0] += eps; sm[0] -= eps
print('NLL gaussiana y gradientes analítico/numérico', loss, gm[0],
(gaussian_nll(mup, s, yg)[0]-gaussian_nll(mum, s, yg)[0])/(2*eps), gs[0],
(gaussian_nll(mu, sp, yg)[0]-gaussian_nll(mu, sm, yg)[0])/(2*eps))
beta_weight = np.exp(0.5*s)
def frozen_beta_objective(m, logvar):
return np.mean(beta_weight * 0.5*(logvar + np.exp(-logvar)*(m-yg)**2))
beta_gm = beta_weight*np.exp(-s)*(mu-yg)/len(mu)
beta_gs = beta_weight*0.5*(1-np.exp(-s)*(mu-yg)**2)/len(mu)
print('beta: gradientes analítico/numérico', beta_gm[0],
(frozen_beta_objective(mup, s)-frozen_beta_objective(mum, s))/(2*eps), beta_gs[0],
(frozen_beta_objective(mu, sp)-frozen_beta_objective(mu, sm))/(2*eps))
q = np.full(10, 0.1/10); q[0] += 0.9
print('smoothing: q correcta, otra, entropía, diferencia de logits', q[0], q[1], -np.sum(q*np.log(q)), np.log(q[0]/q[1]))Lab: heteroscedastic regression
Generate training and test data using different seeds from a known model. Mean is approximated with polynomial features and with a second head; both are fitted by full-batch gradient descent. Predicted variances are explicitly bounded using clip: outside the interval, the clipping operation’s gradient is zero. For β-NLL, the weighting factor is frozen at each step. The MSE fit learns only the mean and produces no variance band. These experiments are small and reproducible; one run’s difference does not prove a method universally better.
def make_data(seed, n):
rng = np.random.default_rng(seed)
x = rng.uniform(-1, 1, n)
mu = np.sin(2*x)
sigma = 0.12 + 0.45*(x+1)/2
return x, mu + sigma*rng.normal(size=n)
def features(x):
return np.column_stack((np.ones_like(x), x, x*x, x*x*x))
def variance_features(x):
return np.column_stack((np.ones_like(x), x, x*x))
xtr, ytr = make_data(12, 240)
xte, yte = make_data(13, 240)
Xtr, Str = features(xtr), variance_features(xtr)
Xte, Ste = features(xte), variance_features(xte)def fit_two_heads(X, S, y, method, steps=1200, lr=0.03, beta=0.5):
w = np.zeros(X.shape[1])
v = np.zeros(S.shape[1])
for _ in range(steps):
mu = X @ w
raw = S @ v
s = np.clip(raw, -5., 3.)
residual = mu-y
if method == 'mse':
gw = X.T @ residual / len(y)
gv = np.zeros_like(v)
else:
weight = np.exp(beta*s) if method == 'beta' else np.ones_like(s)
gm = weight*np.exp(-s)*residual
gs = weight*0.5*(1-np.exp(-s)*residual**2)
gs = gs*((raw > -5.) & (raw < 3.))
gw, gv = X.T @ gm / len(y), S.T @ gs / len(y)
w -= lr*gw
v -= lr*gv
return w, v
models = {method: fit_two_heads(Xtr, Str, ytr, method) for method in ('mse', 'nll', 'beta')}
for method, (w, v) in models.items():
pred = Xte @ w
rmse = np.sqrt(np.mean((pred-yte)**2))
left, right = xte < 0, xte >= 0
rmse_mean = [np.sqrt(np.mean((pred[mask]-np.sin(2*xte[mask]))**2)) for mask in (left, right)]
if method == 'mse':
print(method, 'RMSE prueba', round(rmse, 5), 'sin varianza predicha')
else:
s = np.clip(Ste @ v, -5, 3)
nll = np.mean(0.5*(np.log(2*np.pi)+s+(pred-yte)**2*np.exp(-s)))
print(method, 'RMSE y NLL prueba', round(rmse, 5), round(nll, 5))
print(method, 'RMSE frente a media verdadera izquierda/derecha', np.round(rmse_mean, 5))import matplotlib.pyplot as plt
xx = np.linspace(-1, 1, 160)
fig, axes = plt.subplots(1, 3, figsize=(11, 3), sharey=True)
for ax, method in zip(axes, ('mse', 'nll', 'beta')):
w, v = models[method]
mean = features(xx) @ w
ax.scatter(xtr, ytr, s=5, alpha=0.25)
ax.plot(xx, np.sin(2*xx), '--', label='media verdadera')
ax.plot(xx, mean, label='media ajustada')
if method != 'mse':
std = np.exp(0.5*np.clip(variance_features(xx) @ v, -5, 3))
ax.fill_between(xx, mean-2*std, mean+2*std, alpha=0.2, label='media ± 2σ')
ax.set_title(method)
axes[0].legend(fontsize=7)
plt.tight_layout()
plt.show()A band is a band of the predicted distribution, not a confidence interval for parameters. Check whether residuals and coverage on new data agree with the model; good NLL does not guarantee calibration in every subregion. Clipping and the number of steps affect the fit.
import torch
import torch.nn.functional as F
z = torch.tensor([[2., 1., 0.]], dtype=torch.float64)
target = torch.tensor([0])
print('CrossEntropyLoss desde logits', F.cross_entropy(z, target).item())
print('BCEWithLogitsLoss', F.binary_cross_entropy_with_logits(torch.tensor([-2., 2.]), torch.tensor([1., 0.])).item())
print('HuberLoss', F.huber_loss(torch.tensor([2.]), torch.tensor([0.]), delta=1.).item())
print('GaussianNLLLoss', F.gaussian_nll_loss(torch.tensor([1.]), torch.tensor([0.]), torch.tensor([2.]), full=True).item())npm run lab and open the connection link.Exercises
Step 1 of 3. What remains of Gaussian NLL after removing constants?
Step 1 of 2. What is the derivative of the first term?
bce_with_logits(z, y) returning mean loss and the gradient of that mean with respect to each element of z. Labels can be soft and logits reach ±1000.import numpy as np
def bce_with_logits(z, y):
passThe chosen distribution determines an NLL and an output transformation. Computing from logits avoids instability; smoothing labels changes the optimum; predicting variance changes residual weighting and requires diagnosing both mean and uncertainty. In multitask learning, head scales and reductions are also part of the model.