Approximate Inference by Sampling
When exact inference is too expensive, we can simulate the network many times and count. This is the Monte Carlo idea: if you can generate random worlds from a distribution, frequencies converge to probabilities by the law of large numbers. All the methods here are consistent: the estimates converge to the right answer as the number of samples grows.
We'll use the sprinkler network (AIMA Fig. 14.12): Cloudy influences both Sprinkler (the gardener runs it less on cloudy days) and Rain, and Sprinkler and Rain both make the grass wet.
1. Prior (direct) sampling
Sample each variable in topological order (parents first) from its CPT, using the values already sampled for its parents. Each run produces one complete world, drawn exactly from the joint distribution. Example run: Cloudy ~ P(0.5) gives true. Then Sprinkler ~ P(0.1) gives false, Rain ~ P(0.8) gives true, and WetGrass ~ P(0.90) gives true. One sample: [true, false, true, true].
2. Rejection sampling
To estimate \(P(X \mid e)\): generate prior samples, throw away any that disagree with the evidence, and count among the rest. It's simple and correct, but wasteful. The fraction kept is \(P(e)\), which drops exponentially as evidence accumulates. With evidence probability 0.001, you throw away 99.9% of your work.
3. Likelihood weighting
Don't sample the evidence variables. Fix them to their observed values, and multiply a weight by the likelihood of each fixed value given its parents. Every sample is used, but weighted by how well it explains the evidence:
$$ w = \prod_{E_i \in \text{evidence}} P(e_i \mid \text{parents}(E_i)). $$Estimate: \(P(x \mid e) \approx \frac{\sum_{\text{samples with } x} w}{\sum_{\text{all samples}} w}\).
The weakness: evidence only affects the sampling of its descendants. If the evidence is downstream (an effect) and very unlikely, most samples get tiny weights, and a few dominate the estimate.
4. Gibbs sampling (MCMC)
A completely different idea. Start from any world consistent with the evidence. Then repeatedly pick a non-evidence variable and resample it given all the others. Thanks to the Markov blanket property (§7.2), that only depends on its Markov blanket:
$$ P(x_i \mid \text{everything else}) \;\propto\; P(x_i \mid \text{parents}(X_i)) \prod_{Y_j \in \text{children}(X_i)} P(y_j \mid \text{parents}(Y_j)). $$This is a random walk through the space of worlds, a Markov chain. After a "burn-in" period, the fraction of time it spends in each world equals that world's posterior probability.
Gibbs sampling is a local search (Ch 3) through the space of complete assignments, where moves are random and the walk is designed to visit states in proportion to their probability rather than to maximize anything. Simulated annealing (§3.2) is a close relative. It uses the same "random neighbour + probabilistic acceptance" machinery, plus a temperature that gradually forces the walk toward the maximum.
Compare them
Query: P(Rain | Sprinkler = true, WetGrass = true). The exact answer by enumeration is 0.3204.
import random
# Sprinkler network (AIMA Fig 14.12): Cloudy -> Sprinkler, Cloudy -> Rain, (Sprinkler, Rain) -> WetGrass
ORDER = ["Cloudy", "Sprinkler", "Rain", "WetGrass"]
def p_true(var, s):
if var == "Cloudy": return 0.5
if var == "Sprinkler": return 0.1 if s["Cloudy"] else 0.5
if var == "Rain": return 0.8 if s["Cloudy"] else 0.2
return {(True, True): 0.99, (True, False): 0.90, (False, True): 0.90, (False, False): 0.0}[(s["Sprinkler"], s["Rain"])]
rng = random.Random(0)
def prior_sample():
s = {}
for var in ORDER: # topological order: parents are sampled first
s[var] = rng.random() < p_true(var, s)
return s
def rejection_sampling(query, evidence, n):
kept = [s for s in (prior_sample() for _ in range(n)) if all(s[k] == v for k, v in evidence.items())]
return sum(s[query] for s in kept) / len(kept), len(kept)
def likelihood_weighting(query, evidence, n):
num = den = 0.0
for _ in range(n):
s, w = {}, 1.0
for var in ORDER:
pt = p_true(var, s)
if var in evidence: # don't sample evidence: fix it and weight by its likelihood
s[var] = evidence[var]
w *= pt if evidence[var] else 1 - pt
else:
s[var] = rng.random() < pt
num += w * s[query]; den += w
return num / den
def gibbs(query, evidence, n, burn_in=500):
s = {v: evidence.get(v, rng.random() < 0.5) for v in ORDER}
free = [v for v in ORDER if v not in evidence]
def joint(st):
prob = 1.0
for v in ORDER:
pt = p_true(v, st); prob *= pt if st[v] else 1 - pt
return prob
count = 0
for t in range(n + burn_in):
v = rng.choice(free) # resample one variable given all the others
s[v] = True; p1 = joint(s)
s[v] = False; p0 = joint(s)
s[v] = rng.random() < p1 / (p1 + p0)
if t >= burn_in:
count += s[query]
return count / n
ev = {"Sprinkler": True, "WetGrass": True}
print("exact answer: P(Rain | sprinkler, wetgrass) = 0.3204")
est, kept = rejection_sampling("Rain", ev, 10000)
print("rejection sampling : %.4f (kept %d of 10000 samples)" % (est, kept))
print("likelihood weighting : %.4f" % likelihood_weighting("Rain", ev, 10000))
print("Gibbs sampling : %.4f" % gibbs("Rain", ev, 10000))exact answer: P(Rain | sprinkler, wetgrass) = 0.3204
rejection sampling : 0.3194 (kept 2830 of 10000 samples)
likelihood weighting : 0.3291
Gibbs sampling : 0.3187
All three land within about 0.01 of the truth. Rejection sampling threw away 72% of its samples. (For simplicity, the gibbs function above recomputes the full joint rather than just the Markov blanket. The ratio is the same, because the factors outside the blanket cancel.)
Choose "Cloudy = false, WetGrass = true" with rejection sampling, and watch what fraction of samples survive. Then switch to likelihood weighting and compare how quickly each estimate settles near the green line.
Where do the CPTs come from? Learning from data
So far, the network's numbers have come from an expert. With data, we can learn them. If every variable is observed in every example, the maximum-likelihood estimate of each CPT entry is just a count ratio:
$$ \hat P(X = x \mid \text{parents} = u) = \frac{\#(X = x,\ \text{parents} = u)}{\#(\text{parents} = u)}. $$Each CPT is learned separately: the factorization splits the learning problem into small independent counting problems. With little data, add Laplace smoothing (pseudo-counts) to avoid zero probabilities. That's a prior, i.e. regularization, as in §2.4 and §4.2.
import random
ORDER = ["Cloudy", "Sprinkler", "Rain", "WetGrass"]
def p_true(var, s):
if var == "Cloudy": return 0.5
if var == "Sprinkler": return 0.1 if s["Cloudy"] else 0.5
if var == "Rain": return 0.8 if s["Cloudy"] else 0.2
return {(True, True): 0.99, (True, False): 0.90, (False, True): 0.90, (False, False): 0.0}[(s["Sprinkler"], s["Rain"])]
rng = random.Random(1)
def prior_sample():
s = {}
for var in ORDER:
s[var] = rng.random() < p_true(var, s)
return s
data = [prior_sample() for _ in range(2000)] # pretend this is a log of 2000 observed days
def estimate(var, parent, parent_value, k=1):
"""Maximum-likelihood estimate with add-k (Laplace) smoothing: (count + k) / (total + 2k)."""
rows = [d for d in data if d[parent] == parent_value]
return (sum(d[var] for d in rows) + k) / (len(rows) + 2 * k)
print("P(Rain | Cloudy) true 0.80 learned %.3f" % estimate("Rain", "Cloudy", True))
print("P(Rain | ~Cloudy) true 0.20 learned %.3f" % estimate("Rain", "Cloudy", False))
print("P(Sprinkler | Cloudy) true 0.10 learned %.3f" % estimate("Sprinkler", "Cloudy", True))
print("P(Sprinkler | ~Cloudy) true 0.50 learned %.3f" % estimate("Sprinkler", "Cloudy", False))P(Rain | Cloudy) true 0.80 learned 0.803
P(Rain | ~Cloudy) true 0.20 learned 0.192
P(Sprinkler | Cloudy) true 0.10 learned 0.103
P(Sprinkler | ~Cloudy) true 0.50 learned 0.514
Harder versions of the problem:
- Hidden variables (never observed): use the EM algorithm. Guess the CPTs, infer the hidden variables (E-step), re-estimate by expected counts (M-step), and repeat. It's a local-search method and can get stuck in local optima, just like hill climbing.
- Unknown structure (which arrows?): search over DAGs (hill climbing over add/remove/reverse-edge moves) and score each structure by fit minus a complexity penalty (e.g. BIC). More edges always fit the training data better, so without the penalty you get a fully connected, overfit network. This is the bias–variance tradeoff one final time.
Chapter summary
- A Bayes net = DAG + CPTs. Joint = \(\prod_i P(x_i \mid \text{parents}(X_i))\). This is exponentially more compact than the full joint.
- Build it in causal order for sparse, natural CPTs.
- Chains and forks block when the middle is observed. Colliders block unless the middle or a descendant is observed (explaining away). d-separation generalizes this.
- Exact inference: enumeration (\(O(2^n)\)) and variable elimination (factors, dynamic programming). Linear for polytrees, NP-hard in general.
- Approximate inference: rejection sampling (wasteful), likelihood weighting (weights), Gibbs (MCMC over the Markov blanket).
- Learning CPTs = counting (plus smoothing). Structure learning = search with a complexity penalty.
Look at what Bolt can do now. It learns delivery-time models that generalize (Ch 2). It tunes them by search when gradients aren't available (Ch 3). It reasons about uncertain sensors with Bayes' rule (Ch 4) and Bayes nets (Ch 7). It chooses actions that maximize expected utility (Ch 4–5), plans routes in a slippery world (MDPs), tracks its own location from noisy readings (POMDPs) and explains lateness with readable rules (Ch 6). That is the whole course, and it's also a fair description of a modern autonomous robot. Head to the cheat sheet and study plan to consolidate.