AI Wiki中文/EN

Markov random fields: local compatibility, global normalization

马尔可夫随机场

Enumerate a positive graphical model and distinguish potentials, partition functions and conditional independence.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Neighbors can prefer to agree

Picture three binary labels along a short image strip: A—B—C. A pairwise compatibility table can favor equal neighboring labels without declaring that the left pixel causes the right one. An additional local factor can favor A=1. Multiplying these preferences assigns a weight to each complete labeling; summing all weights supplies the normalization.

That is a small Markov random field. The word “Markov” concerns conditional dependence on neighbors, not necessarily a time sequence. Read conditional probability and Bayesian networks to compare the two graph languages.

Potentials are weights until the joint is normalized

For a finite undirected graph, attach nonnegative functions ψ_C to cliques or smaller allowed scopes. A clique is a set of mutually adjacent vertices. If the sum is finite and positive, the product defines a distribution:

p(x)=1Z∏CψC(xC),Z=∑x∏CψC(xC).p(x)=\frac1Z\prod_C\psi_C(x_C),\qquad Z=\sum_x\prod_C\psi_C(x_C).

Individual potentials need not sum to one, and may exceed one. Multiplying any whole potential by a positive constant changes Z by the same factor and leaves p unchanged. Potentials are therefore not uniquely identified by the distribution. Deep Learning, Section 16.2.2 contrasts this global normalization with directed conditional tables.

For strictly positive finite distributions, the local Markov property and a positive clique factorization are equivalent under the Hammersley–Clifford theorem. Shalizi’s lecture, Gibbs–Markov backup, states the positivity condition explicitly. Factorization implies the corresponding separation independencies; recovering factorization from Markov statements requires care when zeros are allowed. We use positive tables throughout the program.

A fully specified three-node model

Set ψ_A(0)=1 and ψ_A(1)=2. The edge AB gets weight 3 for equal labels and 1 otherwise; BC gets weight 2 for equal labels and 1 otherwise. There are no other nonconstant factors. Binary order 000,001,…,111 gives weights(6,3,1,2,4,2,6,12), whose sum is 36.

The local conditional of B cancels every factor that does not involve B:

p(b∣a,c)=ψAB(a,b)ψBC(b,c)∑b′ψAB(a,b′)ψBC(b′,c).p(b\mid a,c)= \frac{\psi_{AB}(a,b)\psi_{BC}(b,c)} {\sum_{b'}\psi_{AB}(a,b')\psi_{BC}(b',c)}.

At A=0,C=0, weights for B=0 and 1 are 6 and 1, so p(B=1|A=0,C=0)=1/7. The unary A factor cancels because A is fixed. More generally, a node’s conditional given all other nodes depends only on its neighbors for this factorization.

No edge does not mean no marginal association

Once B=b is fixed, the remaining factors split into an A-only part and a C-only part. Their normalization splits too:

p(a,c∣b)=ψA(a)ψAB(a,b)∑a′ψA(a′)ψAB(a′,b)ψBC(b,c)∑c′ψBC(b,c′)=p(a∣b)p(c∣b).p(a,c\mid b)= \frac{\psi_A(a)\psi_{AB}(a,b)}{\sum_{a'}\psi_A(a')\psi_{AB}(a',b)} \frac{\psi_{BC}(b,c)}{\sum_{c'}\psi_{BC}(b,c')} =p(a\mid b)p(c\mid b).

Thus A and C are conditionally independent given B. They are not marginally independent in our table: p(A=1,C=1)=7/18, while p(A=1)p(C=1)=19/54. The path through B transmits association when B is unobserved. On a larger graph, a separating observed set blocks every path between the two variable sets.

Inspect the partition function and exact conditionals

Run this complete Python 3.12 program with rational positive potentials at most 1000. It deliberately handles only the binary three-node chain, rather than hiding an exponential generic model behind a short function call. The query helper operates on the joint returned by the constructor.

from fractions import Fraction as F
from itertools import product


def chain_joint(unary_a, pair_ab, pair_bc):
    unary_a=list(unary_a);pair_ab=[list(row) for row in pair_ab];pair_bc=[list(row) for row in pair_bc]
    if len(unary_a)!=2 or any(len(table)!=2 or any(len(row)!=2 for row in table)
                             for table in (pair_ab,pair_bc)):
        raise ValueError('binary unary vector and two 2-by-2 pair tables required')
    values=unary_a+[x for table in (pair_ab,pair_bc) for row in table for x in row]
    if any(type(x) not in (int,F) or not 0<x<=1000 for x in values):
        raise ValueError('strictly positive rational potentials at most1000 required')
    weights={(a,b,c):F(unary_a[a])*F(pair_ab[a][b])*F(pair_bc[b][c])
             for a,b,c in product((0,1),repeat=3)}
    partition=sum(weights.values(),F(0))
    return {state:w/partition for state,w in weights.items()},partition


def conditional(joint, query, evidence=None):
    evidence={} if evidence is None else evidence
    for assignments in (query,evidence):
        if any(type(k) is not int or k not in (0,1,2) or type(v) is not int or v not in (0,1)
               for k,v in assignments.items()):
            raise ValueError('binary values indexed by0=A,1=B,2=C required')
    mass=sum((w for s,w in joint.items() if all(s[k]==v for k,v in evidence.items())),F(0))
    if not mass:raise ValueError('zero-probability evidence')
    selected=sum((w for s,w in joint.items() if all(s[k]==v for k,v in evidence.items())
                  and all(s[k]==v for k,v in query.items())),F(0))
    return selected/mass


if __name__ == '__main__':
    joint,z=chain_joint([1,2],[[3,1],[1,3]],[[2,1],[1,2]])
    print('partition:',z)
    print('joint masses in binary state order:',*[str(joint[s]) for s in sorted(joint)])
    print('P(A=1,C=1):',conditional(joint,{0:1,2:1}))
    print('P(A=1)P(C=1):',conditional(joint,{0:1})*conditional(joint,{2:1}))
    for b in (0,1):
        print('B='+str(b),'joint:',conditional(joint,{0:1,2:1},{1:b}),
              'product:',conditional(joint,{0:1},{1:b})*conditional(joint,{2:1},{1:b}))
    print('P(B=1|A=0,C=0):',conditional(joint,{1:1},{0:0,2:0}))

Output:

partition: 36
joint masses in binary state order: 1/6 1/12 1/36 1/18 1/9 1/18 1/6 1/3
P(A=1,C=1): 7/18
P(A=1)P(C=1): 19/54
B=0 joint: 2/15 product: 2/15
B=1 joint: 4/7 product: 4/7
P(B=1|A=0,C=0): 1/7

Given B=0, the endpoint joint probability is 2/15 and equals(2/5)(1/3). Given B=1 it is 4/7 and equals(6/7)(2/3). These exact checks verify the conditional factorization without relying on a tolerance or a graph-drawing convention.

For n binary variables, enumerating the joint requires 2ⁿ configurations; with m local factors it takes O(m 2ⁿ) factor evaluations and O(2ⁿ) storage if the full table is retained. A chain has much cheaper message-passing alternatives. Computing a MAP configuration asks for the maximum weight, whereas computing a marginal adds weights across configurations: replacing a sum by a max changes the question.

Local description does not make global inference free

A grid can have simple pairwise potentials and still make exact normalization expensive. Approximate inference needs its own error and convergence assessment. Gibbs sampling uses local conditionals and avoids explicitly evaluating Z in each update, but this does not guarantee rapid mixing or independent samples.

Taking negative logarithms turns positive potentials into additive energies: E(x)=−Σ_C lnψ_C(x_C), so p(x)=exp(−E(x))/Z. “Lower energy” means larger probability within that model. It is not necessarily physical energy, and zero potentials require infinite-energy conventions rather than the ordinary finite logarithm.

A general clique factorization need not be pairwise; reducing a higher-order interaction to pairwise terms may require extra variables or may change the model. Nor can arbitrary locally chosen conditional distributions always be glued into a consistent joint. Our construction starts with potentials, which makes a valid positive normalized joint available by definition.

Keep weights, marginals and conditionals separate

  1. Is ψ_AB(0,0)=3 an invalid probability?

Answer 1: It is a potential weight, not a probability. The normalized full joint is valid.

  1. What changes if every entry of ψ_AB is multiplied by 7?

Answer 2: Z changes from 36 to 252. Every normalized joint probability stays the same.

  1. Are A and C independent merely because there is no AC edge?

Answer 3: No. The graph guarantees independence given B here, not marginal independence; the stated joint table shows the difference.

  1. Why does ψ_A disappear from p(B|A,C)?

Answer 4: With A fixed it is a common positive factor in numerator and denominator and cancels.

Use the representation that makes the computation explicit

Undirected models make symmetric compatibility and local neighborhoods convenient. Directed models specify normalized local conditional distributions. Factor graphs expose the individual factors themselves and can represent either product.

Project: recover the same chain marginals with sum-product messages and compare every probability against this enumerated table. Then add an AC edge and check why conditioning on B alone no longer separates A and C. Recompute the actual conditional probabilities rather than inferring dependence solely from the newly drawn edge.

Make a prediction, then check

Must each potential table sum to one?

Choose one answer

Learning objectives

  • Normalize positive local potentials into a joint distribution.
  • Verify separation conditionals and distinguish them from marginal independence.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter16: Structured Probabilistic Models
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. Markov Random Fields — Data over Space and Time
    Cosma Shalizi · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source locations, mathematical assumptions, original examples, exact/literal and numerical checks, and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: primary-source locations, explicit assumptions and limits, mathematical derivations, literal/exact reference probabilities, bilingual equations and four matching exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter; strict bilingual MDX/KaTeX rendering gives three display equations, six anchors and four answers. Exact rational inference is separated from floating-point maximum-entropy solving; test scopes and repository results are recorded separately.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • Final English copy edit separates words from adjacent numerals outside code, equations and link destinations; formulas/programs unchanged, final SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.