MCMC II: Gibbs sampling, data augmentation and slice sampling
Sampling each variable conditional on the rest is often straightforward thanks to graph structure and conjugacy. We study Gibbs and its blocked and collapsed versions, data augmentation with auxiliary variables (Albert-Chib probit and Pólya-Gamma), slice sampling and Dirichlet-process mixtures with the Chinese restaurant process.
After this lesson you can
- Derive a model's full conditionals from its Markov blanket.
- Implement simple, blocked and collapsed Gibbs and compare mixing.
- Design a data augmentation scheme for probit regression.
- Implement slice sampling with expansion and shrinkage.
- Sample a Dirichlet-process mixture with the Chinese restaurant process.
Before you start
- 14Metropolis-Hastings algorithmDetailed balanceMCMC effective sample sizeMarkov blanketIsing modelForward filtering backward samplingLatent variable modelLatent Dirichlet allocationNon-identifiability and label switchingMultivariate conjugate priors (Normal-gamma, Normal-Wishart)
- 05Conjugate priorsRao-Blackwell theorem
- 04Beta and Dirichlet distributions
- 12Gaussian mixture model
Conditioning to sample
In Gibbs sampling a coordinate is replaced with a sample from its full conditional . This is a Metropolis-Hastings step whose proposal is that conditional and acceptance is one. If all coordinates are updated in systematic order, each kernel preserves the posterior and so does their composition, although the complete composition need not be reversible. A random scan chooses which coordinate to update. Stationarity does not guarantee fast mixing.
In a graph, only factors containing enter its conditional: the rest cancel on normalization. This set corresponds to the Markov blanket. For the lesson 3 Ising model with spins , coupling , observed field and neighbors ,
The next image reuses the drawing, corruption and seed from m14-l03, with open boundaries and flip noise 0.2. ICM chooses the conditional mode; Gibbs accumulates states and estimates a probability per pixel. The first is a local point configuration, the second an approximate mean, not necessarily a binary state of the model. Both depend on the model and runtime.
Blocks and collapsing
For a standardized bivariate Gaussian with correlation , the conditionals are and . As approaches one, individual updates move slowly along the valley. A joint block draws from its joint conditional; in this particular example the block is the entire distribution and samples are independent. In a larger model a block does not guarantee global independence.
Blocked or collapsed Gibbs exploits structure: FFBS can sample an HMM latent trajectory as a block; collapsing analytically integrates variables before sampling others. An estimator’s conditional expectation has no greater variance by total variance, but that per-sample statement does not guarantee every collapsed implementation has higher ESS per second: cost and autocorrelation change.
In LDA, document proportions and topics with Dirichlet priors are integrated out. For a word token in document , after removing that token,
Counting the token twice biases the conditional. Topics are interchangeable: when comparing runs align labels or use invariant statistics. The lab uses part of the actual corpus generated in m14-l09, with topics known only because it is synthetic.
Data augmentation and slice sampling
Data augmentation introduces auxiliary variables that marginally preserve the desired model and make conditionals simple. In probit, and . Conditional on , is a normal truncated above or below zero. With prior ,
This Albert and Chib scheme does not automatically turn logistic regression into probit: these are different links. For logistic regression the Pólya-Gamma representation introduces other auxiliary variables and leaves a Gaussian conditional for coefficients.
Slice sampling introduces height uniformly between zero and the unnormalized density at the current point. Conditional on , the variable is uniformly distributed in the region where density exceeds that height. A practical implementation expands an interval and proposes within it; on rejection it shrinks the proposal side without excluding the current point. For disconnected sets and limited expansion rules, method conditions must be respected: not every interval heuristic preserves the distribution.
Chinese restaurant and mixtures
A Dirichlet process and its mixtures permits a number of occupied groups not fixed in advance. In the Chinese restaurant, the next customer sits at table with probability , or opens a table with probability . After customers, , asymptotically for fixed . In a posterior mixture those probabilities are multiplied by data predictive densities: the restaurant describes the prior over partitions, not the complete posterior result.
Labs
Gaussian mixture: simple and collapsed
This synthetic example has 60 data points, three Gaussian components of known standard deviation 0.45, mean prior and Dirichlet(1,1,1) weights. The simple sampler alternates weights, means and assignments; the collapsed one integrates weights and means to update each label. Compare invariant statistic , not means with unaligned labels. There are only 250 sweeps, 50 discarded, and runtime includes warmup. ESS per second depends on machine, statistic and length; it does not establish universal superiority.
import time
import numpy as np
from scipy.special import logsumexp
def mixture_data():
rng=np.random.default_rng(22);z=np.repeat(np.arange(3),20);rng.shuffle(z)
return np.array([-2.,0.,2.])[z]+.45*rng.normal(size=len(z))
def categorical(logw,rng):
p=np.exp(logw-logsumexp(logw));return rng.choice(len(p),p=p)
def uncollapsed(x,steps=250,seed=1):
rng=np.random.default_rng(seed);n=len(x);K=3;z=rng.integers(K,size=n);out=[];states=[]
for t in range(steps):
counts=np.bincount(z,minlength=K);pi=rng.dirichlet(1+counts);mu=np.empty(K)
for k in range(K):
v=1/(1/4+counts[k]/.45**2);m=v*x[z==k].sum()/.45**2;mu[k]=rng.normal(m,np.sqrt(v))
for i in range(n):
z[i]=categorical(np.log(pi)-.5*((x[i]-mu)/.45)**2,rng)
counts=np.bincount(z,minlength=K);out.append(np.sum(counts**2)/n**2);states.append(mu.copy())
return np.array(out),np.array(states)
def collapsed(x,steps=250,seed=1):
rng=np.random.default_rng(seed);n=len(x);K=3;z=rng.integers(K,size=n);out=[];states=[]
for t in range(steps):
for i in range(n):
z[i]=-1;logw=np.empty(K)
for k in range(K):
members=x[z==k];v=1/(1/4+len(members)/.45**2);m=v*members.sum()/.45**2;pv=.45**2+v
logw[k]=np.log(len(members)+1)-.5*np.log(pv)-.5*(x[i]-m)**2/pv
z[i]=categorical(logw,rng)
counts=np.bincount(z,minlength=K);out.append(np.sum(counts**2)/n**2)
states.append([x[z==k].mean() if counts[k] else np.nan for k in range(K)])
return np.array(out),np.array(states)
def ess(x):
x=x-x.mean();n=len(x);f=np.fft.rfft(x,n=1<<(2*n-1).bit_length());a=np.fft.irfft(f*np.conjugate(f),n=1<<(2*n-1).bit_length())[:n];r=a/a[0];pairs=[]
for i in range(0,n-1,2):
p=r[i]+r[i+1]
if p<0:break
pairs.append(min(p,pairs[-1]) if pairs else p)
return n/max(1/np.log10(n),-1+2*sum(pairs))x=mixture_data()
t=time.perf_counter();trace,means=uncollapsed(x);elapsed=time.perf_counter()-t
e=ess(trace[50:])
print('simple: ESS',e,'segundos',elapsed,'ESS/s',e/elapsed,'medias sin alinear',np.round(means[-1],2))t=time.perf_counter();trace,means=collapsed(x);elapsed=time.perf_counter()-t
e=ess(trace[50:])
print('colapsado: ESS',e,'segundos',elapsed,'ESS/s',e/elapsed,'medias sin alinear',np.round(means[-1],2))Collapsed Gibbs for LDA
This cell reproduces the complete m14-l09 generator, also available for download. To keep execution short take the first 30 documents of 60 words from the full corpus, without altering words. Initial labels use seed 17; each step removes the token before calculating its conditional.
"""Corpus LDA sintético reproducible para m14-l09, l18 y l22."""
import numpy as np
def synthetic_lda(seed=2026, n_docs=250, n_words=60, n_topics=3,
n_vocab=12, alpha=.3, beta=.12):
"""Devuelve (conteos, theta, temas, asignaciones, palabras).
Temas: (K,V); theta: (D,K); asignaciones y palabras: (D,N).
Los temas y proporciones se generan de priors Dirichlet simétricos,
cada palabra tiene su propio tema, y las filas de conteos suman N.
"""
if min(n_docs,n_words,n_topics,n_vocab)<1 or alpha<=0 or beta<=0:
raise ValueError('tamaños y concentraciones deben ser positivos')
rng=np.random.default_rng(seed)
topics=rng.dirichlet(np.full(n_vocab,beta),size=n_topics)
theta=rng.dirichlet(np.full(n_topics,alpha),size=n_docs)
assignments=np.empty((n_docs,n_words),dtype=int)
words=np.empty_like(assignments)
counts=np.zeros((n_docs,n_vocab),dtype=int)
for d in range(n_docs):
assignments[d]=rng.choice(n_topics,size=n_words,p=theta[d])
for n,z in enumerate(assignments[d]):
words[d,n]=rng.choice(n_vocab,p=topics[z])
counts[d]=np.bincount(words[d],minlength=n_vocab)
return counts,theta,topics,assignments,wordsimport time
import numpy as np
from scipy.optimize import linear_sum_assignment
counts,theta,truth,assignments,words=synthetic_lda()
words=words[:30];D,N=words.shape;K=3;V=12;alpha=.3;beta=.12
def lda_init(seed=17):
rng=np.random.default_rng(seed);z=rng.integers(K,size=(D,N));ndk=np.zeros((D,K),int);nkv=np.zeros((K,V),int);nk=np.zeros(K,int)
for d in range(D):
for i in range(N):
k=z[d,i];v=words[d,i];ndk[d,k]+=1;nkv[k,v]+=1;nk[k]+=1
return rng,z,ndk,nkv,nk
def lda_sweep(state):
rng,z,ndk,nkv,nk=state
for d in range(D):
for i in range(N):
k=z[d,i];v=words[d,i];ndk[d,k]-=1;nkv[k,v]-=1;nk[k]-=1
p=(ndk[d]+alpha)*(nkv[:,v]+beta)/(nk+V*beta);p/=p.sum()
k=rng.choice(K,p=p);z[d,i]=k;ndk[d,k]+=1;nkv[k,v]+=1;nk[k]+=1
assert ndk.sum()==nkv.sum()==nk.sum()==D*N
def compare_topics(state):
_,_,ndk,nkv,nk=state;topics=(nkv+beta)/(nk[:,None]+V*beta)
cost=np.abs(truth[:,None,:]-topics[None,:,:]).sum(axis=2);i,j=linear_sum_assignment(cost)
return cost[i,j]
state=lda_init()
print('documentos, palabras por documento',words.shape,'total',state[4].sum())for _ in range(30):lda_sweep(state)
print('tokens conservados',state[4].sum(),'distancias L1 alineadas',compare_topics(state))Distances compare topics estimated from one state with generating topics via Hungarian assignment. These check one simulation, not convergence; uncertainty requires storing and aligning multiple samples.
Augmented probit and slice for logistic regression
The first cell reproduces the m14-l07 module, also downloadable. Use its same data and prior; probit and logistic fits are different models. Slice and MH are compared on the same logistic posterior. These short chains check the workflow and must be repeated with diagnostics and multiple starts before drawing conclusions.
"""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
from scipy.stats import truncnorm
def metropolis(logp,start,seed,warmup=1000,draws=2000,scale=.5):
rg=np.random.default_rng(seed);x=np.array(start,dtype=float);lp=logp(x);logs=np.log(scale);samples=[];accepted=0
for t in range(warmup+draws):
candidate=x+np.exp(logs)*rg.normal(size=x.size);new=logp(candidate)
take=np.log(rg.random())<min(0.,new-lp)
if take:x=candidate;lp=new
if t<warmup:logs+=.8*(t+20)**(-.6)*(take-.234)
else:samples.append(x.copy());accepted+=take
return np.array(samples),accepted/draws,np.exp(logs)
def probit_gibbs(X,y,alpha=1.5,steps=2000,seed=6):
rng=np.random.default_rng(seed);n,d=X.shape;V=np.linalg.inv(alpha*np.eye(d)+X.T@X);L=np.linalg.cholesky(V);w=np.zeros(d);out=np.empty((steps,d))
for i in range(steps):
mu=X@w;a=np.where(y==1,-mu,-np.inf);b=np.where(y==1,np.inf,-mu)
z=truncnorm.rvs(a,b,loc=mu,scale=1,random_state=rng)
[email protected]@[email protected](size=d);out[i]=w
return out
def slice_update(logp,w,j,rng,width=1.):
h=logp(w)+np.log(rng.random());old=w[j];L=old-width*rng.random();R=L+width
def at(x):z=w.copy();z[j]=x;return logp(z)
for _ in range(1000):
if at(L)<=h:break
L-=width
else:raise RuntimeError('No se encontró el límite izquierdo')
for _ in range(1000):
if at(R)<=h:break
R+=width
else:raise RuntimeError('No se encontró el límite derecho')
for _ in range(1000):
v=rng.uniform(L,R)
if at(v)>=h:w=w.copy();w[j]=v;return w
if v<old:L=v
else:R=v
raise RuntimeError('La contracción no aceptó')
def slice_chain(logp,start,steps=3000,seed=7):
rng=np.random.default_rng(seed);w=np.array(start,dtype=float);out=[]
for _ in range(steps):
for j in range(len(w)):w=slice_update(logp,w,j,rng)
out.append(w.copy())
return np.array(out)
X,y,_,_,_=synthetic_data();alpha=1.5
def logp(w):
a=X@w;return float([email protected](0,a).sum()-.5*alpha*(w@w))
mode,cov,_=fit_laplace(X,y,alpha)probit=probit_gibbs(X,y)
print('media probit tras 500 de calentamiento',probit[500:].mean(0))sl=slice_chain(logp,mode);mh,acc,scale=metropolis(logp,mode,101,warmup=1000,draws=2000)
print('media slice',sl[1000:].mean(0),'media MH',mh.mean(0),'aceptación MH',acc)Exercises
Step 1 of 2. Which reverse proposal appears?
Step 1 of 2. How does total variance decompose variance?
probit_gibbs(X, y, alpha, steps, seed). Use a normal prior of precision alpha, normal latents truncated according to y and return an array (steps, d) of coefficients. Initialize at zero and use numpy.random.default_rng(seed).def probit_gibbs(X, y, alpha, steps, seed):
passSummary
- Full conditionals depend on Markov blanket factors and should be checked against known cases.
- Blocking or integrating variables can improve exploration, but cost and autocorrelation determine final efficiency.
- The Chinese restaurant describes a prior over partitions; data also enter a posterior mixture.
Main sources: Albert and Chib; Polson, Scott and Windle; Neal, slice sampling; Neal, Dirichlet-process mixtures.