Out-of-distribution detection
Move from batch shift detection to deciding whether each input is recognized. Derive logit-based and feature-space scores, study outlier exposure and generative likelihood, and establish separate evaluation on near and far OOD examples.
After this lesson you can
- Distinguish semantic from covariate shift and formulate OOD detection per example.
- Derive the energy score from an energy-model interpretation of a classifier and compare it with MSP.
- Implement shared-covariance Mahalanobis, kNN on normalized features, and ReAct.
- Train with outlier exposure and measure its effect on unseen OOD data.
- Evaluate AUROC, AUPR, and FPR at 95% TPR on near and far OOD without contaminating hyperparameter selection.
Before you start
A decision for every input
A skin-lesion classifier receives a photograph of a cat. Its softmax must sum to one across lesion classes even though none describes the image. A malware detector may encounter a family absent from its training labels. It is not enough to know that a batch distribution changed, as in the previous lesson: now we want a score for each case and a decision to refer, reject, or review it.
Out-of-distribution detection (OOD) compares in-distribution (ID) examples with examples from a specified alternative. Semantic shift means a class or content appears outside the intended categories; covariate shift can preserve semantics, for example different lighting. Both categories depend on use: a cat is OOD for a lesion system, but a lesion photographed with another camera may remain valid. Open-set recognition additionally decides the known class when an input is accepted. The score does not prove safety or itself define a valid input.
What the logit vector says
For logits , . Maximum softmax probability (MSP) is . It is relative confidence among known classes, not the probability that the image belongs to them. Adding the same constant to all logits preserves softmax; maximum logit and energy change. The baseline by Hendrycks and Gimpel evaluates this score as a detector without turning it into a calibration guarantee.
Energy at temperature is . We use as an ID compatibility score: higher means more compatible. For ,
If the input space has a measure and is finite, we can define ; then . This interpretation is a mathematical construction, not proof that a discriminative classifier learned the true density. Indeed, adding an arbitrary common function to every logit preserves and changes that implicit density. Liu and colleagues study energy-based detection; score direction and assumptions matter when comparing results.
Consider two inputs with logits and . Both have MSP : relative classification sees the same uniform distribution. Their scores are and , respectively. If larger is treated as ID evidence, the second appears more compatible even though conditional probabilities do not change. That difference does not identify which input actually comes from the training distribution. Measure score behavior on held-out alternatives and an ID set.
ODIN combines temperature and a small perturbation that increases predicted-class confidence, calculated using the gradient with respect to the input. Perturbation size is measured on the correct pixel scale and chosen on validation, not the final OOD set. Liang and colleagues document the procedure; the best size for one domain need not transfer to another. Do not confuse this diagnostic perturbation with a robustness guarantee.
More concretely, if and is the softmax of , define and calculate . Then score using . The sign reduces loss for the class chosen by the model itself; it does not use the true label. If training normalizes channels, must be converted to those units and clipping done in the valid pixel domain. Comparing implementations with different conventions can change the conclusion.
Feature geometry
Feature-space detection compares with ID examples. If classes are modeled as Gaussians with means and shared covariance , an ID score is . Inversion needs regularization when covariance is singular or ill-conditioned. The Gaussian assumption approximates the specific representation; it is not a universal network property. Lee and colleagues build detectors from this family on activations.
The formula follows from the conditional Gaussian log density: with shared covariance, is a shared constant minus half the squared distance. Maximizing over classes chooses the nearest mean in that geometry. With unequal class priors, maximizing joint density adds ; omitting it is a different choice. In high dimensions, estimating a full matrix requires many examples and its inverse can amplify poorly measured directions. Regularization improves stability but changes geometry and must be documented.
The kNN alternative normalizes features, finds the -th ID neighbor, and uses negative distance as score. It captures local shapes without imposing a Gaussian, at the cost of memory, search, and sensitivity to dimension and (Sun and colleagues). Scale matters: neither normalization nor shared covariance automatically repairs a collapsed or poorly chosen representation.
Normalization turns Euclidean distance into direction comparison for nonzero vectors, because . A nearly zero norm needs a stable convention and can carry useful information discarded by normalization. In a neighbor bank, exclude the example itself when evaluating training data: otherwise the nearest neighbor has zero distance by construction. The figure is a two-dimensional unnormalized example to reveal shape; the numerical lab normalizes before kNN and Mahalanobis.
Bank size and query rule are part of the detector. Adding many reference examples tends to reduce nearest-neighbor distance even without distribution change, so a threshold calibrated for an old bank may no longer mean the same thing. If classes have very different counts, a dense cloud may dominate neighborhoods. Distant but legitimate points may also belong to an underrepresented class. Compare rejection rates by class or segment, freeze the bank before test, and record whether its elements can contain sensitive data.
ReAct clips high activations in a layer, , before recalculating the score. Threshold is fixed using ID training or validation activations, not final OOD evaluation. It is an intervention on the representation, not a new distance. Sun, Guo, and Li analyze its effect; it may help or hurt depending on the model and alternative.
Training with auxiliary examples
In outlier exposure (OE), a loss is added on an auxiliary set distinct from ID. One classification option penalizes the difference between softmax and the uniform distribution on those examples: . Total loss combines this penalty with ID cross-entropy and a weight selected on validation. Hendrycks and colleagues investigate generalization to unseen anomalies. If the auxiliary set contains legitimate cases or resembles the final test, the detector may reject useful inputs or appear to generalize better than it does; reserve families and data unused for training and tuning.
A generative model does not automatically solve the problem either: high likelihood can reflect background statistics rather than semantics. Ren and colleagues propose likelihood ratios to reduce background contributions; the ratio depends on the background model and does not guarantee universal identification. This is the OOD likelihood paradox in operational terms.
Metrics and protocol
OOD metrics require stating the positive class. Here ID is positive and a high score favors ID. AUROC is the probability of ranking an ID above an OOD example, with half credit for ties. AUPR depends on prevalence and which class is positive: report both. FPR95 is the accepted OOD fraction at 95% ID TPR. With a finite sample, the threshold may jump over 95%; interpolating between points is equivalent to randomizing the criterion within the tied group. A deterministic threshold guaranteeing at least 95% may have a different FPR.
In deployment with ID prevalence , precision of acceptance is . Thus the same TPR/FPR pair can yield different precision as case mix changes. AUROC averages pairwise rankings across the two populations and does not depend on mix proportion if conditional distributions remain fixed; precision-recall does. Low FPR95 on easy OOD alone says nothing about cost in a population of near cases.
An operating threshold is fixed on calibration data, for example to retain a desired ID fraction, then evaluated unchanged on another set. FPR95 from a curve built directly on test compares rankings but does not replace validation of a deployable threshold. Precision of an observed rate depends on sample count: with few accepted OOD examples, one image can change the percentage substantially. If several images come from one patient or device, resampling and splits must respect that dependence.
Freeze layer, , temperature, ODIN intensity, and ReAct threshold using independent validation. Report near and far OOD separately and do not select hyperparameters on the set used for publication. Also evaluate ID accuracy, calibration, and seed sensitivity. In production, the threshold must reflect prevalence, rejection costs, and real alternatives; high AUROC alone does not determine a useful threshold.
Lab: MLP logits and features
Use digits 0 to 4 as ID and hold out 5 to 9 as semantic OOD. The second OOD consists of deterministic stripes, an artificial distant alternative. Train a one-hidden-layer MLP with NumPy. These are 8-by-8 digits, not clinical validation or a CIFAR reproduction. Cells divide training into four browser-sized batches.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X,y=load_digits(return_X_y=True);X=X/16
idx=np.flatnonzero(y<5);ood=np.flatnonzero(y>=5)
tr,te=train_test_split(idx,test_size=.35,stratify=y[idx],random_state=1)
rng=np.random.default_rng(7); W=rng.normal(0,.12,(64,24));b=np.zeros(24);V=rng.normal(0,.12,(24,5));c=np.zeros(5)
def train_steps(steps=20):
global W,b,V,c
for epoch in range(steps):
for ids in np.array_split(rng.permutation(tr),8):
z=X[ids]@W+b;h=np.maximum(z,0);logits=h@V+c
e=np.exp(logits-logits.max(1,keepdims=True));p=e/e.sum(1,keepdims=True)
p[np.arange(len(ids)),y[ids]]-=1;p/=len(ids)
dv=h.T@p;dc=p.sum(0);dh=([email protected])*(z>0)
W-=.3*(X[ids].T@dh);b-=.3*dh.sum(0);V-=.3*dv;c-=.3*dc
def features(x): return np.maximum(x@W+b,0)
def logsumexp(x):
m=x.max(1,keepdims=True);return (m+np.log(np.exp(x-m).sum(1,keepdims=True))).ravel()
def scores(h):
logits=h@V+c;lse=logsumexp(logits)
return np.exp(logits.max(1)-lse), logits.max(1), lsetrain_steps()train_steps()train_steps()train_steps()
print('exactitud ID:',np.mean(np.argmax(features(X[te])@V+c,axis=1)==y[te]))The space is normalized before Mahalanobis and kNN, with zero norm protected. Mean and covariance fitting uses only ID training data. The ReAct percentile is also obtained there. Hyperparameters are fixed teaching choices, not optimizations on the two evaluated OOD sets.
H=features(X[tr]);Hunit=H/np.maximum(np.linalg.norm(H,axis=1,keepdims=True),1e-12)
means=np.array([Hunit[y[tr]==k].mean(0) for k in range(5)])
resid=Hunit-means[y[tr]];cov=resid.T@resid/len(H)+.002*np.eye(H.shape[1]); inv=np.linalg.inv(cov)
cutoff=np.quantile(H,.9)
def all_scores(x):
h=features(x);msp,maxlog,energy=scores(h)
unit=h/np.maximum(np.linalg.norm(h,axis=1,keepdims=True),1e-12)
dif=unit[:,None,:]-means[None,:,:]
md=np.einsum('nki,ij,nkj->nk',dif,inv,dif).min(1)
dist=((unit[:,None,:]-Hunit[None,:,:])**2).sum(2)
knn=np.partition(dist,4,axis=1)[:,4]
react=scores(np.minimum(h,cutoff))[2]
return np.column_stack((msp,maxlog,energy,-md,-knn,react))Now calculate the ROC by grouping ties before accumulation. AUROC uses trapezoidal integration; average precision integrates stepwise precision over recall increments. FPR95 interpolation may use a fraction of a tied group, representing a randomized decision.
def metricas(inside,outside):
labels=np.r_[np.ones(len(inside)),np.zeros(len(outside))]
s=np.r_[inside,outside];order=np.argsort(-s,kind='stable'); s=s[order];labels=labels[order]
ends=np.r_[np.flatnonzero(s[:-1]!=s[1:]),len(s)-1]
tp=np.r_[0,np.cumsum(labels)[ends]];fp=np.r_[0,np.cumsum(1-labels)[ends]]
tpr=tp/len(inside);fpr=fp/len(outside)
auroc=np.sum(np.diff(fpr)*(tpr[:-1]+tpr[1:])/2)
precision=tp[1:]/(tp[1:]+fp[1:]);ap=np.sum(np.diff(tpr)*precision)
j=int(np.searchsorted(tpr,.95,side='left'))
f95=fpr[j] if j==0 or tpr[j]==.95 else fpr[j-1]+(.95-tpr[j-1])/(tpr[j]-tpr[j-1])*(fpr[j]-fpr[j-1])
return auroc,ap,f95
ins=all_scores(X[te]); digits=all_scores(X[ood][:200])
print('dígitos 5-9: AUROC, AUPR-ID, FPR95')
for i,name in enumerate(['MSP','máximo','menos energía','Mahalanobis','kNN','ReAct']):
print(name, np.round(metricas(ins[:,i],digits[:,i]),3))t=np.arange(8)
noise=np.array([np.tile((np.sin(t*.7+phase)>0), (8,1)).ravel() for phase in np.linspace(0,6,200)])
stripes=all_scores(noise)
print('bandas: AUROC, AUPR-ID, FPR95')
for i,name in enumerate(['MSP','máximo','menos energía','Mahalanobis','kNN','ReAct']):
print(name, np.round(metricas(ins[:,i],stripes[:,i]),3))With one split the comparison can change with seed or class selection. Average precision uses the experiment’s specific ID/OOD ratio; it does not directly transfer to different prevalence. The relative ease of stripes versus held-out digits depends on the score and does not generally define near OOD.
Local lab: a vision benchmark
Download ood_benchmark.py. It requires PyTorch, torchvision, NumPy, scikit-learn, and CUDA; it downloads CIFAR-10, CIFAR-100, SVHN, and DTD to ood_data. Output is saved in ood_runs. The experiment trains a ResNet-18 adapted to 32 by 32 for 15 full epochs and repeats three seeds with and without auxiliary exposure to DTD training data. DTD test uses images distinct from training; SVHN and CIFAR-100 are not auxiliaries. CIFAR-100 is semantically near OOD to CIFAR-10, whereas SVHN and DTD explore other shifts without claiming to represent every domain.
Before testing, fix temperature 1000 and ODIN perturbation 0.001 on pixels in , five neighbors, a 5000-example ID bank, and the 90th percentile for ReAct. The script reports AUROC, AUPR-ID, and FPR95 for each score, ID accuracy, and mean and deviation across seeds. Fixed selection avoids test tuning but does not claim these values are optimal. OE uses a penalty toward the uniform distribution with weight 0.5; compare ID utility and unseen OOD before concluding it helped.
The local run completed all six combinations of seeds 11, 23, and 47, with and without OE, for 15 epochs each. The table shows interpolated FPR95: lower is better. Values are mean and sample deviation across three training runs, not confidence intervals.
| OOD test | Score | Without OE | With OE |
|---|---|---|---|
| CIFAR-100 | MSP | 0.739 ± 0.013 | 0.915 ± 0.039 |
| CIFAR-100 | Mahalanobis | 0.625 ± 0.010 | 0.913 ± 0.028 |
| CIFAR-100 | ODIN | 0.633 ± 0.010 | 0.906 ± 0.041 |
| SVHN | MSP | 0.762 ± 0.029 | 0.989 ± 0.012 |
| SVHN | Mahalanobis | 0.218 ± 0.037 | 0.854 ± 0.091 |
| SVHN | ODIN | 0.715 ± 0.028 | 0.986 ± 0.015 |
| DTD | MSP | 0.736 ± 0.024 | 0.818 ± 0.077 |
| DTD | Mahalanobis | 0.345 ± 0.006 | 0.857 ± 0.062 |
| DTD | ODIN | 0.671 ± 0.022 | 0.776 ± 0.086 |
ID accuracy was without OE and with OE. In this specific recipe, OE worsened both ID accuracy and the table’s FPR95 values; the negative result does not prove OE must generally hurt. The auxiliary here is DTD training data and DTD test shares its domain, although not its images. Loss weight, training, and network statistics may matter, but this comparison isolates no cause. Three seeds quantify limited variation and do not cover other auxiliaries, architectures, or settings.
The downloadable summary retains AUROC, AUPR-ID, and FPR95 by seed and regime for all seven scores and three sets. AUPR-ID depends on the evaluation example ratio: DTD has fewer test images than CIFAR-100 or SVHN, so values cannot be compared without considering that prevalence.
Exercises
Step 1 of 3. What is the marginal density of x?
fpr_at_tpr(scores_in, scores_out, target=0.95). High scores favor ID. Build the ROC by grouping ties and linearly interpolate the first segment reaching target, returning minimum FPR when the target coincides with a plateau.import numpy as np
def fpr_at_tpr(scores_in, scores_out, target=0.95):
pass