Bayesian networks: factor a joint distribution
贝叶斯网络
Build exact conditional tables, observe explaining away and distinguish graph implications from causal claims.
bayesian-networksTwo possible explanations for one warning
A toy monitoring system has two binary conditions A and B, and a warning C. We model A and B as independent before observing anything. Either can make a warning more likely. Once a warning occurs, evidence for B can reduce how strongly we suspect A: the warning already has a plausible explanation.
The diagram is A→C←B, a collider or common-effect structure. Its arrows specify the factorization used by the probability model. They are not automatically causal claims about an actual device. Read conditional probability and Bayesian inference first.
A graph plus conditional distributions defines a model
A Bayesian network contains a directed acyclic graph, one random variable per node, and a normalized conditional distribution for each node given its parents. Root nodes have ordinary marginal distributions. The joint distribution is:
Deep Learning, Section 16.2.1 gives this construction. A topological ordering puts each parent before its child. Summing variables in reverse order removes one normalized conditional at a time, proving that the product sums to one. This argument fails for an arbitrary directed cycle: multiplying locally normalized tables around a cycle need not produce a normalized joint.
For our model, p(a,b,c)=p(a)p(b)p(c|a,b). The binary root probabilities are p(A=1)=1/5 and p(B=1)=1/10. The warning probabilities are:
| A | B | p(C=1 given A,B) |
|---|---|---|
| 0 | 0 | 1/100 |
| 1 | 0 | 4/5 |
| 0 | 1 | 7/10 |
| 1 | 1 | 19/20 |
Each table row also assigns the complementary probability to C=0. The graph alone cannot fill these numbers. Summing out C gives p(a)p(b), so A and B are marginally independent for every choice of this warning table.
Conditioning changes the factorization you use
After observing C=1, the joint over A,B becomes:
The warning probability is 1131/5000. A is present together with the warning with probability 815/5000, so p(A=1|C=1)=815/1131. If B is also known to be present, this falls to 19/75; if B is absent, it rises to 20/21. Without the warning, knowing B leaves p(A=1)=1/5 unchanged. These are exact calculations for the declared table, not measurements of a physical system.
Read conditional independence through d-separation
In a chain A→B→C or fork A←B→C, conditioning on the middle node blocks that path. In a collider A→C←B, the path is blocked until the collider or one of its descendants is conditioned on. More generally, a path is active given an observed set when all its non-colliders are unobserved and every collider is observed or has an observed descendant. If no path is active, the sets are d-separated.
Sontag’s 2012 lecture, slides 32–36 contrasts these local structures and d-separation. D-separation guarantees conditional independence in distributions that factor according to the graph. An active path permits dependence; it does not force it for every parameter choice. For example, a constant warning table makes C independent of its listed parents. Inferring graph structure from observed independencies therefore needs additional assumptions such as faithfulness, not just this forward implication.
Sum eight joint states, then condition
The complete Python 3.12 program uses rational tables for this fixed three-node collider. collider_joint constructs eight probabilities; probability is a query helper for the generated joint. It checks binary variable assignments and rejects impossible evidence. A contradictory query and positive-probability evidence returns zero, as it should.
from fractions import Fraction as F
from itertools import product
def collider_joint(pa, pb, pc):
keys=set(product((0,1),repeat=2))
if set(pc)!=keys or any(type(v) is not int for key in pc for v in key):
raise ValueError('C table requires exactly the four binary parent tuples')
values=[pa,pb,*pc.values()]
if any(type(v) not in (int,F) or not 0<=v<=1 for v in values):
raise ValueError('rational probabilities in [0,1] required')
pa,pb=F(pa),F(pb)
result={}
for a,b,c in product((0,1),repeat=3):
p=F(pc[a,b])
result[a,b,c]=(pa if a else 1-pa)*(pb if b else 1-pb)*(p if c else 1-p)
return result
def probability(joint, query, evidence=None):
evidence={} if evidence is None else evidence
names={'A':0,'B':1,'C':2}
for assignments in (query,evidence):
if any(k not in names or type(v) is not int or v not in (0,1)
for k,v in assignments.items()):
raise ValueError('binary assignments to A, B or C required')
denominator=numerator=F(0)
for state,mass in joint.items():
if all(state[names[k]]==v for k,v in evidence.items()):
denominator+=mass
if all(state[names[k]]==v for k,v in query.items()):numerator+=mass
if denominator==0: raise ValueError('evidence has zero probability')
return numerator/denominator
if __name__ == '__main__':
c={(0,0):F(1,100),(1,0):F(4,5),(0,1):F(7,10),(1,1):F(19,20)}
joint=collider_joint(F(1,5),F(1,10),c)
print('joint mass:',sum(joint.values()))
for query,evidence in [({'A':1},{}),({'A':1},{'B':1}),({'C':1},{}),
({'A':1},{'C':1}),({'A':1},{'C':1,'B':1}),
({'A':1},{'C':1,'B':0})]:
print(query,'given',evidence,':',probability(joint,query,evidence))
Output:
joint mass: 1
{'A': 1} given {} : 1/5
{'A': 1} given {'B': 1} : 1/5
{'C': 1} given {} : 1131/5000
{'A': 1} given {'C': 1} : 815/1131
{'A': 1} given {'C': 1, 'B': 1} : 19/75
{'A': 1} given {'C': 1, 'B': 0} : 20/21
A general binary table over n nodes needs 2ⁿ−1 free probabilities. A binary Bayesian network needs a total of Σᵢ2^dᵢ conditional parameters, where dᵢ is the number of parents. For this collider, that is 1+1+4=6 instead of 7. Larger sparse networks may save much more storage, but compact representation does not guarantee cheap inference.
For a query Q and evidence e, exact inference marginalizes the hidden variables H:
Our code enumerates eight states and is constant-sized; naive general enumeration takes O(n 2ⁿ) factor operations and O(2ⁿ) storage if it materializes the joint. Variable elimination exploits repeated subexpressions, with cost depending strongly on elimination order and induced width. The example is not a generic network loader or a d-separation algorithm.
Probability arrows and intervention arrows differ
Observing A=a changes beliefs about related variables. Forcing A=a in a causal model changes the generating mechanism. These operations are not interchangeable. To interpret a network causally, explain the structural assumptions, omitted variables and intervention semantics; observational probabilities alone generally do not identify direction.
Parameter learning from complete data can estimate local conditional tables. Sparse rows, hidden variables or missing values need smoothing, priors or a justified learning method. The word “Bayesian” in the network’s name does not require that every parameter was fitted by Bayesian estimation. A probability table can come from counts, expert judgment or another model, with different uncertainty and validation needs.
Zero-probability evidence has no ordinary conditional distribution under the declared joint; silently adding a tiny denominator hides the model’s contradiction. In larger systems, numerical underflow is a different issue and calls for stable arithmetic, not changing the probabilistic question.
Keep the observed set visible
- Why are A and B independent before observing C?
Answer 1: Summing p(a)p(b)p(c|a,b) over c leaves p(a)p(b).
- Does observing B=1 alone change p(A=1) in this model?
Answer 2: No; it remains 1/5. After also observing C=1, it is 19/75.
- Does an active path prove nonzero dependence for every parameter table?
Answer 3: No. Special parameters can introduce extra independencies; constant conditional tables give a simple example.
- What should happen when conditioning on evidence assigned probability zero?
Answer 4: Report that the conditional query is undefined for this model; the program raises an error.
Representation, learning and inference are separate jobs
A graph tells us how to assemble the joint; learning supplies its parameters or structure; inference answers queries. Evaluating all three as one opaque “Bayesian network method” conceals where approximation or modeling assumptions enter.
Project: replace the warning table by a constant and verify the extra independence, then restore it and compare the three posterior probabilities above. Next express the same joint as a factor graph. Matching the distribution across representations is a stronger check than drawing similar arrows.
Make a prediction, then check
Does an active path force dependence for every parameter choice?
Learning objectives
- Construct a normalized joint from a DAG and conditional tables.
- Explain collider conditioning and the limits of graph-based independence claims.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning — Chapter16: Structured Probabilistic Models
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - Graphical Models — Lecture1, January26,2012
David Sontag · 2012
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:
- Deep Learning — Chapter16: Structured Probabilistic Models · Section16.2.1 equation16.1: DAG plus normalized local conditionals and compact parameterization; no textbook figure or table copied.
- Graphical Models — Lecture1, January26,2012 · Lecture1 datedJanuary26,2012, NYU affiliation in slides despite MIT-hosted URL; slides32–36 local fork/chain/collider and d-separation.
Related topics