Uncertainty quantification and Bayesian deep learning
Separate predictive uncertainty into aleatoric and epistemic components, use epistemic uncertainty for active learning with BALD, and apply Bayesian inference to neural networks. Compare reference HMC posteriors with scalable approximations such as last-layer Laplace, MC dropout, SWAG, and deep ensembles. Use the NNGP from lesson 16 as a function-space prior and examine the cold posterior effect.
After this lesson you can
- Decompose predictive variance and entropy into aleatoric and epistemic components.
- Implement active learning with BALD and compare it with maximum-entropy acquisition.
- Implement last-layer Laplace, MC dropout, and a deep ensemble, and evaluate NLL, ECE, and out-of-distribution detection.
- Use the NNGP kernel from lesson 16 in your GP regression as an infinite-width reference for finite networks.
- Define tempered posteriors, reproduce the cold posterior effect in a small problem, and assess proposed explanations.
Before you start
- 14Laplace approximationGaussian process regressionReparameterization gradientHamiltonian Monte CarloLangevin Monte CarloBayesian model averagingNon-identifiability and label switchingNeural network Gaussian process limit
- 15Multilayer perceptronBackpropagation
- 00Canonical training and evaluation loop
- 11Classifier calibrationReliability diagram
- 07Mutual information
- 13Gibbs posteriorPAC-Bayes bound
What does it mean to be uncertain?
A network can assign a probability close to one to inputs far from its training data. Accuracy on similar data alone does not reveal this behavior. If represents plausible models after observing , the law of total variance separates the following terms for each :
The decomposition into aleatoric and epistemic uncertainty calls the first term aleatoric uncertainty, the conditional variation that the model attributes to the observation. The second term is epistemic uncertainty, the disagreement about the mean across posterior parameter values. The distinction depends on the model, the data, and what counts as an observation. More data can reduce disagreement in regions it informs. The assumed conditional noise is still present. In classification, mixture entropy decomposes into average conditional entropy and mutual information. Kendall and Gal distinguish these two notions in computer vision.
Query where the label teaches you something
For classification, BALD selects the point with the greatest mutual information between the label and parameters:
Total entropy can be high when models disagree or when all models predict a fair coin. In the second case, the label gives no information about which model is correct. Houlsby and colleagues apply this identity to GP classifiers. The figure makes the distinction clear by giving the model a known region with 50% irreducible noise. The 5000 functions are samples from the GP prior, reweighted as labels arrive. Low effective sample size warns of weight degeneracy and limits the approximation.
Uncertain weights and approximations
A Bayesian neural network combines a weight prior with a likelihood and averages predictions under the posterior. Permuting hidden units can leave the function unchanged, so different weight-space modes may give identical predictions. Full-batch HMC can serve as a demanding reference. It needs diagnostics and substantial compute, and even a reference approximation offers no automatic robustness under distribution shift. Izmailov and colleagues study these questions empirically.
Among scalable approximations, Laplace approximates the posterior locally by a Gaussian around the MAP estimate. Last-layer Laplace freezes the features . For binary classification, the GGN matrix is
Include the bias by appending a one to . A logistic–probit approximation uses with and to approximate the predictive integral. Full Laplace considers all weights. KFAC approximates curvature blocks, while last-layer Laplace reduces cost by ignoring uncertainty in the features. Daxberger and colleagues and the Laplace library describe these alternatives.
MC dropout keeps the masks active at prediction time and averages several passes. Its Bayesian interpretation depends on assumptions about training and dropout rates. A deep ensemble trains several networks from different initializations and averages their probabilities. It provides a practical baseline, and its members need not be posterior samples. SWAG fits a Gaussian with low-rank and diagonal covariance terms to weight statistics collected during SGD. See Gal and Ghahramani, Lakshminarayanan and colleagues, and Maddox and colleagues for the methods and their costs.
The NNGP from lesson 16 gives another reference. Under suitable independence and scaling assumptions, an infinitely wide random network induces a GP prior. Condition it using GP inference. A trained finite network generally has a different posterior. The lab compares the exact ReLU kernel with finite random features and observes Monte Carlo error. Lee and colleagues derive the deep limit.
Changing the temperature
A fully tempered posterior has , provided it can be normalized. At the difference between high- and low-density regions grows. Tempering the likelihood alone gives a different distribution. The PAC-Bayes Gibbs posterior also weights a loss exponentially, with a scale setting the balance against the prior. Some temperatures have no ordinary Bayesian interpretation under the original model.
Wenzel and colleagues observed improved prediction with cold posteriors in some experiments. Izmailov and colleagues found little evidence of the effect in their setting and attributed much of it to data augmentation. Model misspecification, priors, likelihoods, inference approximations, and evaluation all merit study. The figure shows a small example and short chains. Test NLL, calibration, and detection under relevant shifts alongside accuracy. Compare the compute for one network with that for five.
Labs
BALD with a GP prior
This self-contained example reweights a collection of GP functions after each label. The noisy region is known, and the strategies share the available labels and a budget of 12 queries. ESS measures how many particles contribute effectively. Posterior accuracy requires additional checks.
"""BALD y entropía en un clasificador GP aproximado por partículas."""
import numpy as np
from scipy.special import expit
rng=np.random.default_rng(2026)
points=rng.uniform(-2,2,(70,2)); d=((points[:,None]-points[None,:])**2).sum(-1)
K=np.exp(-d/(2*.8**2))+1e-6*np.eye(len(points))
f=rng.normal(size=(3000,len(points)))@np.linalg.cholesky(K).T*2
flip=np.where(points[:,0]>.9,.5,0.)
p=flip+(1-2*flip)*expit(f)
true=expit(2*(points[:,1]-.6*np.sin(2*points[:,0])))
labels=rng.binomial(1,flip+(1-2*flip)*true)
def H(p):
p=np.clip(p,1e-12,1-1e-12); return -p*np.log(p)-(1-p)*np.log(1-p)
for strategy in ('azar','entropia','bald'):
w=np.ones(len(f))/len(f);chosen=[];r=np.random.default_rng(87)
for _ in range(12):
avg=w@p;score=H(avg) if strategy=='entropia' else H(avg)-w@H(p);score[chosen]=-np.inf
i=int(r.choice([j for j in range(len(points)) if j not in chosen])) if strategy=='azar' else int(np.argmax(score))
chosen.append(i);w*=p[:,i] if labels[i] else 1-p[:,i];w/=w.sum()
print(strategy,'consultas ruidosas',sum(flip[chosen]>.0),'ESS final',round(1/(w@w),1))NNGP and finite width
Each feature is the output of two random ReLU layers with Gaussian biases and width-scaled weights. Apply the arc-cosine kernel recursion from lesson 16 twice and add the unit bias variance between layers. Condition both the exact and approximate kernels with the same Gaussian noise. Compare the means and variances. The error for a single seed need not decrease monotonically.
"""GP ReLU de anchura infinita frente a características aleatorias finitas."""
import numpy as np
rng=np.random.default_rng(26)
x=np.linspace(-2,2,12); y=np.sin(x)+rng.normal(0,.12,len(x)); xt=np.linspace(-2.5,2.5,60)
def kernel(a,b):
a=np.asarray(a);b=np.asarray(b);q=a*a+1; qp=b*b+1
def relu(cov,q,qp):
cos=np.clip(cov/np.sqrt(np.outer(q,qp)),-1,1); theta=np.arccos(cos)
return np.sqrt(np.outer(q,qp))*(np.sin(theta)+(np.pi-theta)*cos)/(2*np.pi)
first=relu(np.outer(a,b)+1,q,qp)
return relu(first+1,q/2+1,qp/2+1)
def gp(K,Ks,Kss):
L=np.linalg.cholesky(K+.12**2*np.eye(len(x))); v=np.linalg.solve(L,Ks)
return [email protected](L.T,np.linalg.solve(L,y)),np.diag(Kss)-np.sum(v*v,axis=0)
ref,rv=gp(kernel(x,x),kernel(x,xt),kernel(xt,xt))
for width in (100,500):
w=rng.normal(size=width);b=rng.normal(size=width)
A0=np.maximum(0,x[:,None]*w+b);B0=np.maximum(0,xt[:,None]*w+b)
W=rng.normal(size=(width,width))/np.sqrt(width);bias=rng.normal(size=width)
A=np.maximum(0,A0@W+bias)/np.sqrt(width);B=np.maximum(0,B0@W+bias)/np.sqrt(width)
m,v=gp([email protected],[email protected],[email protected])
print('anchura',width,'error RMSE media',np.sqrt(np.mean((m-ref)**2)),'error medio varianza',np.mean(abs(v-rv)))
print('NNGP media y varianza primeras',ref[:3],rv[:3])HMC and temperature in logistic regression
Use exactly the synthetic generator from lesson 7 and the logistic density with precision 1.5, raising both the prior and likelihood to . This implementation uses fixed-step HMC with 300 warm-up steps, 800 retained draws per temperature, and a single chain. The acceptance rate alone cannot establish convergence. Test and training data share the same generator. Small differences may reflect Monte Carlo noise.
"""Posterior logística de l07, potenciada completa y muestreada con HMC."""
import numpy as np
from scipy.special import expit
def synthetic_data(seed=2026,n_train=40,n_test=2000):
rng=np.random.default_rng(seed);true_w=np.array([-.4,1.4,-1.])
def generate(n):
X=np.column_stack((np.ones(n),rng.normal(size=(n,2))));y=rng.binomial(1,expit(X@true_w));return X,y
X,y=generate(n_train);Xt,yt=generate(n_test);return X,y,Xt,yt
X,y,Xt,yt=synthetic_data();alpha=1.5
def leapfrog(grad,q,p,eps,L):
q=q.copy();p=p.copy();p+=.5*eps*grad(q)
for i in range(L):
q+=eps*p
if i<L-1:p+=eps*grad(q)
p+=.5*eps*grad(q);return q,p
def sample(T,seed):
rng=np.random.default_rng(seed);q=np.zeros(3);eps=.075*np.sqrt(T);out=[];accepted=0
def logp(w):return (y@(X@w)-np.logaddexp(0,X@w).sum()-.5*alpha*(w@w))/T
def grad(w):return (X.T@(y-expit(X@w))-alpha*w)/T
for i in range(1100):
p=rng.normal(size=3);qq,pp=leapfrog(grad,q,p,eps,8)
delta=logp(qq)-logp(q)+.5*(p@p-pp@pp)
if np.log(rng.random())<min(0,delta):q=qq;accepted+=i>=300
if i>=300:out.append(q.copy())
return np.array(out),accepted/800T=0.1
samples,acc=sample(T,100+int(10*T));p=expit([email protected]).mean(1);p=np.clip(p,1e-9,1-1e-9)
print('T',T,'NLL',-np.mean(yt*np.log(p)+(1-yt)*np.log(1-p)),'aceptación',acc)T=0.2
samples,acc=sample(T,100+int(10*T));p=expit([email protected]).mean(1);p=np.clip(p,1e-9,1-1e-9)
print('T',T,'NLL',-np.mean(yt*np.log(p)+(1-yt)*np.log(1-p)),'aceptación',acc)T=0.5
samples,acc=sample(T,100+int(10*T));p=expit([email protected]).mean(1);p=np.clip(p,1e-9,1-1e-9)
print('T',T,'NLL',-np.mean(yt*np.log(p)+(1-yt)*np.log(1-p)),'aceptación',acc)T=1.0
samples,acc=sample(T,100+int(10*T));p=expit([email protected]).mean(1);p=np.clip(p,1e-9,1-1e-9)
print('T',T,'NLL',-np.mean(yt*np.log(p)+(1-yt)*np.log(1-p)),'aceptación',acc)T=2.0
samples,acc=sample(T,100+int(10*T));p=expit([email protected]).mean(1);p=np.clip(p,1e-9,1-1e-9)
print('T',T,'NLL',-np.mean(yt*np.log(p)+(1-yt)*np.log(1-p)),'aceptación',acc)GPU networks and UCI data
Download the full code as incertidumbre.py. It requires PyTorch, NumPy, SciPy, and scikit-learn and uses CUDA when available. Airfoil Self-Noise comes from the original UCI archive, downloaded over HTTPS and identified by its ZIP SHA-256. The split is random, and normalization is fitted only on the training set. Regression NLL uses normalized response units and an estimated residual variance. The regression calibration error averages deviations in central coverage across nine levels. Classification ECE instead uses ten confidence bins. OOD inputs come from a shifted synthetic normal in standardized coordinates. They model a specific change and are separate from any real domain-shift benchmark. The ensemble requires five training runs, and MC dropout uses 50 passes.
"""MLP, Laplace de última capa, MC dropout y conjunto sobre dos tareas.
Datos: dos lunas sintéticas y Airfoil Self-Noise (UCI, URL fija). No afirma
equivalencia de presupuestos ni generalización fuera de estos conjuntos.
"""
import io, zipfile, urllib.request, hashlib
import numpy as np
import torch
from torch import nn
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from scipy.special import ndtr
from scipy.optimize import minimize
torch.set_num_threads(1)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('dispositivo', device, 'torch', torch.__version__)
seed = 26
rng = np.random.default_rng(seed)
class Net(nn.Module):
def __init__(self, d, dropout=.1):
super().__init__()
self.features = nn.Sequential(nn.Linear(d, 32), nn.Tanh(), nn.Dropout(dropout),
nn.Linear(32, 32), nn.Tanh(), nn.Dropout(dropout))
self.last = nn.Linear(32, 1)
def forward(self, x): return self.last(self.features(x)).squeeze(-1)
def fit(x, y, task, seed, steps=800):
torch.manual_seed(seed)
net = Net(x.shape[1]).to(device)
opt = torch.optim.Adam(net.parameters(), lr=.01, weight_decay=1e-4)
x, y = torch.tensor(x, dtype=torch.float32, device=device), torch.tensor(y, dtype=torch.float32, device=device)
for _ in range(steps):
net.train(); opt.zero_grad(); pred=net(x)
loss = nn.functional.binary_cross_entropy_with_logits(pred,y) if task=='class' else ((pred-y)**2).mean()/2
loss.backward(); opt.step()
net.eval(); return net
def phi(net,x):
with torch.no_grad():
a=net.features(torch.as_tensor(x,dtype=torch.float32,device=device)).cpu().numpy()
return np.column_stack((a,np.ones(len(a))))
def posterior(net,x,y,task,precision=1):
X=phi(net,x); w=np.r_[net.last.weight.detach().cpu().numpy().ravel(),net.last.bias.detach().cpu().numpy()]
z=X@w
if task=='class':
def objective(v):
z=X@v; p=1/(1+np.exp(-np.clip(z,-40,40)))
return (np.logaddexp(0,z).sum()-y@z+.5*precision*(v@v), X.T@(p-y)+precision*v)
opt=minimize(objective,w,jac=True,method='BFGS',options={'gtol':1e-8});w=opt.x
z=X@w;p=1/(1+np.exp(-np.clip(z,-40,40))); noise=1.; weight=p*(1-p)
else:
noise=max(np.mean((y-z)**2),.01); weight=np.full(len(x),1/noise)
w=np.linalg.solve(X.T@(weight[:,None]*X)+precision*np.eye(X.shape[1]),X.T@(weight*y))
H=X.T@(weight[:,None]*X)+precision*np.eye(X.shape[1])
return w,np.linalg.inv(H),noise
def predictions(nets,x,y,xt,task,method):
net=nets[0]
if method=='laplace':
w,cov,noise=posterior(net,x,y,task); X=phi(net,xt)
# probit approximation to the logistic-normal integral
m=X@w; v=np.einsum('ij,jk,ik->i',X,cov,X)
if task=='class': return 1/(1+np.exp(-m/np.sqrt(1+np.pi*v/8))),None
return m,np.maximum(noise+v,1e-6)
vals=[]
chosen=nets if method=='ensemble' else [net]*50 if method=='dropout' else [net]
with torch.no_grad():
for m in chosen:
m.train(method=='dropout'); v=m(torch.as_tensor(xt,dtype=torch.float32,device=device)).cpu().numpy()
vals.append(1/(1+np.exp(-np.clip(v,-40,40))) if task=='class' else v)
m.eval()
vals=np.array(vals)
if task=='class': return vals.mean(0),None
residual=np.mean((y-net(torch.as_tensor(x,dtype=torch.float32,device=device)).detach().cpu().numpy())**2)
return vals.mean(0),np.maximum(vals.var(0)+residual,1e-6)
def metrics(y,p,var,task):
if task=='class':
p=np.clip(p,1e-7,1-1e-7); nll=-np.mean(y*np.log(p)+(1-y)*np.log(1-p))
conf=np.maximum(p,1-p); correct=(p>=.5)==y; ece=0.
for lo in np.linspace(0,1,11)[:-1]:
mask=(conf>=lo)&(conf<(lo+.1) if lo<.9 else conf<=1)
if mask.any(): ece+=mask.mean()*abs(correct[mask].mean()-conf[mask].mean())
return nll,ece
nll=np.mean(.5*np.log(2*np.pi*var)+.5*(y-p)**2/var)
z=np.abs(y-p)/np.sqrt(var)
levels=np.arange(.1,1.,.1); empirical=np.array([(2*ndtr(z)-1<=v).mean() for v in levels])
return nll,np.mean(np.abs(empirical-levels))
def run(name,X,y,task):
x,xte,yt,yte=train_test_split(X,y,test_size=.25,random_state=seed,stratify=y if task=='class' else None)
mean=x.mean(0); scale=x.std(0); scale[scale==0]=1; x=(x-mean)/scale; xte=(xte-mean)/scale
if task=='reg':
ym,ys=yt.mean(),yt.std(); yt=(yt-ym)/ys; yte=(yte-ym)/ys
nets=[fit(x,yt,task,seed+i) for i in range(5)]
# Synthetic covariate shift, deliberately overlapping, is not a real OOD benchmark.
ood=rng.normal(3,1,size=xte.shape)
print('\n',name,'n',len(x),len(xte),'synthetic OOD N(3,1), shifted standardized features')
for method in ['map','laplace','dropout','ensemble']:
p,v=predictions(nets,x,yt,xte,task,method); po,vo=predictions(nets,x,yt,ood,task,method)
nll,ece=metrics(yte,p,v,task)
score=(lambda q: -(q*np.log(np.clip(q,1e-8,1))+(1-q)*np.log(np.clip(1-q,1e-8,1)))) if task=='class' else None
s=score(p) if task=='class' else v; so=score(po) if task=='class' else vo
auc=roc_auc_score(np.r_[np.zeros(len(s)),np.ones(len(so))],np.r_[s,so])
print(method,'NLL',round(nll,4),'ECE' if task=='class' else 'coverage calibration error',round(ece,4),'OOD AUROC',round(auc,4))
return nets,x,yt
if __name__ == '__main__':
X,y=make_moons(n_samples=600,noise=.20,random_state=seed)
classification=run('dos lunas',X,y,'class')
url='https://archive.ics.uci.edu/static/public/291/airfoil+self+noise.zip'
raw=urllib.request.urlopen(url,timeout=60).read()
print('UCI SHA256 zip',hashlib.sha256(raw).hexdigest())
with zipfile.ZipFile(io.BytesIO(raw)) as z:
a=np.loadtxt(io.BytesIO(z.read('airfoil_self_noise.dat')))
regression=run('UCI Airfoil Self-Noise',a[:,:-1],a[:,-1],'reg')npm run lab and open the connection link.As an independent curvature check, laplace-torch computes the full GGN for a two-logit layer. Use the previous network with its features frozen. The first logit starts at zero and the second matches the binary output. Compare matrices at this point. The two-logit parameterization has redundant parameters and a different prior, so its posterior can differ. The library runs on CPU because the full backend in this version needs its identity matrix there. The preceding network training uses CUDA when available.
from laplace import Laplace
from torch.utils.data import DataLoader,TensorDataset
nets,x,y=classification;net=nets[0]
class TwoLogits(nn.Module):
def __init__(self,net):
super().__init__();self.features=net.features
self.last=nn.Linear(32,2).to(next(net.parameters()).device)
with torch.no_grad():
self.last.weight[0].zero_();self.last.bias[0].zero_()
self.last.weight[1].copy_(net.last.weight[0]);self.last.bias[1].copy_(net.last.bias[0])
def forward(self,x):return self.last(self.features(x))
model=TwoLogits(net).eval().cpu()
tensor=torch.tensor(x,dtype=torch.float32); labels=torch.tensor(y,dtype=torch.long)
loader=DataLoader(TensorDataset(tensor,labels),batch_size=80)
la=Laplace(model,'classification',subset_of_weights='last_layer',hessian_structure='full',prior_precision=1.,last_layer_name='last')
la.fit(loader)
P=la.posterior_precision.detach().numpy()
with torch.no_grad():
A=np.column_stack((model.features(tensor).numpy(),np.ones(len(x))))
probs=model(tensor).softmax(-1).numpy()
H=np.eye(66)
for a,p in zip(A,probs): H+=np.kron(np.diag(p)-np.outer(p,p),np.outer(a,a))
# Orden por clase con sesgo al final de cada bloque -> orden torch: pesos, sesgos.
perm=np.r_[np.arange(32),np.arange(33,65),32,65];H=H[np.ix_(perm,perm)]
print('forma',P.shape,'error máximo',np.max(np.abs(P-H)),'error relativo Frobenius',np.linalg.norm(P-H)/np.linalg.norm(H))npm run lab and open the connection link.Exercises
Step 1 of 2. How do you split the difference between y and its predictive mean?
Step 1 of 2. Which entropy identity defines mutual information?
laplace_predict(Phi, probs, precision, W, Xtest). Phi is N×D and includes the bias, probs is N×C with MAP probabilities, and W is C×D. Build the full class-wise GGN, H = precision I + sum_i kron(diag(p_i) − p_i p_iᵀ, phi_i phi_iᵀ). Return normalized probabilities by taking the softmax of m_c / sqrt(1 + π v_c / 8) using each logit’s marginal variance. This approximates the softmax integral.def laplace_predict(Phi, probs, precision, W, Xtest):
passSummary
- BALD seeks reducible disagreement, while total entropy includes known noise.
- Laplace, dropout, and ensembles provide different approximations at different costs. Under suitable assumptions, NNGP gives a limiting prior.
- The cold posterior effect raises questions about model specification and inference. Its predictive impact depends on the setting.