Bayesian networks: factorizing the joint with a directed graph
A Bayesian network encodes a joint distribution as a product of local conditionals on a DAG. Study the independences implied by its graph, including d-separation and Markov blankets, how to draw models with plates, sample in topological order and learn probability tables from complete data.
After this lesson you can
- Write the joint factorization associated with a DAG and count its free parameters.
- Decide conditional independences using d-separation and implement the Bayes-ball reachability algorithm.
- Identify a node's Markov blanket and explain explaining away.
- Translate a plate model into its unrolled graph and back.
- Estimate conditional probability tables using maximum likelihood and MAP with a Dirichlet prior.
Before you start
A joint distribution you can write down
Thirty binary variables have configurations. A joint table needs free parameters; normalization fixes the last. But if each variable depends on few parents, a collection of local tables can be much smaller. The trade-off is that structure imposes assumptions: probabilities that do not fit those tables cannot be represented.
A binary node with binary parents has parent configurations and one free probability per configuration. In general, if has states and its parents have configurations, the network needs parameters. An edge does not always add a fixed number: its cost depends on the child’s existing parents.
A local rule produces the joint
A Bayesian network consists of a directed acyclic graph and a normalized conditional distribution for each node given its parents. The graph admits a topological order in which each parent precedes its child. The joint is
This expression also defines a valid distribution: sum successively over leaf nodes and each conditional sums to one. The chain rule for any distribution generally contains all predecessors. The factorization above removes predecessors that are not parents through conditional independences. Hence not every distribution factorizes on every graph.
The DAG is an independence map (I-map) of when every separation it predicts implies an independence in . The converse, that every independence in is predicted by the graph, is called faithfulness. This is an additional assumption: exact cancellations in the tables may create independences not required by the graph. An arrow indicates permitted local dependence; it does not demonstrate causality. Interpreting it as an intervention requires additional causal assumptions.
Direction alone does not identify a cause either. For example, two variables with a positive joint distribution admit both and . Both one-edge DAGs encode the same observational independences, although causal interpretations would respond differently to intervention. Distinguishing observation from intervention requires a causal model and cannot be settled from factorization alone.
As an example of unfaithfulness, in choose the same distribution for in every row of the table for . Then even though the direct path is active. The network remains an I-map: all separations it asserts are correct. It simply fails to represent some independences caused by its particular parameter values.
Paths and evidence
Three fragments explain the rule. In chain , observing blocks the path: once the intermediate state is known, the source adds no information about the destination. The same holds for fork . Collider is the reverse: the path is blocked if neither nor any descendant is observed, and opens when one of them is observed.
The implication is universal over compatible tables. An active path does not guarantee dependence in a particular table because probabilities may coincide or effects cancel. Conditioning considers only evidence values with positive probability.
Distinguish a path from a directed edge: when traversing, ignore directions, but retain them when classifying interior nodes. In both arrows point to and form a collider. In they leave , making a non-collider. One active path suffices for the graph not to guarantee independence; proving separation requires blocking all paths. With multiple evidence variables, apply the rule to each whole path, not an isolated node.
The global result connects this graphical test to factorization: if the graph d-separates disjoint sets and by , every factorizing distribution satisfies the corresponding conditional independence. Strict positivity is unnecessary for this direction with discrete variables, but conditional equality is required only where evidence has positive mass. The converse can fail due to the unfaithfulness seen above.
The figure’s network uses eight binary variables in order : , , , and . Its conditionals form an explicit model: , , if and otherwise; or ; or ; ; or ; and is for . The numerical table enumerates all 256 configurations and shows the maximum over possible values of of . A numerical zero confirms independence in this model but does not prove faithfulness for any other.
Reachability. Before traversal, mark the ancestors of , including . The ball enters the origin from a child. On arriving from a child at an unobserved node it goes to parents and children; on arriving from a parent it goes to children if the node is unobserved and to parents if it is an ancestor of evidence. Memorizing each pair (node, arrival direction) prevents repeats: there are at most two states per node and each edge is examined a constant number of times. Cost is . If an unobserved target is reachable, an active path exists. For sets, initialize a ball per node of .
This variant makes the preliminary ancestor search explicit; the original algorithm and complexity analysis are in Shachter, Bayes-Ball. Linear cost refers to the graph, not enumeration of a joint distribution to display probabilities as our figure does.
Explaining an effect and shielding a node
Take independent rain and sprinkler , with wet grass as their common effect. With the figure’s initial tables, wet grass favors the sprinkler; known rain explains part of that evidence and reduces its posterior. This is not a law for all tables: it depends on interactions between causes.
By Bayes, if and ,
This phenomenon is called explaining away: observing a common effect can make independent causes dependent. If wetness has the same probability for every combination, observing it gives no information.
With initial values, : add the four joint rain-sprinkler probabilities weighted by the row’s wetness probability. Sprinkler probability given wetness is . If rain is also known, the formula above gives approximately . Both exceed prior under these tables; in particular, rain reduces probability relative to observing wet grass alone. These numbers describe the chosen model, not a measured real-world frequency.
Why does it fall? Wet grass was evidence for some cause. Rain already makes the effect likely even without the sprinkler, leaving less additional evidence for the latter. The direction is not universal: changing the interaction table can eliminate or reverse the comparison. The figure therefore lets you modify all four cells, not just a prior.
A node has a Markov blanket comprising its parents, children and its children’s other parents. Given the blanket, is independent of the rest of the network at blanket values with positive probability. In the factorization the only factors containing are and its children’s factors. With the blanket fixed, the product of all other factors is constant in and cancels when normalizing the conditional. Co-parents are needed because observing a child opens a collider.
In the figure’s network, the blanket of is : are its parents, its children and the other parent of . Given these five nodes, and add no information about . The blanket is a separation guaranteed by the graph; a smaller set may also separate for a particular parameterization, for example if a factor ignores one of its parents.
Plates, latent variables and sampling
Plate notation groups copies with the same structure; it does not mean their values are equal. In a finite mixture, shared vector sets assignment probabilities, each component has parameter , and each datum generates followed by . The joint conditional on is . If they are also random, multiply their priors. The are latent if unobserved; that does not prevent including them in the generative story.
Notice two uses of plates. The plate of size replicates component parameters; the plate of size replicates one assignment and one observation per datum. The observations share and all component parameters. In the unrolled DAG each is a parent of every : the conditional table for queries the component selected by . Conditional on shared parameters, pairs are generated independently. Marginalizing shared random parameters can make observations dependent.
Ancestral sampling traverses the DAG in topological order and draws each variable from its conditional using already-generated parents. By the multiplication rule, the probability of a complete configuration is exactly the product of those conditionals. To calculate an exact posterior, enumerate unobserved values and normalize; cost grows exponentially with the number of variables even when the graph is compact.
For query , with hidden variables , enumeration calculates and divides by . Do not sample only queried variables while ignoring evidence: ancestral samples come from the joint, not automatically from the posterior. A simple option rejects samples incompatible with evidence, but rare evidence wastes almost all samples. Later, variable elimination reuses intermediate sums and avoids enumerating many complete configurations.
Learn the tables
With independent complete data, log likelihood decomposes by family:
if . Here identifies a parent configuration and a child state. If , the row is not identified by maximum likelihood. An unobserved cell in a row with data receives zero probability and can make a posterior vanish.
For parameter learning, a Dirichlet prior per row with positive parameters is conjugate: posterior parameters are . Its mean is . The interior MAP mode is only if all posterior parameters exceed one; the interior formula does not apply at the boundary. BDeu distributes equivalent sample size uniformly over the cells in each family. The smoothed posterior mean and MAP mode are distinct estimators.
For example, a binary row with counts and Dirichlet prior has posterior . The mean probability of the second state is , while the interior mode is . By contrast, with uniform prior and zero cases for one state, the mode can lie on the boundary and does not smooth that zero. A prior with parameters below one can concentrate density toward the boundary: do not interpret every positive pseudocount as guaranteeing an interior mode.
Family decomposition requires complete data and independently parameterized rows. With hidden variables, family counts are unknown: integrate or estimate latent assignments, as in EM. Learning structure is a separate task: here the DAG is fixed and only its tables are estimated.
Lab: a discrete network from scratch
The code uses the figure’s model. The class calculates joint mass, samples in topological order and answers queries by enumeration. The ball uses the algorithm above.
r, s = .3, .4
q00, q10, q01, q11 = .05, .8, .9, .99
wet = (1-r)*(1-s)*q00 + r*(1-s)*q10 + (1-r)*s*q01 + r*s*q11
print("P(mojado), P(aspersor | mojado), P(aspersor | mojado,lluvia):",
wet, s*((1-r)*q01+r*q11)/wet, s*q11/((1-s)*q10+s*q11))
print("cadena:", .8*.9+.2*.1, .2*.9+.8*.1)
print("parámetros:", 2**30-1, sum(2**p for p in [0,1,1,2,2,2,3,3,3,3]))
print("posterior y MAP Dirichlet:", 3/8, 2/6)import itertools
import numpy as np
class BayesNet:
def __init__(self, parents, probs):
self.parents, self.probs = parents, probs
self.nodes = list(parents) # orden topológico
assert all(p in self.nodes[:i] for i, n in enumerate(self.nodes)
for p in parents[n])
def joint(self, values):
out = 1.0
for n in self.nodes:
q = self.probs[n][tuple(values[p] for p in self.parents[n])]
out *= q if values[n] else 1 - q
return out
def sample(self, size, seed=0):
rng = np.random.default_rng(seed)
rows = []
for _ in range(size):
row = {}
for n in self.nodes:
q = self.probs[n][tuple(row[p] for p in self.parents[n])]
row[n] = int(rng.random() < q)
rows.append(row)
return rows
def query(self, event, evidence):
num = den = 0.0
for bits in itertools.product((0, 1), repeat=len(self.nodes)):
row = dict(zip(self.nodes, bits))
if any(row[k] != v for k, v in evidence.items()):
continue
p = self.joint(row)
den += p
if all(row[k] == v for k, v in event.items()):
num += p
if den == 0:
raise ValueError("Evidencia imposible")
return num / den
def separated(self, X, Y, Z):
parents = self.parents
children = {n: [] for n in self.nodes}
for child, ps in parents.items():
for p in ps:
children[p].append(child)
ancestors, todo = set(Z), list(Z)
while todo:
for p in parents[todo.pop()]:
if p not in ancestors:
ancestors.add(p); todo.append(p)
queue = [(x, 'up') for x in X]
seen, reached = set(), set()
while queue:
n, direction = queue.pop()
if (n, direction) in seen:
continue
seen.add((n, direction))
if n not in Z:
reached.add(n)
if direction == 'up' and n not in Z:
queue.extend((p, 'up') for p in parents[n])
queue.extend((c, 'down') for c in children[n])
elif direction == 'down':
if n not in Z:
queue.extend((c, 'down') for c in children[n])
if n in ancestors:
queue.extend((p, 'up') for p in parents[n])
return not bool(reached & set(Y))
parents = {'A': [], 'S': [], 'T': ['A'], 'L': ['S'], 'B': ['S'],
'E': ['T', 'L'], 'X': ['E'], 'D': ['E', 'B']}
probs = {'A': {(): .01}, 'S': {(): .5},
'T': {(0,): .01, (1,): .05},
'L': {(0,): .01, (1,): .1},
'B': {(0,): .3, (1,): .6},
'E': {(0,0): 0., (0,1): 1., (1,0): 1., (1,1): 1.},
'X': {(0,): .05, (1,): .98},
'D': {(0,0): .1, (0,1): .8, (1,0): .7, (1,1): .9}}
net = BayesNet(parents, probs)
print("masa total:", sum(net.joint(dict(zip(net.nodes, bits)))
for bits in itertools.product((0, 1), repeat=8)))
print("T y L sin evidencia:", net.separated({'T'}, {'L'}, set()))
print("T y L dado X:", net.separated({'T'}, {'L'}, {'X'}))
print("P(T=1 | X=1):", net.query({'T': 1}, {'X': 1}))samples = net.sample(20000, seed=4)
def empirical(event, evidence):
subset = [r for r in samples if all(r[k] == v for k, v in evidence.items())]
return sum(all(r[k] == v for k, v in event.items()) for r in subset) / len(subset)
print("P(T=1) exacta y muestra:", net.query({'T':1}, {}), empirical({'T':1}, {}))
print("P(T=1 | L=1) exacta y muestra:", net.query({'T':1}, {'L':1}),
empirical({'T':1}, {'L':1}))
print("P(T=1 | X=1) exacta y muestra:", net.query({'T':1}, {'X':1}),
empirical({'T':1}, {'X':1}))The sample estimates rather than proves independences; deviations depend on size and seed. Enumeration establishes values for this particular model, while d-separation guarantees independences for every compatible parameterization.
We can check every two-single-node query with any subset of other nodes as evidence. Grouping by the 256 configurations avoids rescanning all samples for each query. To avoid interpreting nearly empty cells, the empirical check uses only strata with at least 50 observations; maximum discrepancy need not be zero.
bits = np.array(list(itertools.product((0, 1), repeat=8)), dtype=int)
weights = np.zeros(256, dtype=int)
for row in samples:
index = sum(row[n] << (7-i) for i, n in enumerate(net.nodes))
weights[index] += 1
checked = 0
max_gap = 0.0
for i in range(8):
for j in range(i+1, 8):
other = [k for k in range(8) if k not in (i, j)]
for mask in range(1 << len(other)):
inds = [k for h,k in enumerate(other) if mask & (1 << h)]
Z = {net.nodes[k] for k in inds}
if not net.separated({net.nodes[i]}, {net.nodes[j]}, Z):
continue
for vals in itertools.product((0, 1), repeat=len(inds)):
select = np.ones(256, dtype=bool)
for k,v in zip(inds, vals):
select &= bits[:,k] == v
w = weights[select]
if w.sum() < 50:
continue
xi, yj = bits[select, i], bits[select, j]
px = np.dot(w, xi) / w.sum()
py = np.dot(w, yj) / w.sum()
pxy = np.dot(w, xi*yj) / w.sum()
max_gap = max(max_gap, abs(pxy-px*py))
checked += 1
print("estratos evaluados:", checked, "discrepancia máxima:", round(max_gap, 4))Local lab: count tables and pgmpy
The next cell requires local Python with NumPy, pandas and pgmpy. It generates complete data from the same model, fits each row by counts and compares with pgmpy estimators. MLE is assigned a uniform row when it has no data: this is a library convention, not an identified value. BDeu smoothing uses a posterior mean with equivalent sample size 8. Error against the generating tables is mean absolute cell error . One repetition does not prove a universal trend: change the seed and repeat.
The pgmpy documentation distinguishes maximum-likelihood and Bayesian estimation. BDeu adds to each cell before normalizing; this matches the posterior mean, not the interior MAP formula.
import itertools
import numpy as np
import pandas as pd
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator, BayesianEstimator
parents2 = {'A': [], 'S': [], 'T': ['A'], 'L': ['S'], 'B': ['S'],
'E': ['L', 'T'], 'X': ['E'], 'D': ['B', 'E']}
nodes2 = list(parents2)
truth = {'A': {(): .01}, 'S': {(): .5},
'T': {(0,): .01, (1,): .05},
'L': {(0,): .01, (1,): .1}, 'B': {(0,): .3, (1,): .6},
'E': {(0,0): 0., (0,1): 1., (1,0): 1., (1,1): 1.},
'X': {(0,): .05, (1,): .98},
'D': {(0,0): .1, (0,1): .7, (1,0): .8, (1,1): .9}}
def generate(size, seed):
rng = np.random.default_rng(seed)
rows = []
for _ in range(size):
row = {}
for n in nodes2:
row[n] = int(rng.random() < truth[n][tuple(row[p] for p in parents2[n])])
rows.append(row)
return pd.DataFrame(rows, columns=nodes2)
model = DiscreteBayesianNetwork([(p,n) for n, ps in parents2.items() for p in ps])
states = {n: [0, 1] for n in nodes2}
for size in (100, 1000, 10000):
data = generate(size, 19)
mle = MaximumLikelihoodEstimator(model, data, state_names=states)
bayes = BayesianEstimator(model, data, state_names=states)
errors_mle, errors_bayes, zeros = [], [], 0
for n in nodes2:
ps = parents2[n]
configs = list(itertools.product((0, 1), repeat=len(ps)))
m = mle.estimate_cpd(n).get_values()[1]
b = bayes.estimate_cpd(n, prior_type='BDeu', equivalent_sample_size=8).get_values()[1]
for j, config in enumerate(configs):
selected = data
for parent, value in zip(ps, config):
selected = selected[selected[parent] == value]
N = len(selected)
N1 = int(selected[n].sum())
own_mle = N1/N if N else .5
alpha_cell = 8/(2*len(configs))
own_bayes = (N1 + alpha_cell)/(N + 2*alpha_cell)
assert abs(own_mle - m[j]) < 1e-12
assert abs(own_bayes - b[j]) < 1e-12
zeros += int(N > 0 and (N1 == 0 or N1 == N))
errors_mle.append(abs(own_mle - truth[n][config]))
errors_bayes.append(abs(own_bayes - truth[n][config]))
print(size, 'error MLE', round(np.mean(errors_mle), 4),
'error BDeu', round(np.mean(errors_bayes), 4),
'filas observadas con un cero', zeros)npm run lab and open the connection link.Exercises
Step 1 of 3. What happens when summing over C?
Step 1 of 3. Which factors contain X?
def d_separated(parents, X, Y, Z):
# tu código
return False