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.
The figure is an explicit simulation on a periodic 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 is a distribution satisfying a Markov property relative to that graph. In a finite space, one construction chooses nonnegative potentials on cliques and normalizes:
where when all potentials are positive. A clique is a set whose nodes are pairwise adjacent. The sum 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 separates from in the undirected graph, the global property states . 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 , separates the endpoints. To see the mechanism without a theorem, write . Fixing , the first factor depends only on and the second only on . The sum of all weights over 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 by the same constant and leaves 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 and group connected components containing , those containing and the rest. No clique can contain nodes from two distinct components of : their connecting edge would join the components. With fixed, the product of potentials separates into one factor per component and one depending only on . Summing variables other than also separates by component. The conditional normalization constant factorizes into the product of the sums on each side, giving . 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.
In , the parents are d-separated without evidence but connected when is observed. After moralization edge 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.
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 , with in the pairwise case. The displayed value is calculated by enumerating its eight states.
This is more than different names. With and , 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 and once each. Pairwise marginals miss the joint interaction; average 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 and defines
With and zero field, aligned neighbors are favored. With all other spins fixed, only factors containing remain. The mass ratio of to gives
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 labels and favors equality with terms such as . On an infinite square lattice with no field and , Ising has critical temperature 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 ; 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 in the isotropic case with Boltzmann’s constant set to one. Solving gives the expression above.
A noisy image
Suppose each original pixel flips independently with probability , giving . Combine the Ising prior with that likelihood. Ignoring constants independent of ,
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 , and . Then . Initialize : the first pixel’s local field is , so ICM changes it to . The compatibility term goes from to , while data fit goes from to zero. The objective increases because . This minimal case shows how smoothing can erase a genuine detail.
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 spins there are configurations, so enumeration grows exponentially. Do not omit when comparing parameters: it changes with them and ensures probabilities sum to one.
If is a natural parameter and its sufficient statistic, the exponential family gives
The second equality follows by differentiating the finite sum and dividing by . For 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 , define and . The gradient with respect to 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 is negative and an ascent update reduces . The sign reverses when minimizing negative log likelihood in the lab.
The Hessian of 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 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 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 network observations contain spins, log pseudolikelihood sums logistic terms. Sharing and 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 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 states and calculate , marginals and neighbor correlations. The convention is unit temperature, and .
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 : every state has weight one, , each marginal equals and distinct-spin correlations are zero. This checks the implementation rather than measuring a physical system.
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 to gives 512 times as many states, not times. The next long cell enumerates all 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.
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, requires times as many states as . A one-minute budget would be infeasible if the measurement exceeds seconds and cost scales proportionally. This extrapolates this algorithm, not a measurement of or a bound for methods exploiting structure.
Lab: fit two objectives
Use an open lattice with six spins. Draw independent samples from its exact distribution by enumeration and fit one and one 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.
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 . 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 for maximum likelihood and for pseudolikelihood, versus generating value . 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
Step 1 of 3. Can a clique contain nodes from two different components of G without S?
More than one answer may be correct.
import numpy as np
def log_pseudo(theta, data, edges):
return 0.0, np.zeros(2)