Module contents
Lesson 2 of 27Core 100 min

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 2302^{30} configurations. A joint table needs 230−1=1 073 741 8232^{30}-1 = 1\,073\,741\,823 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.

InteractiveThe price of an edge
1234
7
Network
15
Joint
Add an edge to list pairwise separations the graph no longer guarantees.
4
Local parameters7
Full joint table15
Nodes and edges4 and 3
Add edges and compare local parameters with the complete table. Each extra binary parent doubles the rows of its child's table.

A binary node with kk binary parents has 2k2^k parent configurations and one free probability per configuration. In general, if XiX_i has rir_i states and its parents have qiq_i configurations, the network needs ∑iqi(ri−1)\sum_i q_i(r_i-1) 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

p(x1,…,xn)=∏i=1np(xi∣xpa⁡(i)).p(x_1,\ldots,x_n)=\prod_{i=1}^n p(x_i\given x_{\operatorname{pa}(i)}).

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 pp when every separation it predicts implies an independence in pp. The converse, that every independence in pp 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 p(a)p(b∣a)p(a)p(b\given a) and p(b)p(a∣b)p(b)p(a\given b). 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 A→BA\to B choose the same distribution for BB in every row of the table for AA. Then A⊥ ⁣ ⁣ ⁣⊥BA\indep B 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 A→C→BA\to C\to B, observing CC blocks the path: once the intermediate state is known, the source adds no information about the destination. The same holds for fork A←C→BA\leftarrow C\to B. Collider A→C←BA\to C\leftarrow B is the reverse: the path is blocked if neither CC 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 A→C←BA\to C\leftarrow B both arrows point to CC and form a collider. In A←C→BA\leftarrow C\to B they leave CC, making CC 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 XX and YY by ZZ, 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.

InteractiveBayes ball
ASTLBEXD
Step 6 of 6: D
Blue: explored paths; filled gray: observed; magenta: query. The numerical value summarizes every possible evidence configuration with positive probability.
Evidence emptyP(T=1)P(L=1)P(T=1, L=1)Product
none0.01040.05500.00060.0006
Graphical criterionseparated
Maximum exact conditional discrepancy0.00000
Query T and L. Observe E and then only X: both open the collider. Blue lines show the ball's exploration, not proof that each line belongs to a complete path between the endpoints.

The figure’s network uses eight binary variables in order A,S,T,L,B,E,X,DA,S,T,L,B,E,X,D: A→TA\to T, S→L,BS\to L,B, T,L→ET,L\to E, E→X,DE\to X,D and B→DB\to D. Its conditionals form an explicit model: p(A=1)=0.01p(A=1)=0.01, p(S=1)=0.5p(S=1)=0.5, p(T=1∣A)=0.05p(T=1\given A)=0.05 if A=1A=1 and 0.010.01 otherwise; p(L=1∣S)=0.1p(L=1\given S)=0.1 or 0.010.01; p(B=1∣S)=0.6p(B=1\given S)=0.6 or 0.30.3; E=T∨LE=T\lor L; p(X=1∣E)=0.98p(X=1\given E)=0.98 or 0.050.05; and p(D=1∣E,B)p(D=1\given E,B) is 0.1,0.8,0.7,0.90.1,0.8,0.7,0.9 for (E,B)=(0,0),(0,1),(1,0),(1,1)(E,B)=(0,0),(0,1),(1,0),(1,1). The numerical table enumerates all 256 configurations and shows the maximum over possible values of ZZ of ∣p(x=1,y=1∣z)−p(x=1∣z)p(y=1∣z)∣|p(x=1,y=1\given z)-p(x=1\given z)p(y=1\given z)|. A numerical zero confirms independence in this model but does not prove faithfulness for any other.

Reachability. Before traversal, mark the ancestors of ZZ, including ZZ. 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 O(∣V∣+∣E∣)O(|V|+|E|). If an unobserved target is reachable, an active path exists. For sets, initialize a ball per node of XX.

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 RR and sprinkler SS, with wet grass WW 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.

InteractiveOne explanation competes with another
00.20.40.60.8Before0.4Wet0.692Wet and rain0.4521
0.30
0.40
0.05
0.80
0.90
0.99
P(wet)0.536
P(sprinkler | wet, rain)0.452
Change the priors and four probabilities of wet grass. Compare sprinkler probability before seeing the grass, on seeing it wet, and after also learning that it is raining.

By Bayes, if s=p(S=1)s=p(S=1) and qrs=p(W=1∣R=r,S=s)q_{rs}=p(W=1\given R=r,S=s),

p(S=1∣W=1,R=1)=sq11sq11+(1−s)q10.p(S=1\given W=1,R=1)=\frac{s q_{11}}{s q_{11}+(1-s)q_{10}}.

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, p(W=1)=0.5358p(W=1)=0.5358: add the four joint rain-sprinkler probabilities weighted by the row’s wetness probability. Sprinkler probability given wetness is 0.4(0.7⋅0.9+0.3⋅0.99)/0.5358≈0.69200.4(0.7\cdot0.9+0.3\cdot0.99)/0.5358 \approx 0.6920. If rain is also known, the formula above gives approximately 0.45210.4521. Both exceed prior 0.40.4 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 XX has a Markov blanket comprising its parents, children and its children’s other parents. Given the blanket, XX is independent of the rest of the network at blanket values with positive probability. In the factorization the only factors containing xx are p(x∣pa⁡(X))p(x\given \operatorname{pa}(X)) and its children’s factors. With the blanket fixed, the product of all other factors is constant in xx 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 EE is {T,L,X,D,B}\{T,L,X,D,B\}: T,LT,L are its parents, X,DX,D its children and BB the other parent of DD. Given these five nodes, AA and SS add no information about EE. 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 π\pi sets assignment probabilities, each component has parameter θk\theta_k, and each datum generates zi∼Categorical⁡(π)z_i\sim\operatorname{Categorical}(\pi) followed by xi∼p(xi∣θzi)x_i\sim p(x_i\given\theta_{z_i}). The joint conditional on π,θ\pi,\theta is ∏ip(zi∣π)p(xi∣zi,θ)\prod_i p(z_i\given\pi)p(x_i\given z_i,\theta). If they are also random, multiply their priors. The ziz_i are latent if unobserved; that does not prevent including them in the generative story.

Notice two uses of plates. The plate of size KK replicates component parameters; the plate of size NN replicates one assignment and one observation per datum. The NN observations share π\pi and all component parameters. In the unrolled DAG each θk\theta_k is a parent of every xix_i: the conditional table for xix_i queries the component selected by ziz_i. Conditional on shared parameters, pairs (zi,xi)(z_i,x_i) are generated independently. Marginalizing shared random parameters can make observations dependent.

InteractiveUnroll a mixture
z1x1z2x2z3x3πθ1θ2
The K parameters θ are parents of every observation: assignment zᵢ determines which one is used. Shaded circles are observed data.
Representation
3
2
Assignments and data3 + 3
Component parameters2
Change the number of observations and components. Identify the shared block, each latent assignment and each observation.

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 p(Q=q∣E=e)p(Q=q\given E=e), with hidden variables HH, enumeration calculates ∑hp(q,e,h)\sum_h p(q,e,h) and divides by ∑q′,hp(q′,e,h)\sum_{q',h}p(q',e,h). 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:

log⁡L=∑i∑j=1qi∑k=1riNijklog⁡θijk,θ^ijkMLE=NijkNij,\log L=\sum_i\sum_{j=1}^{q_i}\sum_{k=1}^{r_i} N_{ijk}\log\theta_{ijk}, \qquad \hat\theta_{ijk}^{\mathrm{MLE}}=\frac{N_{ijk}}{N_{ij}},

if Nij>0N_{ij}>0. Here jj identifies a parent configuration and kk a child state. If Nij=0N_{ij}=0, 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 αijk\alpha_{ijk} is conjugate: posterior parameters are αijk+Nijk\alpha_{ijk}+N_{ijk}. Its mean is (Nijk+αijk)/(Nij+∑kαijk)(N_{ijk}+\alpha_{ijk})/(N_{ij}+\sum_k\alpha_{ijk}). The interior MAP mode is (Nijk+αijk−1)/(Nij+∑kαijk−ri)(N_{ijk}+\alpha_{ijk}-1)/(N_{ij}+\sum_k\alpha_{ijk}-r_i) only if all posterior parameters exceed one; the interior formula does not apply at the boundary. BDeu distributes equivalent sample size α\alpha uniformly over the riqir_iq_i cells in each family. The smoothed posterior mean and MAP mode are distinct estimators.

For example, a binary row with counts (3,1)(3,1) and Dirichlet prior (2,2)(2,2) has posterior (5,3)(5,3). The mean probability of the second state is 3/83/8, while the interior mode is (3−1)/(8−2)=1/3(3-1)/(8-2)=1/3. By contrast, with uniform prior (1,1)(1,1) 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.

[ ]Check numerical examplesBrowser
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)
[ ]Network and exact queriesBrowser
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}))
[ ]Sampling and empirical verificationBrowser
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.

[ ]Check predicted separationsBrowser
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 p(X=1∣pa⁡(X))p(X=1\given\operatorname{pa}(X)). One repetition does not prove a universal trend: change the seed and repeat.

The pgmpy documentation distinguishes maximum-likelihood and Bayesian estimation. BDeu adds α/(riqi)\alpha/(r_iq_i) to each cell before normalizing; this matches the posterior mean, not the interior MAP formula.

[ ]MLE and BDeu versus pgmpyLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Quiz
In A → C ← B and C → D, what happens to the path between A and B when D is observed?
Quiz
In A → C → B, what separation is guaranteed by observing C?
Quiz
In A ← C → B, with no evidence, are A and B d-separated?
Quiz
In A → C ← B, with no evidence, what does the graph guarantee?
Quiz
In A → C ← B, with C observed, what can be concluded from the graph alone?
Quiz
In A → C → B and C → D, D is observed but C is not. Is the path from A to B blocked?
Numeric
Given P(S=1)=0.4, P(W=1 | R=1,S=0)=0.8 and P(W=1 | R=1,S=1)=0.99, calculate P(S=1 | W=1,R=1), assuming R and S are independent.
Numeric
A network has ten binary nodes with 0, 1, 1, 2, 2, 2, 3, 3, 3 and 3 parents. How many free parameters does it have?
Proof
Prove: In A → C ← B, A and B are marginally independent but may be dependent given C.
0
Consider discrete variables and a joint distribution factorizing on that graph.

Step 1 of 3. What happens when summing over C?

Proof
Prove: X is independent of nodes outside its blanket given the blanket.
0
The distribution factorizes on a finite DAG and is conditioned on a blanket value with positive probability.

Step 1 of 3. Which factors contain X?

CodeReachability in a DAG
Implement d_separated(parents, X, Y, Z). parents is a dictionary from nodes to parent lists; X, Y and Z are disjoint sets. Return True if X and Y are d-separated by Z. Tests compare with path enumeration for all four-node DAGs respecting order 0, 1, 2, 3 and all single-node queries.
def d_separated(parents, X, Y, Z):
  # tu código
  return False
Shift+Enter to run
Key idea
A DAG and its conditionals define a joint distribution; d-separation guarantees independences for every compatible parameterization. Inference conditions that joint, while learning estimates its tables from data.