Bayesian workflow and probabilistic programming
Build a small probabilistic programming language with effect handlers to understand the machinery behind PyMC, NumPyro and Pyro. Integrate predictive checks, validate the algorithm with simulation-based calibration, compare models with Pareto-smoothed importance-sampling leave-one-out, and estimate evidence with bridge sampling or thermodynamic integration.
After this lesson you can
- Build a minimal probabilistic programming language with traces, conditioning and seeding via effect handlers.
- Integrate prior and posterior predictive checks using statistics chosen to detect specific failures.
- Validate a sampler or model with simulation-based calibration (SBC).
- Calculate PSIS-LOO, interpret the k̂ diagnostic, and compare with WAIC and Bayes factors.
- Estimate evidence in a nonconjugate model with bridge sampling and thermodynamic integration, and explain the harmonic-mean estimator’s failure.
- Run a full workflow in PyMC or NumPyro with ArviZ.
Before you start
- 14Bayesian hierarchical modelPriors for hierarchical scale parametersNo-U-Turn SamplerRank-normalized split R-hatMCMC effective sample sizeBayesian model averagingBayesian information criterionLaplace approximation to the evidenceAutomatic differentiation variational inferenceSelf-normalized importance samplingImportance-sampling effective sample sizeAncestral sampling
- 05Posterior predictive checksWeakly informative priors and prior predictive simulationMarginal likelihood (evidence)Bayes factor and the Jeffreys-Lindley paradox
- 11k-fold cross-validation
A cycle, not just a fit
A Bayesian workflow alternates construction, simulation, fitting, diagnosis, criticism and revision. Before seeing data, the prior predictive distribution shows what observations the model considers possible. After fitting, a posterior predictive check compares a statistic chosen for a specific suspicion with model replicates: for example, the proportion of zeros or the variance in count data. Because the data are used both to fit and to check, this comparison is not automatically a frequentist test with a uniform p-value.
Probabilistic programming separates a program that declares distributions and sampling sites from the mechanisms that record, condition or substitute those sites. A trace stores values and log-density contributions. Conditioning a site fixes an observation; that does not perform inference by itself. Seeds reproduce a sequence under a particular implementation, and a plate expresses conditional repetition, not unconditional marginal independence.
Calibrating the algorithm
Simulation-based calibration (SBC) repeats: generate a parameter from the prior, simulate data, run the algorithm and record the generated parameter’s rank among posterior draws. If inference is exact and posterior draws are exchangeable with the generated value conditional on the data, the rank is uniform between 0 and . Ties require an appropriate randomized rule. Correlated chains can distort the histogram even if their marginal distribution is correct; an apparently flat histogram does not prove that everything is right either.
A posterior that is too narrow often produces excess extreme ranks; one that is too wide produces excess central ranks. A prior incompatible with the generator can produce asymmetry. These are indicative patterns, not unique diagnoses: the number of repetitions, correlation and chosen statistic also matter. Talts and colleagues develop SBC as a check of the implementation and algorithm, not proof that the model describes real data well.
LOO, PSIS and predictive comparison
Leave-one-out validation evaluates . Given draws from , importance weights for leaving out are proportional to . The tail of these weights can be extreme. PSIS-LOO fits a generalized Pareto distribution to the tail and smooths the weights; diagnoses whether the approximation is reliable. The practical threshold also depends on the number of draws: one rule used is .
A high indicates that a few draws dominate and error can be large; consider checking the data point and model, increasing draws when appropriate or refitting with the point left out. It does not by itself prove the data point is wrong. WAIC also estimates predictive ability from pointwise log likelihoods but can be unstable with influential observations. Stacking selects weights for a predictive mixture using the LOO score; they are not posterior probabilities that each model is true. The PSIS and stacking papers detail their conditions.
Evidence and normalizing constants
Evidence estimation seeks . Importance sampling averages under a normalized proposal; it needs overlap and suitable tails. Bridge sampling combines posterior and proposal draws using a ratio-of-constants identity that can be solved iteratively. Thermodynamic integration uses and
if the prior is normalized and the conditions for exchanging integration and differentiation hold. Chains at each temperature have their own error, and quadrature introduces another. AIS uses a sequence of intermediate distributions to construct weights, with its own assumptions; it is not the same as a single posterior chain.
The harmonic mean identity can exist while its estimator has infinite variance. Apparent stability in a few draws does not guarantee accuracy. The Bayes factor compares evidences and depends on complete priors; LOO asks about prediction of held-out observations. They can therefore disagree without contradiction. Stan, PyMC, NumPyro and Pyro offer different languages and inference strategies: the choice depends on the model, available computation and diagnostics, not only syntax.
Labs
Mini PPL: trace, condition and substitution
The mini_ppl.py module is deliberately small: it supports normals, a handler stack and a plate represented by a vector. It does not handle all distributions, transformations, parallelism or semantics of a full PPL. The innermost handler fixing a site takes priority; explicit observations already fixed are not overwritten. Log densities are recorded per site and a seed is required for values to be simulated.
"""Un PPL mínimo para variables normales y manejadores componibles."""
import numpy as np
_stack=[]
class Normal:
def __init__(self,loc,scale):
self.loc=np.asarray(loc);self.scale=np.asarray(scale)
if np.any(self.scale<=0):raise ValueError('scale debe ser positiva')
def sample(self,rng):return rng.normal(self.loc,self.scale)
def log_prob(self,value):
z=(np.asarray(value)-self.loc)/self.scale
return -.5*z*z-np.log(self.scale)-.5*np.log(2*np.pi)
class Handler:
def __enter__(self):_stack.append(self);return self
def __exit__(self,*exc):
if _stack[-1] is not self:raise RuntimeError('orden de manejadores inválido')
_stack.pop()
def process(self,msg):pass
def postprocess(self,msg):pass
class seed(Handler):
def __init__(self,value):self.rng=np.random.default_rng(value)
def process(self,msg):
if msg['rng'] is None:msg['rng']=self.rng
class condition(Handler):
def __init__(self,values):self.values=values
def process(self,msg):
if msg['value'] is None and msg['name'] in self.values:
msg['value']=self.values[msg['name']];msg['observed']=True
class substitute(Handler):
def __init__(self,values):self.values=values
def process(self,msg):
if msg['value'] is None and msg['name'] in self.values:msg['value']=self.values[msg['name']]
class trace(Handler):
def __init__(self):self.sites={}
def postprocess(self,msg):
if msg['name'] in self.sites:raise ValueError('nombre de sitio repetido')
self.sites[msg['name']]={'value':np.array(msg['value'],copy=True),'observed':msg['observed'],
'log_prob':float(np.sum(msg['dist'].log_prob(msg['value'])))}
def log_joint(self):return sum(site['log_prob'] for site in self.sites.values())
def sample(name,dist,obs=None):
msg={'name':name,'dist':dist,'value':obs,'observed':obs is not None,'rng':None}
for handler in reversed(_stack):handler.process(msg)
if msg['value'] is None:
if msg['rng'] is None:raise RuntimeError('falta seed para un sitio aleatorio')
msg['value']=dist.sample(msg['rng'])
for handler in _stack:handler.postprocess(msg)
return msg['value']
def normal_model(n=3):
mu=sample('mu',Normal(0.,1.))
values=sample('y',Normal(np.full(n,mu),1.))
return mu,valueswith seed(9),trace() as tr:
mu,sim=normal_model()
print('simulación',mu,sim,'log conjunta',tr.log_joint())
with seed(9),condition({'y':[1.,2.,3.]}),substitute({'mu':.4}),trace() as tr:
normal_model()
print('sitios',tr.sites,'log conjunta',tr.log_joint())The same program provides the joint log density evaluated at ; the gradient in this example is calculated by hand. MH and HMC sample the posterior , known by conjugacy. The result checks this case, not a general validation of the handler.
import numpy as np
observed=np.array([1.,2.,3.])
def logjoint(w):
with condition({'y':observed}),substitute({'mu':float(w)}),trace() as tr:normal_model()
return tr.log_joint()
def grad(w):return -w+np.sum(observed-w)
def mh(steps=6000,seed=25):
rng=np.random.default_rng(seed);w=0.;out=[];lp=logjoint(w)
for _ in range(steps):
prop=w+.8*rng.normal();q=logjoint(prop)
if np.log(rng.random())<min(0.,q-lp):w=prop;lp=q
out.append(w)
return np.array(out)
def hmc(steps=6000,seed=26):
rng=np.random.default_rng(seed);w=0.;out=[]
for _ in range(steps):
p=rng.normal();H=-logjoint(w)+p*p/2;q=w;v=p+.4*grad(q)/2
for j in range(6):
q+=.4*v
if j<5:v+=.4*grad(q)
v+=.4*grad(q)/2;Hnew=-logjoint(q)+v*v/2
if np.log(rng.random())<min(0.,H-Hnew):w=q
out.append(w)
return np.array(out)a=mh();b=hmc()
print('MH media y desviación',a[1000:].mean(),a[1000:].std())
print('HMC media y desviación',b[1000:].mean(),b[1000:].std(),'exacta',1.5,.5)PSIS-LOO from scratch
The psis_numpy.py implementation fits a GPD by maximum likelihood to tail excesses, replaces extreme weights with smoothed quantiles and normalizes in logarithms. It is an educational variant: ArviZ adjustments and regularization may differ, especially with finite samples. We compare with exact LOO for conjugate normal regression, where the last point is deliberately shifted.
"""PSIS educativo: ajuste GPD por máxima verosimilitud y cola suavizada."""
import numpy as np
from scipy.special import logsumexp
from scipy.stats import genpareto
def psis(log_weights):
log_weights=np.asarray(log_weights,dtype=float)
if log_weights.ndim!=1 or len(log_weights)<50 or not np.all(np.isfinite(log_weights)):
raise ValueError('Se necesitan al menos 50 log pesos finitos')
n=len(log_weights);w=np.exp(log_weights-np.max(log_weights));order=np.argsort(w);m=min(n//5,int(3*np.sqrt(n)))
cutoff=w[order[-m-1]];excess=w[order[-m:]]-cutoff
if np.max(excess)<=0:return log_weights-logsumexp(log_weights),np.nan
k,_,scale=genpareto.fit(excess,floc=0)
p=(np.arange(m)+.5)/m;smoothed=cutoff+genpareto.ppf(p,k,loc=0,scale=scale)
w[order[-m:]]=np.minimum(smoothed,w[order[-1]])
log_smooth=np.log(np.maximum(w,np.finfo(float).tiny))
return log_smooth-logsumexp(log_smooth),float(k)
def psis_loo(log_likelihood):
log_likelihood=np.asarray(log_likelihood)
pointwise=[];ks=[]
for i in range(log_likelihood.shape[1]):
logw,k=psis(-log_likelihood[:,i]);pointwise.append(logsumexp(logw+log_likelihood[:,i]));ks.append(k)
return np.array(pointwise),np.array(ks)import numpy as np
from scipy.stats import norm
from scipy.special import logsumexp
x=np.r_[np.linspace(-1,1,14),1.1];X=np.c_[np.ones(len(x)),x]
y=np.r_[.4+.8*x[:14]+.15*np.sin(3*np.arange(14)),4.];sigma=.35
V=np.linalg.inv(np.eye(2)/4+X.T@X/sigma**2);[email protected]@y/sigma**2
rng=np.random.default_rng(2526);draws=rng.multivariate_normal(m,V,size=4000)
ll=norm.logpdf(y[None,:],[email protected],scale=sigma)
point,k=psis_loo(ll);exact=[]
for i in range(len(y)):
keep=np.arange(len(y))!=i;Vi=np.linalg.inv(np.eye(2)/4+X[keep].T@X[keep]/sigma**2);mi=Vi@X[keep].T@y[keep]/sigma**2
exact.append(norm.logpdf(y[i],loc=X[i]@mi,scale=np.sqrt(sigma**2+X[i]@Vi@X[i])))
waic=(logsumexp(ll,axis=0)-np.log(len(ll))-ll.var(axis=0,ddof=1)).sum()
print('point k',np.round(k,3),'last PSIS/exact',point[-1],exact[-1]);print('sum PSIS/exact/WAIC',point.sum(),sum(exact),waic)In the reference run the final point has , PSIS gives log predictive -22.36 and exact conjugate refitting -23.08. The discrepancy illustrates why the diagnostic is checked; it is not a general error bound.
Eight schools SBC
The generator uses the m14-l24 priors: and , with the eight historical standard errors. To keep cost low, this check samples from quadrature on a [0,30] grid, with random interpolation within each cell. It is a numerical approximation to the posterior, not validation of the HMC from m14-l24. It is contrasted with an injected error: infer with a half-normal(2) prior when data are generated with scale 5.
import numpy as np
from scipy.special import logsumexp
sigma=np.array([15,10,16,11,9,11,10,18],float)
grid=np.linspace(0,30,1501);step=grid[1]-grid[0]
def posterior_tau(y,scale=5):
d=sigma[None,:]**2+grid[:,None]**2;v=1/(.01+(1/d).sum(1));mu=v*(y[None,:]/d).sum(1)
logdet=np.log(d).sum(1)+np.log(100/v);quad=(y[None,:]**2/d).sum(1)-mu**2/v
logp=-.5*(logdet+quad+(grid/scale)**2);logp[[0,-1]]+=np.log(.5)
return np.exp(logp-logsumexp(logp))
def sbc_eight(reps=400,draws=100,seed=2528,posterior_scale=5):
rng=np.random.default_rng(seed);ranks=[]
for _ in range(reps):
mu=rng.normal(0,10);tau=abs(rng.normal(0,5));theta=rng.normal(mu,tau,size=8);y=rng.normal(theta,sigma)
p=posterior_tau(y,posterior_scale);idx=rng.choice(len(grid),size=draws,p=p)
samples=np.clip(grid[idx]+rng.uniform(-step/2,step/2,size=draws),0,30)
ranks.append(np.sum(samples<tau))
return np.bincount(np.minimum(np.array(ranks)*10//(draws+1),9),minlength=10)
print('SBC eight schools correct approximate',sbc_eight(),'wrong prior scale 2',sbc_eight(posterior_scale=2))Bridge sampling and thermodynamic integration
The estimators are implemented in logarithms. The proposal is the Laplace approximation with covariance multiplied by 1.5, so it does not exactly match the normal posterior of the first case. The Meng–Wong bridge uses draws from the proposal and posterior and solves the identity iteratively. Integration uses 31 temperatures , a random-walk MH with adaptation only in the first 1000 steps and 2000 states saved per temperature. The cost is split into cells for browser execution; accuracy depends on mixing, grid and budget.
"""MAP logístico con prior gaussiano y aproximación de Laplace."""
import numpy as np
from scipy.special import expit
def negative_log_posterior(w, X, y, alpha):
z = X @ w
p = expit(z)
value = np.logaddexp(0., z).sum() - y @ z + .5 * alpha * (w @ w)
gradient = X.T @ (p-y) + alpha*w
H = X.T @ ((p*(1-p))[:,None]*X) + alpha*np.eye(X.shape[1])
return value, gradient, H
def fit_laplace(X, y, alpha=1., tol=1e-9, max_iter=100):
X=np.asarray(X,dtype=float);y=np.asarray(y,dtype=float)
if X.ndim!=2 or y.shape!=(X.shape[0],) or X.shape[1]==0:
raise ValueError('dimensiones incompatibles')
if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)) or np.any((y!=0)&(y!=1)) or not np.isfinite(alpha) or alpha<=0 or tol<=0 or max_iter<1:
raise ValueError('datos finitos, etiquetas binarias, alpha y tolerancia positivos y al menos una iteración')
w=np.zeros(X.shape[1]); converged=False
for iteration in range(max_iter):
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:
converged=True;break
direction=np.linalg.solve(H,gradient)
rate=1.
while rate>1e-12:
candidate=w-rate*direction
if negative_log_posterior(candidate,X,y,alpha)[0]<=value-1e-4*rate*(gradient@direction):
break
rate*=.5
if rate<=1e-12:break
w=candidate
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:converged=True
cov=np.linalg.solve(H,np.eye(X.shape[1]))
return w,cov,{'converged':converged,'iterations':iteration+1,
'gradient_inf':np.linalg.norm(gradient,np.inf),'objective':value}
def predict_probit(X, mean, covariance):
X=np.asarray(X,dtype=float)
variance=np.einsum('ij,jk,ik->i',X,covariance,X)
return expit((X@mean)/np.sqrt(1+np.pi*np.maximum(variance,0)/8))
def synthetic_data(seed=2026,n_train=40,n_test=2000):
"""Datos sintéticos Bernoulli, partición de test independiente en el mismo generador."""
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);X_test,y_test=generate(n_test)
return X,y,X_test,y_test,true_wimport numpy as np
from scipy.special import expit,logsumexp
from scipy.stats import multivariate_normal
def logmean(x):return logsumexp(x)-np.log(len(x))
def bridge(logf_q,logq_q,logf_p,logq_p,initial=0.,iterations=100):
n,m=len(logf_p),len(logf_q);sp=n/(n+m);sq=m/(n+m);z=initial
for _ in range(iterations):
denq=np.logaddexp(np.log(sp)+logf_q,np.log(sq)+z+logq_q)
denp=np.logaddexp(np.log(sp)+logf_p,np.log(sq)+z+logq_p)
new=logmean(logf_q-denq)-logmean(logq_p-denp)
if abs(new-z)<1e-10:return new
z=new
return z
def rw_tempered(loglike,logprior,start,seed,beta,scale,steps=2500,burn=500):
rg=np.random.default_rng(seed);x=start.copy();L=loglike(x);P=logprior(x);out=[];ll=[];logscale=0.
for i in range(steps):
prop=x+np.exp(logscale)*([email protected](size=len(x)));newL=loglike(prop);newP=logprior(prop)
take=np.log(rg.random())<min(0.,newP-P+beta*(newL-L))
if take:x=prop;L=newL;P=newP
if i<burn:logscale+=.8*(i+20)**(-.6)*(take-.3)
if i>=burn:out.append(x.copy());ll.append(L)
return np.array(out),np.array(ll)
def integration(loglike,logprior,start,scale,seed):
betas=np.linspace(0,1,31)**2;avg=[]
for i,beta in enumerate(betas):
_,ll=rw_tempered(loglike,logprior,start,seed+i,beta,scale,steps=3000,burn=1000)
avg.append(ll.mean())
return np.trapezoid(avg,betas)
def estimate(loglike,logprior,mode,cov,seed):
rg=np.random.default_rng(seed);scale=np.linalg.cholesky(cov)*1.4
post,ll=rw_tempered(loglike,logprior,mode,seed,1.,scale,steps=5500,burn=1500)
proposal=rg.multivariate_normal(mode,cov*1.5,size=len(post));q=multivariate_normal(mean=mode,cov=cov*1.5)
logf_q=np.array([loglike(x)+logprior(x) for x in proposal]);logf_p=np.array([loglike(x)+logprior(x) for x in post])
logq_q=q.logpdf(proposal);logq_p=q.logpdf(post)
imp=logmean(logf_q-logq_q);harm=-logmean(-ll);brid=bridge(logf_q,logq_q,logf_p,logq_p,initial=imp)
return imp,harm,brid
betas=np.linspace(0,1,31)**2
def ti_chunk(loglike,logprior,start,cov,seed,first,last):
scale=np.linalg.cholesky(cov)*1.4
return [rw_tempered(loglike,logprior,start,seed+i,betas[i],scale,steps=3000,burn=1000)[1].mean() for i in range(first,last)]We begin with normal regression with two variables and analytic evidence. Data are simulated with seed 25, prior and noise deviation 0.7.
rg=np.random.default_rng(25);X=rg.normal(size=(30,2));w=np.array([.7,-.4]);sig=.7;priorvar=4.;y=X@w+sig*rg.normal(size=30);d=X.shape[1]
V=np.linalg.inv(X.T@X/sig**2+np.eye(d)/priorvar);[email protected]@y/sig**2
def ll(q):return np.sum(-.5*((y-X@q)/sig)**2-np.log(sig)-.5*np.log(2*np.pi))
def lp(q):return -.5*np.sum(q*q)/priorvar-d/2*np.log(2*np.pi*priorvar)
truth=multivariate_normal.logpdf(y,mean=np.zeros(len(y)),cov=sig**2*np.eye(len(y))+priorvar*[email protected])
print('exacta',truth,'importancia, armónica, bridge',estimate(ll,lp,mode,V,250))
vals=ti_chunk(ll,lp,mode,V,350,0,10)vals+=ti_chunk(ll,lp,mode,V,350,10,20)vals+=ti_chunk(ll,lp,mode,V,350,20,31)
print('integración termodinámica',np.trapezoid(vals,betas),'exacta',truth)Now we compare two logistic models on the same synthetic dataset from m14-l07, with an intercept and one or two covariates; both use a prior with precision 1.5. The difference in evidence is small in this run, and the discrete numerical methods and short chains do not resolve it reliably.
X,y,_,_,_=synthetic_data();alpha=1.5
def configure(dim):
A=X[:,:dim];mode,cov,_=fit_laplace(A,y,alpha)
def ll(q):
z=A@q;return float([email protected](0,z).sum())
def lp(q):return -.5*alpha*np.sum(q*q)+dim/2*np.log(alpha/(2*np.pi))
return mode,cov,ll,lp
mode,cov,ll,lp=configure(2)
print('dos coeficientes: importancia, armónica, bridge',estimate(ll,lp,mode,cov,252))
vals=ti_chunk(ll,lp,mode,cov,352,0,10)vals+=ti_chunk(ll,lp,mode,cov,352,10,20)vals+=ti_chunk(ll,lp,mode,cov,352,20,31)
print('dos coeficientes: integración termodinámica',np.trapezoid(vals,betas))mode,cov,ll,lp=configure(3)
print('tres coeficientes: importancia, armónica, bridge',estimate(ll,lp,mode,cov,253))
vals=ti_chunk(ll,lp,mode,cov,353,0,10)vals+=ti_chunk(ll,lp,mode,cov,353,10,20)vals+=ti_chunk(ll,lp,mode,cov,353,20,31)
print('tres coeficientes: integración termodinámica',np.trapezoid(vals,betas))The thermodynamic approximation for the normal model was -40.34 against the exact -40.25 in the reference run. The harmonic mean was clearly different in that sample. Do not take any of these figures as a guarantee: repeat chains, improve the grid and measure uncertainty before using a Bayes factor.
Hierarchical counts: checking and expansion
We generate 80 synthetic counts in eight groups from a negative binomial with overdispersion known in the simulation. The first model uses Poisson and the second incorporates overdispersion; both have hierarchical intercepts. For each, prior and posterior predictives are generated, two short NUTS chains are fit, and diagnostics, PSIS-LOO and WAIC are shown. Stacking combines approximate predictives, not model probabilities.
With 600 posterior draws ArviZ uses a threshold of . In the checked run one observation in the negative binomial model exceeds it: the code refits without that datum and compares its log predictive with PSIS. Stacking weights remain those calculated with the original PSIS and should be interpreted with that caveat. The R-hat of the Poisson intercept is approximately 1.013 and only that parameter is shown: more chains, draws and diagnostics are needed before concluding. The counts are simulated; there is no external evaluation.
import numpy as np,pymc as pm,arviz as az
from scipy.special import logsumexp
from scipy.stats import nbinom
rng=np.random.default_rng(2525);G=8;n=80;group=np.repeat(np.arange(G),n//G)
x=rng.normal(size=n);intercept=rng.normal(1,.35,size=G);mu=np.exp(intercept[group]+.35*x)
y=rng.negative_binomial(2,2/(2+mu))
print('datos sintéticos: n',n,'grupos',G,'media',y.mean(),'varianza',y.var(),'proporción cero',np.mean(y==0))
def fit_model(kind,seed):
with pm.Model() as model:
a=pm.Normal('a',0,1.5);b=pm.Normal('b',0,1);scale=pm.HalfNormal('scale',.7)
z=pm.Normal('z',0,1,shape=G);rate=pm.math.exp(a+scale*z[group]+b*x)
if kind=='poisson':pm.Poisson('obs',mu=rate,observed=y)
else:
alpha=pm.Exponential('alpha',1)
pm.NegativeBinomial('obs',mu=rate,alpha=alpha,observed=y)
prior=pm.sample_prior_predictive(draws=200,random_seed=seed)
fit=pm.sample(draws=300,tune=300,chains=2,cores=1,random_seed=seed,progressbar=False,target_accept=.9,idata_kwargs={'log_likelihood':True},compute_convergence_checks=False)
pm.sample_posterior_predictive(fit,random_seed=seed,progressbar=False,extend_inferencedata=True)
a0=prior['prior_predictive']['obs'].values.reshape(-1,n)
ap=fit['posterior_predictive']['obs'].values.reshape(-1,n)
print(kind,'prior mean variance',a0.mean(),a0.var(axis=1).mean(),'posterior mean variance',ap.mean(),ap.var(axis=1).mean(),'observed variance',y.var())
print(kind,'divergences',int(fit['sample_stats']['diverging'].values.sum()),'Rhat a',az.rhat(fit,var_names=['a'])['a'].values)
loo=az.loo(fit,pointwise=True);print(kind,'LOO',loo)
loglik=fit['log_likelihood']['obs'].values.reshape(-1,n)
lppd=np.sum(logsumexp(loglik,axis=0)-np.log(len(loglik)));pwaic=np.var(loglik,axis=0,ddof=1).sum()
print(kind,'ELPD WAIC',lppd-pwaic,'p_WAIC',pwaic)
return fit,loo
pois,loo_p=fit_model('poisson',25);nb,loo_n=fit_model('nb',26)
print('stacking approximate',az.compare({'Poisson':pois,'NegBin':nb},method='stacking',round_to=2))
threshold=min(1-1/np.log10(600),.7);bad=np.flatnonzero(np.asarray(loo_n.pareto_k)>threshold)
for idx in bad:
mask=np.arange(n)!=idx
with pm.Model() as model:
a=pm.Normal('a',0,1.5);b=pm.Normal('b',0,1);scale=pm.HalfNormal('scale',.7)
z=pm.Normal('z',0,1,shape=G);alpha=pm.Exponential('alpha',1)
rate=pm.math.exp(a+scale*z[group[mask]]+b*x[mask])
pm.NegativeBinomial('obs',mu=rate,alpha=alpha,observed=y[mask])
refit=pm.sample(draws=300,tune=300,chains=2,cores=1,random_seed=99+int(idx),progressbar=False,target_accept=.9,compute_convergence_checks=False)
post=refit['posterior'];aa=post['a'].values;bb=post['b'].values;ss=post['scale'].values
zz=post['z'].values[...,group[idx]];al=post['alpha'].values;pred=np.exp(aa+ss*zz+bb*x[idx])
lpd=nbinom.logpmf(y[idx],n=al,p=al/(al+pred));exact=logsumexp(lpd)-np.log(lpd.size)
print('exact refit index',int(idx),'k',float(np.asarray(loo_n.pareto_k)[idx]),'PSIS lpd',float(np.asarray(loo_n.elpd_i)[idx]),'refit lpd',float(exact),'divergences',int(refit['sample_stats']['diverging'].values.sum()))npm run lab and open the connection link.Exercises
Step 1 of 2. What is the distribution of conditional on y?
Step 1 of 3. Which integral controls the second moment of under the posterior?
Trace and Condition(values) for the tests’ sample. Each handler is added to the global STACK list on entry and removed on exit; Condition.process(msg) fixes an unobserved value if its name appears in values, and Trace.postprocess(msg) stores the value, observed flag and log density. Both must have process and postprocess methods.class Trace:
pass
class Condition:
passsbc(simulate, infer, reps, draws, rng). simulate(rng) returns (theta, y) and infer(y, draws, rng) returns scalar posterior draws. Return an array of reps ranks: the number of draws strictly less than theta. The tests use continuous distributions without ties.def sbc(simulate, infer, reps, draws, rng):
passSummary
- A PPL records sites and effects; conditioning data and performing inference are distinct operations.
- SBC checks the algorithm under the chosen generator; PSIS requires checking weight tails.
- LOO, stacking and evidence answer different questions; bridge and tempered methods require checking numerical error.
Main sources: Gelman and colleagues, Bayesian workflow; Vehtari and colleagues, PSIS; Talts and colleagues, SBC; Gronau and colleagues, bridge sampling; Yao and colleagues, stacking.