Module contents
Lesson 3 of 27Core 100 min

Markov random fields and factor graphs

Undirected models represent symmetric interactions with clique potentials. Prove the relationship between Markov properties and factorization (Hammersley-Clifford), introduce the partition function as a major computational obstacle, unify the representations with factor graphs, and learn an Ising model using pseudolikelihood.

After this lesson you can

  • Write a Gibbs distribution from clique potentials and read its independences from the undirected graph.
  • State Hammersley-Clifford and prove the direction from factorization to the Markov property.
  • Convert a Bayesian network to an MRF by moralization and both to factor graphs.
  • Compute the partition function of a small Ising model by brute force and explain its exponential scaling.
  • Fit MRF parameters by pseudolikelihood and compare with exact maximum likelihood.

Before you start

Interactions without arrows

A pixel in an image tends to resemble its neighbors. In a magnetic material, nearby spins may favor the same orientation. Neither example requires choosing a temporal direction between neighbors. A Bayesian network can represent a joint distribution through directed conditionals; here we build the joint with pieces describing symmetric compatibilities.

InteractiveA lattice of spins

Blue: +1; red: −1. This finite lattice does not demonstrate an infinite phase transition.

2.4
1.0
0.0
Magnetization0.014
Neighbor sum-2
P(spin + | neighbors)0.159
Sweeps0
Run the dynamics and compare temperatures, couplings and fields. Select a spin and inspect its conditional calculated from its four neighbors.

The figure is an explicit simulation on a periodic 12×1212\times12 lattice, not an experiment on a material. Each sweep proposes 144 local updates at positions chosen with replacement. A finite configuration can remain trapped in a domain for many sweeps; an image at one instant is not an independent sample or proof of a phase transition.

Potentials, energy and separation

A Markov random field (MRF) on an undirected graph G=(V,E)G=(V,E) is a distribution satisfying a Markov property relative to that graph. In a finite space, one construction chooses nonnegative potentials ψC\psi_C on cliques CC and normalizes:

p(x)=1Z∏CψC(xC)=exp⁡[−E(x)]Z,Z=∑xexp⁡[−E(x)],p(\vb{x})=\frac{1}{Z}\prod_{C}\psi_C(\vb{x}_C) =\frac{\exp[-E(\vb{x})]}{Z},\qquad Z=\sum_{\vb{x}}\exp[-E(\vb{x})],

where E=−∑Clog⁡ψCE=-\sum_C\log\psi_C when all potentials are positive. A clique is a set whose nodes are pairwise adjacent. The sum ZZ must be positive and finite. A potential is a compatibility function: it need not sum to one and generally is not a marginal.

If a set SS separates AA from BB in the undirected graph, the global property states XA⊥ ⁣ ⁣ ⁣⊥XB∣XSX_A\indep X_B\given X_S. The local property says a node is independent of other non-neighbors given its neighbors; the pairwise property says two nonadjacent nodes are independent given all others. Both follow from the global property with appropriate separators.

In an undirected chain A−C−BA-C-B, CC separates the endpoints. To see the mechanism without a theorem, write p(a,b,c)∝ψAC(a,c)ψCB(c,b)p(a,b,c)\propto\psi_{AC}(a,c)\psi_{CB}(c,b). Fixing cc, the first factor depends only on aa and the second only on bb. The sum of all weights over a,ba,b is the product of the two individual sums, so the conditional factorizes. Neither potential needs to be normalized.

Potentials are not unique. Multiplying any potential by a positive constant multiplies ZZ by the same constant and leaves pp unchanged. A factor depending on one variable can also move between potentials containing it. Thus do not assign autonomous probabilistic meaning to each number in a potential table without fixing a convention.

Proof

Remove SS and group connected components containing AA, those containing BB and the rest. No clique can contain nodes from two distinct components of G∖SG\setminus S: their connecting edge would join the components. With S=sS=s fixed, the product of potentials separates into one factor per component and one depending only on ss. Summing variables other than A,B,SA,B,S also separates by component. The conditional normalization constant factorizes into the product of the sums on each side, giving p(a,b∣s)=p(a∣s)p(b∣s)p(a,b\given s)=p(a\given s)p(b\given s). The proof permits zero potentials if the evidence has positive mass.

∎

The Hammersley-Clifford theorem supplies the other direction: for finite discrete variables with strictly positive mass, the local Markov property is equivalent to factorization into positive clique potentials. Under positivity, pairwise, local and global properties are equivalent. Without positivity, the converse can fail: the logarithm of zero mass is unavailable and the constructive argument cannot simply be applied. Positivity is unnecessary for the direction proved above.

The distinction matters when a model imposes hard constraints. A zero potential can forbid states and the resulting distribution can still factorize perfectly: the proof remains valid. What no longer follows from the local property alone is that such a factorization always exists. The theorem’s assumption concerns every joint configuration, not just those observed in a finite sample.

What changing languages loses

To moralize a DAG, connect every pair of parents of a child by an undirected edge and remove orientations. Moralization produces an undirected graph whose factorization includes each original family: every set consisting of a node and its parents is now a clique. Preserving the joint does not preserve every independence the DAG could express.

InteractiveMarry the parents
ABC

In DAG A → C ← B the collider blocks the marginal path. The new A-B edge means the moral graph no longer separates it; the original joint distribution stays the same.

DAG
BeforeA ⟂ B marginally
AfterA ⟂ B
Advance from A → C ← B to its moral graph. The parents' marginal independence is visible in the DAG, but the triangle does not guarantee it.

In A→C←BA\to C\leftarrow B, the parents are d-separated without evidence but connected when CC is observed. After moralization edge A−BA-B prevents the undirected graph from guaranteeing their marginal independence. This does not change the original distribution’s probabilities; it changes what the graph guarantees. In larger graphs other separations may be lost due to added edges. Conversely, a four-node undirected cycle permits opposite-node separations conditioned on the other two; no DAG on exactly those four edges without adding relations expresses that pattern without introducing a collider or an additional connection.

To understand the cycle difficulty, orient its four edges without creating a collider. Each node would have at most one incoming arrow; with four arrows and four nodes, each would have exactly one. That orientation is necessarily a directed cycle and not a DAG. Breaking it creates an unshielded collider whose parents lack an edge: the directed structure acquires a different constraint. A chord avoids the problem but also eliminates one separation of the original cycle.

A factor graph is bipartite: it has a circular node per variable and a factor node per function, connected to the variables it uses. Their product recovers the unnormalized function. Replacing each factor with edges between all its variables produces the associated undirected graph, but forgets how the factors were grouped.

The representation and message-passing algorithm are developed by Kschischang, Frey and Loeliger; we return to messages in the next lesson.

InteractiveThe triangle does not tell the whole story
X₁X₂X₃

Circles are variables; squares are factors. The dimensions refer to general positive families, not the symmetric two-slider example.

Factors
0.4
0.8
General-family dimension6
E[X₁X₂X₃]0.000
P(+,+,+)0.311
Switch between three pairwise factors and one three-way factor. Both yield the same triangular graph, but the latter allows a three-variable interaction.

For three positive binary variables, an arbitrary joint has seven degrees of freedom. A log-linear model with individual and pair terms has six: three fields and three pair interactions, excluding the normalization constant. Adding a three-way term provides the seventh. The figure uses symmetric subfamily exp⁡[J(x1x2+x2x3+x1x3)+Kx1x2x3]\exp[J(x_1x_2+x_2x_3+x_1x_3)+Kx_1x_2x_3], with K=0K=0 in the pairwise case. The displayed value is calculated by enumerating its eight states.

This is more than different names. With J=0J=0 and K≠0K\ne0, flipping all three spins changes the three-way term’s sign. Yet all individual and pair marginals are uniform: summing over the remaining variable encounters weights exp⁡(K)\exp(K) and exp⁡(−K)\exp(-K) once each. Pairwise marginals miss the joint interaction; average E[X1X2X3]=tanh⁡KE[X_1X_2X_3]=\tanh K detects it. A general pairwise model cannot simultaneously reproduce that third-order log-linear term and preserve all probabilities.

Ising and Potts

The Ising model assigns spins xi∈{−1,+1}x_i\in\{-1,+1\} and defines

p(x)=1Z(J,h,T)exp⁡ ⁣[JT∑(i,j)∈Exixj+hT∑ixi],T>0.p(\vb{x})=\frac{1}{Z(J,h,T)} \exp\!\left[\frac{J}{T}\sum_{(i,j)\in E}x_ix_j+\frac{h}{T}\sum_i x_i\right], \qquad T>0.

With J>0J>0 and zero field, aligned neighbors are favored. With all other spins fixed, only factors containing xix_i remain. The mass ratio of xi=+1x_i=+1 to xi=−1x_i=-1 gives

p(xi=+1∣x−i)=σ ⁣(2T(h+J∑j∈N(i)xj)).p(x_i=+1\given\vb{x}_{-i}) =\sigmoid\!\left(\frac{2}{T}\left(h+J\sum_{j\in N(i)}x_j\right)\right).

The conditional depends only on neighbors: they form the local blanket. In the figure boundaries are periodic, so every node has four neighbors. An image with open boundaries has only two at its corners. A Gibbs update draws from this conditional and leaves the target distribution invariant; a short sequence can still be far from equilibrium.

Potts extends the states to KK labels and favors equality with terms such as J1[xi=xj]J\ind[x_i=x_j]. On an infinite square lattice with no field and J>0J>0, Ising has critical temperature Tc=2J/log⁡(1+2)T_c=2J/\log(1+\sqrt2) in these units. That formula belongs to the infinite limit. On a finite lattice the partition function is a finite sum of exponentials and is smooth for T>0T>0; one observes regime changes and domains, not an exact singularity. Near a transition, spatial correlation and slow mixing complicate inference using local updates.

Onsager’s solution establishes critical condition sinh⁡(2J/Tc)2=1\sinh(2J/T_c)^2=1 in the isotropic case with Boltzmann’s constant set to one. Solving gives the expression above.

A noisy image

Suppose each original pixel xix_i flips independently with probability ε<1/2\eps<1/2, giving yiy_i. Combine the Ising prior with that likelihood. Ignoring constants independent of x\vb{x},

log⁡p(x∣y)=J∑(i,j)xixj+η∑ixiyi+constante,η=12log⁡1−εε.\log p(\vb{x}\given\vb{y})= J\sum_{(i,j)}x_ix_j+ \eta\sum_i x_iy_i+\text{constante},\quad \eta=\tfrac12\log\frac{1-\eps}{\eps}.

ICM (iterated conditional modes) updates a pixel to the mode of its conditional given the current state of the rest. This increases or preserves the posterior at each step, but can end at a local optimum and depends on order and initialization. High coupling favors uniform regions and can erase details.

For one update, take two neighboring pixels with observation (+1,−1)(+1,-1), ε=0.2\eps=0.2 and J=1J=1. Then η=12log⁡4≈0.6931\eta=\tfrac12\log 4\approx0.6931. Initialize x=y\vb{x}=\vb{y}: the first pixel’s local field is Jx2+ηy1=−1+η<0Jx_2+\eta y_1=-1+\eta<0, so ICM changes it to −1-1. The compatibility term goes from −1-1 to +1+1, while data fit goes from 2η2\eta to zero. The objective increases because 1>−1+2η1>-1+2\eta. This minimal case shows how smoothing can erase a genuine detail.

InteractiveClean or erase details

Drawing

Observed

Estimate

0.20
0.7
Accuracy against drawing74 %
ICM sweeps0
Edit the drawing, choose the flip probability, press 'Add noise' and apply ICM sweeps. Compare removed noise and erased details as J increases.

The slider immediately sets the likelihood’s assumed rate; to generate new corruption with that rate, press ‘Add noise’. If you change the slider without regenerating, the model and the rate used for the previous observation may differ. The percentage compares against the known drawing in this simulation. For a real image without ground truth that accuracy would not be directly observable.

The expensive constant

The partition function sums all weights. For nn spins there are 2n2^n configurations, so enumeration grows exponentially. Do not omit ZZ when comparing parameters: it changes with them and ensures probabilities sum to one.

If θ\theta is a natural parameter and T(x)T(\vb{x}) its sufficient statistic, the exponential family gives

log⁡pθ(x)=θ⊤T(x)−log⁡Z(θ),∇θlog⁡Z(θ)=Eθ[T(X)].\log p_\theta(\vb{x})=\theta\T T(\vb{x})-\log Z(\theta), \quad \nabla_\theta\log Z(\theta)=\E_\theta[T(X)].

The second equality follows by differentiating the finite sum and dividing by ZZ. For mm observations, the average log-likelihood gradient is the empirical statistic minus its expectation under the model. A learning step therefore needs an expectation that generally requires difficult or approximate inference, not merely evaluating the observed state.

For Ising with T=1T=1, define T1(x)=∑(i,j)xixjT_1(\vb{x})=\sum_{(i,j)}x_ix_j and T2(x)=∑ixiT_2(\vb{x})=\sum_i x_i. The gradient with respect to (J,h)(J,h) is the difference between observed averages of those statistics and averages under the current model. If coupling predicts too much alignment, the gradient component for JJ is negative and an ascent update reduces JJ. The sign reverses when minimizing negative log likelihood in the lab.

The Hessian of log⁡Z\log Z is the covariance of statistics under the model. It is positive semidefinite, so an exponential family’s log likelihood in natural parameters is concave. This does not make the expectation cheap or ensure a finite maximum for every dataset: with separable observations the optimum can escape to infinite parameters.

Besag’s pseudolikelihood replaces the joint by ∏ip(xi∣x−i)\prod_i p(x_i\given\vb{x}_{-i}) per observation. In Ising each conditional is logistic and its normalization sums only two values. It is not the joint likelihood and the numbers are not directly comparable; it avoids global ZZ at the cost of a different objective. Next compare its estimators with exact maximum likelihood in a small model.

The proposal by Besag uses products of local conditionals precisely when joint normalization makes estimation difficult.

If mm network observations contain nn spins, log pseudolikelihood sums mnmn logistic terms. Sharing JJ and hh across nodes makes all contribute to the same parameters. If instead you fit a separate logistic regression per node, estimates of the same edge from its two ends need not agree in a finite sample; you need a symmetrization rule or joint optimization with shared parameters.

Pseudolikelihood uses all local observations without evaluating joint normalization. This does not make terms independent or turn its uncertainty into that of ordinary logistic regression with mnmn independent examples. To quantify uncertainty, account for dependence and use, for example, independent experimental repetitions as in the lab.

Lab: enumerate a 4×4 Ising model

The lab lattice has open boundaries, unlike the first figure. Enumerate its 216=655362^{16}=65536 states and calculate ZZ, marginals and neighbor correlations. The convention is unit temperature, J=0.3J=0.3 and h=0.1h=0.1.

[ ]Exact enumerationBrowser
import itertools
import time
import numpy as np

def grid_edges(rows, cols):
    edges = []
    for r in range(rows):
        for c in range(cols):
            i = r*cols+c
            if c+1 < cols: edges.append((i, i+1))
            if r+1 < rows: edges.append((i, i+cols))
    return edges

def states(n):
    integers = np.arange(1 << n, dtype=np.uint32)
    return (2*((integers[:, None] >> np.arange(n, dtype=np.uint32)) & 1).astype(np.int8)-1)

def features(X, edges):
    pair = np.zeros(len(X), dtype=float)
    for i,j in edges:
        pair += X[:,i]*X[:,j]
    return np.column_stack((pair, X.sum(axis=1)))

X16 = states(16)
edges16 = grid_edges(4,4)
f16 = features(X16, edges16)
J, h = .3, .1
logw = f16 @ np.array([J,h])
weights = np.exp(logw-logw.max())
Z = np.exp(logw.max())*weights.sum()
weights /= weights.sum()
print("estados, aristas:", len(X16), len(edges16))
print("Z:", Z)
print("P(esquina +), P(interior +):",
      weights[X16[:,0]==1].sum(), weights[X16[:,5]==1].sum())
print("E[x0 x1], E[x5 x6]:",
      weights @ (X16[:,0]*X16[:,1]), weights @ (X16[:,5]*X16[:,6]))

Check J=h=0J=h=0: every state has weight one, Z=216Z=2^{16}, each marginal equals 1/21/2 and distinct-spin correlations are zero. This checks the implementation rather than measuring a physical system.

[ ]Independent controlBrowser
uniform = np.full(len(X16), 1/len(X16))
print("Z sin interacción:", len(X16))
print("marginal y correlación:", uniform[X16[:,0]==1].sum(), uniform @ (X16[:,0]*X16[:,1]))
print("relación de estados 5×5 / 4×4:", 2**25 / 2**16)
eta = .5*np.log(4)
print("ICM, eta y objetivos antes/después:", eta, -1+2*eta, 1)
print("Z de cadena de tres espines:", 8*np.cosh(1)**2)

Moving from 4×44\times4 to 5×55\times5 gives 512 times as many states, not 25/1625/16 times. The next long cell enumerates all 5×55\times5 states in blocks to avoid allocating the full table. It is excluded from automatic execution due to cost; run it voluntarily and compare the observed browser duration with the first calculation. Time depends on the device and is not a performance guarantee.

[ ]Long 5×5 enumerationBrowser
def partition_blocks(rows, cols, J, h, block=65536):
    n = rows*cols
    edges = grid_edges(rows, cols)
    total = 0.0
    for start in range(0, 1 << n, block):
        integers = np.arange(start, min(start+block, 1 << n), dtype=np.uint32)
        X = (2*((integers[:,None] >> np.arange(n, dtype=np.uint32)) & 1).astype(np.int8)-1)
        f = features(X, edges)
        total += np.exp(J*f[:,0] + h*f[:,1]).sum()
    return total

for side in (4, 5):
    start = time.perf_counter()
    z = partition_blocks(side, side, .3, .1)
    print("lado:", side, "Z:", z, "segundos:", time.perf_counter()-start)

Blocked enumeration reduces memory, not state count. Even a constant-factor improvement cannot defeat exponential growth: each extra spin doubles configurations. Assuming constant throughput per state, 6×66\times6 requires 211=20482^{11}=2048 times as many states as 5×55\times5. A one-minute budget would be infeasible if the 5×55\times5 measurement exceeds 60/204860/2048 seconds and cost scales proportionally. This extrapolates this algorithm, not a measurement of 6×66\times6 or a bound for methods exploiting structure.

Lab: fit two objectives

Use an open 2×32\times3 lattice with six spins. Draw independent samples from its exact distribution by enumeration and fit one JJ and one hh shared across nodes. Exact maximum likelihood sums all 64 states each step; pseudolikelihood sums local conditionals. Repeat with different seeds to observe sampling variation. This small run compares estimators and costs for this case, not which dominates universally.

[ ]Exact MLE and pseudolikelihoodBrowser
from scipy.optimize import minimize
from scipy.special import expit, logsumexp

X6 = states(6)
edges6 = grid_edges(2,3)
f6 = features(X6, edges6)
true_theta = np.array([.45,.2])
logp = f6 @ true_theta
p6 = np.exp(logp-logsumexp(logp))
neighbors = [[] for _ in range(6)]
for a,b in edges6:
    neighbors[a].append(b); neighbors[b].append(a)

def nll_exact(theta, data):
    fd = features(data, edges6)
    scores = f6 @ theta
    p = np.exp(scores-logsumexp(scores))
    loss = logsumexp(scores) - np.mean(fd @ theta)
    grad = p @ f6 - fd.mean(axis=0)
    return loss, grad

def nll_pseudo(theta, data):
    J, h = theta
    near = np.column_stack([data[:,ns].sum(axis=1) for ns in neighbors])
    margin = 2*data*(J*near+h)
    loss = np.logaddexp(0, -margin).sum(axis=1).mean()
    factor = -2*data*expit(-margin)
    grad = np.array([(factor*near).sum(axis=1).mean(),
                     factor.sum(axis=1).mean()])
    return loss, grad

est_exact, est_pseudo = [], []
elapsed = np.zeros(2)
for seed in range(20):
    rng6 = np.random.default_rng(seed)
    data = X6[rng6.choice(len(X6), size=150, p=p6)]
    for i, (target, fun) in enumerate([(est_exact,nll_exact),(est_pseudo,nll_pseudo)]):
        start = time.perf_counter()
        result = minimize(fun, np.zeros(2), args=(data,), jac=True, method="BFGS")
        elapsed[i] += time.perf_counter()-start
        assert result.success, result.message
        target.append(result.x)
for name, estimates in [('exacta',est_exact),('pseudo',est_pseudo)]:
    estimates = np.asarray(estimates)
    print(name, "media:", estimates.mean(axis=0).round(4),
          "sesgo:", (estimates.mean(axis=0)-true_theta).round(4),
          "varianza:", estimates.var(axis=0,ddof=1).round(6),
          "desviación:", estimates.std(axis=0,ddof=1).round(4))
print("tiempos totales de ajuste exacta y pseudo:", elapsed.round(3))

The means and standard deviations above describe twenty particular datasets of 150 samples, not exact population bias or variance. Exact cost evaluates 64 states per step here; as the lattice grows their number rises as 2n2^n. Pseudolikelihood evaluates one conditional per node and observation, although optimization still has a cost.

The cell’s times include twenty fits per method; compare them in your run while accounting for changing clock and load and potentially different optimizer step counts. On this small network, enumerating 64 states can be cheap: one timing measurement implies no universal advantage.

With these seeds and parameters, the reference run gives approximate means (0.4529,0.2032)(0.4529,0.2032) for maximum likelihood and (0.4526,0.2015)(0.4526,0.2015) for pseudolikelihood, versus generating value (0.45,0.2)(0.45,0.2). Variation across repetitions is visible in the output. Do not interpret a small advantage across twenty repetitions as conclusive: increase repetitions and present intervals to study efficiency.

Exercises

ProofFrom factors to separation
Prove: A mass factorizing over the cliques of an undirected graph satisfies the global Markov property.
0
S separates A from B and configuration s has positive probability.

Step 1 of 3. Can a clique contain nodes from two different components of G without S?

Quiz
Consider the independence patterns of an undirected four-node cycle and DAG A → C ← B. Which statements are correct, assuming positive distributions faithful to each graph and adding no variables?

More than one answer may be correct.

Numeric
Three spins form chain 1-2-3, with J=1, h=0 and T=1. Calculate the partition function.
Quiz
Why does an MRF log likelihood require an expectation under the model?
CodePseudolikelihood and gradient
Implement log_pseudo(theta, data, edges). theta=(J,h), data has shape (m,n) with spins ±1, and edges lists undirected pairs, each appearing once. Return mean log pseudolikelihood per observation and its length-two gradient. Use np.logaddexp for stability.
import numpy as np

def log_pseudo(theta, data, edges):
  return 0.0, np.zeros(2)
Shift+Enter to run
Key idea
Local potentials define a joint distribution when divided by Z. Undirected separation guarantees independences; positivity enables the reverse Hammersley-Clifford direction. Pseudolikelihood avoids the global sum while changing the learning objective.