Uncertainty in deep networks: selective prediction and evaluation under shift
Turn uncertainty into decisions using abstention and confidence rankings. Study ReLU confidence away from data, distance-aware SNGP and DDU methods, and evaluation across shift intensities.
After this lesson you can
- Derive Chow’s rule and construct risk-coverage curves with AURC and E-AURC.
- Prove asymptotic confidence of 1 for a ReLU network along almost every ray and explain feature collapse.
- Implement SNGP with spectral normalization and a random Fourier feature GP head, and DDU.
- Evaluate ensembles, MC dropout, and SNGP using NLL, Brier, ECE, and AURC across corruption intensities.
- Choose a confidence function for calibration, ranking, or detection.
Before you start
Deciding when not to decide
In a triage system, a prediction may trigger an action or be sent for review. Selective classification adds a reject option. Coverage is the accepted fraction; selective risk is the average error among accepted examples. With 0-1 loss and fixed rejection cost , Chow’s rule compares with : predict the most likely class if , reject if it is lower, and either action ties at equality. The rule is optimal for the true probabilities and assumed costs; substituting poorly estimated probabilities does not automatically preserve optimality.
The risk-coverage curve orders examples by a confidence score and evaluates error on increasingly large accepted prefixes. AURC averages risks over discrete coverages . E-AURC subtracts the AURC of an oracle that orders all correct predictions before all errors in the same set; this reduces the influence of the base error rate but does not make different populations directly equivalent. For ties, we average over all possible permutations; points inside a tie require random tie-breaking and do not necessarily correspond to a deterministic threshold.
MSP is maximum probability; entropy measures spread of the predictive distribution, margin compares the two leading classes, and ensemble mutual information measures disagreement among members. Calibration concerns probability values; ranking concerns error ordering. In binary classification, positive temperature applied to a logit of the mean predictive distribution preserves MSP ordering. In multiclass classification this is not guaranteed: logits and have MSP 0.787 and 0.730 at , but 0.576 and 0.604 at . Invariance of ensemble mutual information does not follow either. Geifman and El-Yaniv study selective classification under explicit evaluation conditions.
Confidence far from the data
A finite ReLU network is affine by region. Along a ray , it eventually enters a final region. If one class has a strictly greater slope than the others in that region, logit differences grow linearly and its softmax tends to one. Hein and colleagues prove the result for almost every ray under a distinct-row condition on affine matrices. Without it the claim is false: identical logits may yield uniform softmax forever. The asymptotic result uses an unbounded domain; physical images constrained to cannot travel arbitrarily far along that ray.
Feature collapse occurs when distinct inputs are projected close together in the learned space: a large input distance does not imply a large distance there. Distance-aware uncertainty tries to avoid this. SNGP combines spectral layer normalization with a GP head approximated by random Fourier features; posterior precision in those features yields a variance for moderating logits. Residual connections, projections, and batch normalization must be included in any Lipschitz argument: normalizing only some matrices does not prove a global bound or stable inverse.
After training, DDU fits per-class Gaussian densities in feature space, , and uses low density as an epistemic signal. It depends on regularization, dimension, and representation; neither SNGP nor DDU guarantees detection of every unknown input. Liu and colleagues and Mukhoti and colleagues present these approaches.
Staging the shift
Evaluation under shift fixes data, models, corruption families, and intensities before comparison. Use accuracy, NLL, multiclass Brier, ECE, and AURC: each answers a different question. Low ECE with very low accuracy may reflect uncertainty consistent with frequent errors, not utility. Keep a separate test, report variability across seeds, and do not select only a favorable corruption afterward.
The experiment is deliberately small and its clean models are modest. It does not numerically reproduce CIFAR-10-C or the budgets of Ovadia and colleagues. In these runs an ensemble does not always degrade more smoothly: at maximum Gaussian intensity its mean accuracy was around 0.10. A method that stands out at one level may rank differently at another; do not turn a particular trend into a universal law. The next lesson’s conformal prediction addresses another question: set coverage under explicit assumptions, not a generic accuracy guarantee.
Lab: selective classification
Five MLPClassifier learn synthetic two moons; MSP, entropy, and disagreement are calculated, comparing original data with an input shift preserving generated labels. The budget is 250 iterations per network and may not reach convergence. The oracle only compares rankings on the same test because it uses correctness labels unavailable at deployment.
"""Riesgo-cobertura: expectativa de desempate uniforme, AURC y E-AURC."""
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
def risk_curve(confidence,correct):
confidence=np.asarray(confidence,dtype=float);correct=np.asarray(correct,dtype=bool)
if len(confidence)==0 or len(confidence)!=len(correct):raise ValueError('entradas no vacías e iguales')
order=np.argsort(-confidence,kind='stable');scores=confidence[order];errors=(~correct[order]).astype(float)
n=len(errors);risks=np.empty(n);previous=0.;start=0
while start<n:
end=start+1
while end<n and scores[end]==scores[start]:end+=1
g=end-start;block=errors[start:end].sum()
# En un empate, expectativa sobre todas las permutaciones equiprobables.
j=np.arange(1,g+1);risks[start:end]=(previous+j*block/g)/(start+j)
previous+=block;start=end
return np.arange(1,n+1)/n,risks
def aurc(confidence,correct):
_,risk=risk_curve(confidence,correct);return float(risk.mean())
def e_aurc(confidence,correct):
correct=np.asarray(correct,dtype=bool);return aurc(confidence,correct)-aurc(correct.astype(float),correct)
def entropy(p):
p=np.clip(p,1e-12,1);return -np.sum(p*np.log(p),axis=-1)
def summarize(predictions,y,cost):
p=np.mean(predictions,axis=0);msp=np.max(p,axis=1);correct=p.argmax(1)==y
scores={'MSP':msp,'menos entropía':-entropy(p),'menos MI':-(entropy(p)-np.mean(entropy(predictions),axis=0))}
for name,score in scores.items():print(name,'AURC',aurc(score,correct),'E-AURC',e_aurc(score,correct))
keep=msp>=1-cost;print('Chow c',cost,'cobertura',keep.mean(),'riesgo empírico',float(np.mean(~correct[keep])) if keep.any() else 'sin aceptadas')
return scores,correctX,y=make_moons(n_samples=700,noise=.23,random_state=30)
xtr,xte,ytr,yte=train_test_split(X,y,test_size=.4,stratify=y,random_state=30)
models=[]models.append(MLPClassifier(hidden_layer_sizes=(20,20),alpha=.01,max_iter=250,random_state=30).fit(xtr,ytr))
print('red',len(models),'iteraciones',models[-1].n_iter_)models.append(MLPClassifier(hidden_layer_sizes=(20,20),alpha=.01,max_iter=250,random_state=31).fit(xtr,ytr))
print('red',len(models),'iteraciones',models[-1].n_iter_)models.append(MLPClassifier(hidden_layer_sizes=(20,20),alpha=.01,max_iter=250,random_state=32).fit(xtr,ytr))
print('red',len(models),'iteraciones',models[-1].n_iter_)models.append(MLPClassifier(hidden_layer_sizes=(20,20),alpha=.01,max_iter=250,random_state=33).fit(xtr,ytr))
print('red',len(models),'iteraciones',models[-1].n_iter_)models.append(MLPClassifier(hidden_layer_sizes=(20,20),alpha=.01,max_iter=250,random_state=34).fit(xtr,ytr))
print('red',len(models),'iteraciones',models[-1].n_iter_)for shift in (np.array([0.,0.]),np.array([.5,.3])):
p=np.stack([m.predict_proba(xte+shift) for m in models]);print('shift',shift);summarize(p,yte,.15)
# El escalado de la predictiva media binaria conserva el ranking MSP.
from scipy.special import expit,logit
p=np.stack([m.predict_proba(xte) for m in models]).mean(0); q=expit(logit(np.clip(p[:,1],1e-9,1-1e-9))/2)
print('AURC MSP antes/después T=2',aurc(p.max(1),p.argmax(1)==yte),aurc(np.maximum(q,1-q),p.argmax(1)==yte))Local lab: CIFAR and a GP head
Download cifar_lab.py; it requires PyTorch, torchvision, NumPy, and scikit-learn. torchvision downloads official CIFAR-10 if absent from ORYON_CIFAR_ROOT or ./data. It always uses the same 6000/1000 indices, three seeds, three epochs, a small residual network, 10 dropout passes, and five members per ensemble. Each severity reuses one noise matrix; dropout passes are random. Limits across seeds are a range from three runs, not statistical precision inference.
The head uses 128 Fourier features and a surrogate Gaussian precision with mean-field-style logit correction; it is neither the full multinomial Hessian nor an exact reproduction of original SNGP. Residual projections and batch norm are not all normalized. DDU fits regularized per-class Gaussians over features and compares clean test with severity 5 Gaussian noise; this is a synthetic detection task, not general OOD evaluation. The code computes AURC using stable tie-breaking; exact ties may depend on order, unlike the exercise’s average over tie-breaks.
"""CIFAR-10, ResNet pequeño, ensembles/MC dropout/SNGP y DDU.
Ensayo reducido, no reproducción numérica del benchmark de Ovadia et al.
Descarga datos oficiales con torchvision si no existen en ORYON_CIFAR_ROOT.
"""
import os,json,math,time
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.utils.parametrizations import spectral_norm
from torchvision.datasets import CIFAR10
from sklearn.metrics import roc_auc_score
torch.set_num_threads(2);device='cuda' if torch.cuda.is_available() else 'cpu'
root=os.environ.get('ORYON_CIFAR_ROOT','./data')
train=CIFAR10(root,train=True,download=True);test=CIFAR10(root,train=False,download=True)
rng=np.random.default_rng(30);it=rng.choice(len(train),6000,replace=False);iv=rng.choice(len(test),1000,replace=False)
X=torch.tensor(train.data[it].transpose(0,3,1,2),dtype=torch.float32)/255;y=torch.tensor(np.asarray(train.targets)[it],dtype=torch.long)
Xt=torch.tensor(test.data[iv].transpose(0,3,1,2),dtype=torch.float32)/255;yt=np.asarray(test.targets)[iv]
noise=torch.tensor(np.random.default_rng(90).normal(size=Xt.shape),dtype=torch.float32)
print('device',device,'torch',torch.__version__,'train',len(X),'test',len(Xt),flush=True)
def conv(cin,cout,stride=1,spectral=False):
layer=nn.Conv2d(cin,cout,3,stride,1,bias=False)
return spectral_norm(layer) if spectral else layer
class Block(nn.Module):
def __init__(self,cin,cout,stride,spectral):
super().__init__();self.a=conv(cin,cout,stride,spectral);self.b=conv(cout,cout,1,spectral)
self.n1=nn.BatchNorm2d(cout);self.n2=nn.BatchNorm2d(cout)
self.skip=nn.Identity() if stride==1 and cin==cout else nn.Sequential(nn.AvgPool2d(stride),nn.Conv2d(cin,cout,1,bias=False))
def forward(self,x):return F.relu(self.n2(self.b(F.relu(self.n1(self.a(x)))))+self.skip(x))
class Net(nn.Module):
def __init__(self,drop=0.,gp=False):
super().__init__();self.gp=gp;self.input=conv(3,16,1,gp);self.bn=nn.BatchNorm2d(16)
self.blocks=nn.Sequential(Block(16,16,1,gp),Block(16,32,2,gp),Block(32,64,2,gp));self.drop=nn.Dropout(drop)
if gp:
self.register_buffer('omega',torch.randn(64,128));self.register_buffer('phase',2*math.pi*torch.rand(128));self.out=nn.Linear(128,10)
else:self.out=nn.Linear(64,10)
def features(self,x):
x=(x-.5)/.5;return self.drop(self.blocks(F.relu(self.bn(self.input(x)))).mean((2,3)))
def rff(self,h):return math.sqrt(2/128)*torch.cos([email protected]+self.phase)
def forward(self,x):
h=self.features(x);return self.out(self.rff(h) if self.gp else h)
def fit(seed,drop=0.,gp=False):
torch.manual_seed(seed);model=Net(drop,gp).to(device);opt=torch.optim.Adam(model.parameters(),lr=.001,weight_decay=.0001)
gen=torch.Generator().manual_seed(seed)
for epoch in range(3):
model.train();order=torch.randperm(len(X),generator=gen)
for ids in order.split(128):
xx=X[ids].to(device);yy=y[ids].to(device);opt.zero_grad();loss=F.cross_entropy(model(xx),yy);loss.backward();opt.step()
model.eval();return model
def feature_matrix(model,images):
model.eval();out=[]
with torch.no_grad():
for xx in images.split(256):out.append(model.features(xx.to(device)).cpu())
return torch.cat(out)
def gp_cov(model):
h=feature_matrix(model,X).to(device);phi=model.rff(h)
# Gaussian-observation precision surrogate; not full multinomial Hessian.
precision=torch.eye(phi.shape[1],device=device)+phi.T@phi
return torch.linalg.inv(precision)
def predict(model,images,mc=1,cov=None):
model.eval()
if mc>1:model.drop.train()
outputs=[]
with torch.no_grad():
for _ in range(mc):
chunks=[]
for xx in images.split(256):
xx=xx.to(device)
if cov is None:logits=model(xx)
else:
h=model.features(xx);phi=model.rff(h);logits=model.out(phi)
var=torch.sum((phi@cov)*phi,dim=1);logits=logits/torch.sqrt(1+math.pi*var[:,None]/8)
chunks.append(logits.softmax(-1).cpu())
outputs.append(torch.cat(chunks))
model.eval();return torch.stack(outputs).mean(0).numpy()
def metrics(p,y):
p=np.clip(p,1e-12,1);pred=p.argmax(1);conf=p.max(1);correct=pred==y;n=len(y)
ece=0.
for j in range(10):
mask=(conf>=j/10)&((conf<(j+1)/10) if j<9 else (conf<=1))
if mask.any():ece+=mask.mean()*abs(correct[mask].mean()-conf[mask].mean())
order=np.argsort(-conf,kind='stable');risk=np.cumsum(~correct[order])/np.arange(1,n+1)
onehot=np.eye(10)[y]
return {'accuracy':float(correct.mean()),'nll':float(-np.log(p[np.arange(n),y]).mean()),'brier':float(np.mean(np.sum((p-onehot)**2,axis=1))),'ece':float(ece),'aurc':float(risk.mean())}
def ddu(model,images):
h=feature_matrix(model,X).numpy();z=feature_matrix(model,images).numpy();d=h.shape[1];logs=[]
for c in range(10):
a=h[y.numpy()==c];mean=a.mean(0);cov=np.cov(a.T)+.01*np.eye(d);L=np.linalg.cholesky(cov);r=np.linalg.solve(L,(z-mean).T)
logs.append(-.5*np.sum(r*r,axis=0)-np.log(np.diag(L)).sum()+np.log(len(a)/len(h)))
values=np.stack(logs,axis=1);m=values.max(1);return m+np.log(np.exp(values-m[:,None]).sum(1))
def corrupted(kind,s):
if kind=='gauss':return torch.clamp(Xt+[0,.05,.10,.15,.20,.30][s]*noise,0,1)
return torch.clamp((Xt-.5)*[1,.8,.6,.4,.25,.1][s]+.5,0,1)
results={}
for seed in (30,31,32):
t=time.time();ensemble=[fit(seed*10+i) for i in range(5)];drop=fit(seed*10+8,drop=.2);gp=fit(seed*10+9,gp=True);cov=gp_cov(gp)
result={}
for kind in ('gauss','contraste'):
result[kind]={}
for severity in range(6):
xx=corrupted(kind,severity)
pred={'ensemble':np.mean([predict(m,xx) for m in ensemble],axis=0),'dropout':predict(drop,xx,mc=10),'sngp':predict(gp,xx,cov=cov)}
result[kind][str(severity)]={name:metrics(p,yt) for name,p in pred.items()}
clean=ddu(gp,Xt);shift=ddu(gp,corrupted('gauss',5))
result['ddu_auroc']=float(roc_auc_score(np.r_[np.zeros(len(clean)),np.ones(len(shift))],np.r_[-clean,-shift]))
results[str(seed)]=result
print('semilla',seed,'segundos',round(time.time()-t,1),'DDU AUROC ruido 5',result['ddu_auroc'],'limpio',result['gauss']['0'],flush=True)
with open('cifar_results.json','w',encoding='utf-8') as f:json.dump(results,f)
del ensemble,drop,gp,cov
if device=='cuda':torch.cuda.empty_cache()
print('memoria máxima GPU MB',torch.cuda.max_memory_allocated()/1e6 if device=='cuda' else 0)npm run lab and open the connection link.Exercises
Step 1 of 2. What is the minimum conditional risk if you decide on a class?
Step 1 of 2. What happens to a ray after enough region changes?
aurc(confidence, correct) and e_aurc(confidence, correct). AURC is the mean risk across n prefixes ordered by decreasing confidence. Within a tied group use the uniform expectation over all group permutations. E-AURC subtracts the AURC of the oracle ordering that places correct predictions before errors.def aurc(confidence, correct):
pass
def e_aurc(confidence, correct):
passSummary
- Chow compares conditional error with rejection cost; AURC and E-AURC summarize rankings with an explicit tie convention.
- ReLU can become arbitrarily confident far from data under precise assumptions; feature distance is not input distance.
- Compare methods and metrics at several severities, declare budgets, and do not infer guarantees beyond the protocol.