Module contents
Lesson 26 of 27Research 110 min

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

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 θ\theta represents plausible models after observing DD, the law of total variance separates the following terms for each xx:

Var⁡(y∣x,D)=Eθ∣D[Var⁡(y∣x,θ)]+Var⁡θ∣D[E(y∣x,θ)].\Var(y\mid x,D)=\E_{\theta\mid D}[\Var(y\mid x,\theta)]+\Var_{\theta\mid D}[\E(y\mid x,\theta)].

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.

InteractiveNoise and disagreement
Data in the gap
Mean epistemic variance in the gap0.073
Observations30
Exact posterior for a linear model with six basis functions and known heteroscedastic noise. Add synthetic observations in the gap and compare the bands. The orange band adds the variances before taking the square root.

Query where the label teaches you something

For classification, BALD selects the point with the greatest mutual information between the label and parameters:

I(y;θ∣x,D)=H ⁣(Eθp(y∣x,θ))−EθH[p(y∣x,θ)].I(y;\theta\mid x,D)=H\!\left(\E_\theta p(y\mid x,\theta)\right)-\E_\theta H[p(y\mid x,\theta)].

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.

InteractiveChoosing queries
Acquisition
12
Queries in the noisy strip0 of 12
Final particle ESS110
The same 70 synthetic points and labels are used for each strategy. After 12 queries, entropy selects 12 points in the noisy region, BALD selects none, and random selection picks 5. This is one realization with known noise.

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 ϕ(x)\phi(x). For binary classification, the GGN matrix is

H=αI+∑ipi(1−pi)ϕiϕi⊤,Σ=H−1.\mat H=\alpha\mat I+\sum_i p_i(1-p_i)\phi_i\phi_i\T,\qquad \mat\Sigma=\mat H^{-1}.

Include the bias by appending a one to ϕ\phi. A logistic–probit approximation uses p(y=1∣x,D)≈σ(m/1+πv/8)p(y=1\mid x,D)\approx\sigma(m/\sqrt{1+\pi v/8}) with m=ϕ⊤w^m=\phi\T\hat w and v=ϕ⊤Σϕv=\phi\T\Sigma\phi 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.

InteractiveLast-layer Laplace on two moons
Prediction
Prior precision
Training points300
p(class 1) at (3, 0)0.991
Reproducible synthetic training. The last layer is reoptimized at each precision, then its MAP prediction is compared with the predictive approximation. Confidence outside the data can behave differently for other architectures.

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 pT(θ∣D)∝[p(D∣θ)p(θ)]1/Tp_T(\theta\mid D)\propto[p(D\mid\theta)p(\theta)]^{1/T}, provided it can be normalized. At T<1T<1 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.

InteractiveTemperature and data augmentation
Temperature
Data
Test NLL0.445
Test accuracy0.790
A small network and prerecorded full-batch SGLD chains, with and without two perturbed copies of each training example. The figure uses a synthetic split and 500 draws per chain. The short runs provide no demonstration of convergence.

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 with GP particlesBrowser
"""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.

[ ]NNGP and finite featuresBrowser
"""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 1/T1/T. 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.

[ ]Generator and HMCBrowser
"""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/800
[ ]Temperature 0.1Browser
T=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)
[ ]Temperature 0.2Browser
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)
[ ]Temperature 0.5Browser
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)
[ ]Temperature 1.0Browser
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)
[ ]Temperature 2.0Browser
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.

[ ]Networks, Airfoil, and evaluationLocal GPU
"""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')
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Check GGN against laplace-torchLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofDecomposing variance
Prove: Prove the law of total variance for the predictive distribution.
0
Assume finite second moments and write m(θ) for the conditional mean of y given θ and x.

Step 1 of 2. How do you split the difference between y and its predictive mean?

ProofThe BALD identity
Prove: Show that BALD is mutual information between the label and parameters.
0
Condition on x and D and assume a discrete label.

Step 1 of 2. Which entropy identity defines mutual information?

NumericThree predictors
Three equally likely models give probabilities 0.9, 0.5, and 0.1 for the positive class. Compute BALD in nats.
NumericTempering a normal distribution
Raise the density of N(0,1) to 1/T and normalize it with T=0.5. What is the resulting standard deviation?
QuizInterpreting temperature
What does the cold posterior effect describe?
CodeLast-layer curvature
Implement 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):
  pass
Shift+Enter to run

Summary

Key idea
Predictive uncertainty combines noise and disagreement about the model. Measure it by checking predictions and decisions in specific conditions.
  • 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.