Module contents
Lesson 22 of 27Core 110 min

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

Conditioning to sample

In Gibbs sampling a coordinate is replaced with a sample from its full conditional p(xi∣x−i,y)p(x_i\mid\vb x_{-i},\vb y). 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 xix_i enter its conditional: the rest cancel on normalization. This set corresponds to the Markov blanket. For the lesson 3 Ising model with spins ±1\pm1, coupling JJ, observed field ηyi\eta y_i and neighbors ∂i\partial i,

P(xi=1∣x−i,y)=σ ⁣(2J∑j∈∂ixj+2ηyi).P(x_i=1\mid\vb x_{-i},\vb y)=\sigma\!\left(2J\sum_{j\in\partial i}x_j+2\eta y_i\right).

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.

InteractiveGibbs cleans an image

Observed

ICM point

Posterior mean

In the posterior mean, color indicates estimated probability of spin +1. The true drawing is known only in this simulation.
0.7
50
ICM accuracy67 %
Thresholded mean accuracy72 %
Adjust J and the number of samples accumulated after 50 initial sweeps. Mean color represents the proportion of +1 spins; drawing truth is known only in this simulation.

Blocks and collapsing

For a standardized bivariate Gaussian with correlation ρ\rho, the conditionals are x∣y∼N(ρy,1−ρ2)x\mid y\sim\Normal(\rho y,1-\rho^2) and y∣x∼N(ρx,1−ρ2)y\mid x\sim\Normal(\rho x,1-\rho^2). As ∣ρ∣|\rho| approaches one, individual updates move slowly along the valley. A joint block draws (x,y)(x,y) 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.

InteractiveGibbs zigzag
Trace of the first coordinate
0.90
Update
Approximate ESS for x182
Compare coordinate updates and a joint block. ESS for x is a truncated estimate and depends on this finite run.

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 vv in document dd, after removing that token,

P(zdi=k∣z−di,w)∝(ndk−di+α)nkv−di+ηnk−di+Vη.P(z_{di}=k\mid\vb z_{-di},\vb w)\propto (n_{dk}^{-di}+\alpha)\frac{n_{kv}^{-di}+\eta}{n_k^{-di}+V\eta}.

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, zi∼N(xi⊤w,1)z_i\sim\Normal(\vb x_i\T\vb w,1) and yi=1[zi>0]y_i=\ind[z_i>0]. Conditional on yiy_i, ziz_i is a normal truncated above or below zero. With prior w∼N(0,α−1I)\vb w\sim\Normal(\vb0,\alpha\inv\mat I),

V=(X⊤X+αI)−1,w∣z∼N(VX⊤z,V).\mat V=(\mat X\T\mat X+\alpha\mat I)\inv,\qquad \vb w\mid\vb z\sim\Normal(\mat V\mat X\T\vb z,\mat V).

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 uu uniformly between zero and the unnormalized density at the current point. Conditional on uu, 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.

InteractiveSlice sampling step by step
-2.0
Step1 / 5
ActionHeight and first interval
Height0.306
Advance through height, expansion, rejection and shrinkage until acceptance. The initial point is magenta and a proposal appears in green at the height.

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 kk with probability nk/(n+α)n_k/(n+\alpha), or opens a table with probability α/(n+α)\alpha/(n+\alpha). After nn customers, EKn=∑i=1nα/(α+i−1)\E K_n=\sum_{i=1}^n\alpha/(\alpha+i-1), asymptotically αlog⁡n+O(1)\alpha\log n+O(1) for fixed α\alpha. In a posterior mixture those probabilities are multiplied by data predictive densities: the restaurant describes the prior over partitions, not the complete posterior result.

InteractiveThe Chinese restaurant
1
46 people
2
3 people
3
1 people
View
1.0
50
Observed tables3
Expected tables4.50
Compare tables under the prior with collapsed Gibbs for a synthetic 2D Gaussian mixture. Colors are interchangeable labels and repeat if there are more than seven groups.

Labs

Gaussian mixture: simple and collapsed

This synthetic example has 60 data points, three Gaussian components of known standard deviation 0.45, mean prior N(0,4)\Normal(0,4) 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 ∑knk2/n2\sum_k n_k^2/n^2, 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.

InteractiveLabels in two chains
  • Component 1
  • Component 2
  • Component 3
Chain
Representation
Sweeps per chain250
Curves come from two actual runs of simple Gibbs with seeds 1 and 2. Their label orders differ; these short chains did not exhibit order changes within either trajectory. Sorting means is a simple way to align them in this one-dimensional example.
[ ]Two mixture samplersBrowser
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))
[ ]Simple GibbsBrowser
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))
[ ]Collapsed GibbsBrowser
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 from m14-l09Browser
"""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,words
[ ]Counts and collapsed sweepBrowser
import 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())
[ ]Thirty LDA sweepsBrowser
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.

[ ]Logistic data from m14-l07Browser
"""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_w
[ ]Probit augmentation and sliceBrowser
import 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 GibbsBrowser
probit=probit_gibbs(X,y)
print('media probit tras 500 de calentamiento',probit[500:].mean(0))
[ ]Slice and Metropolis for logistic regressionBrowser
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

NumericExpected tables
In a Chinese restaurant with α=2\alpha=2 and 100 customers, what is the expected number of tables?
QuizGibbs and correlation
Where can coordinate Gibbs mix poorly and what reasonable remedy would you try?
ProofGibbs as MH
Prove: A coordinate Gibbs update has acceptance one as a Metropolis-Hastings step.
0
Fix other coordinates and propose xi′∼p(xi′∣x−i)x_i'\sim p(x_i'\mid\vb x_{-i}). Assume positive densities in the states considered.

Step 1 of 2. Which reverse proposal appears?

ProofConditioning reduces variance
Prove: An estimator's conditional expectation has no greater variance than the original estimator.
0
Let TT be square integrable and SS the variable retained after integrating an auxiliary variable.

Step 1 of 2. How does total variance decompose variance?

CodeGibbs for probit
Implement 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):
  pass
Shift+Enter to run

Summary

Key idea
Gibbs and data augmentation replace a difficult joint distribution with manageable conditionals; blocks, collapsing and slice sampling change how the posterior is traversed.
  • 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.