A clinical team considering treatment has to bring together information about the disease and the patient's condition. A probability estimate is easier to examine when the relationships behind it are explicit, so the team can see which evidence the model uses. Bayesian networks provide a way to represent those relationships and update estimates when observations are supplied. One query compares the probability of survival at one year under different treatments.
In practice, the Lung Cancer Assistant built by Sesen and colleagues in 2014 learned from 126,986 LUCADA patients. Its exact concordance with recorded treatments was 0.27, under an objective of maximising survival. We build a synthetic network in pgmpy to query survival under treatment evidence and unpack that comparison.
Quick Win: A Lung-Cancer DAG in Twenty Lines
Seven nodes inspired by Table 1 of the LCA paper, nine directed edges, all discrete. The factorisation collapses what would be a 191-parameter joint distribution into 35 numbers spread across small CPTs.
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination
edges = [
("Smoking", "Histology"),
("Smoking", "PerfStatus"),
("Age", "PerfStatus"),
("PerfStatus", "Treatment"),
("TNM", "Treatment"),
("Histology", "Treatment"),
("TNM", "Survival"),
("Treatment", "Survival"),
("PerfStatus", "Survival"),
]
model = DiscreteBayesianNetwork(edges)
model.add_cpds(*build_cpds()) # see the notebook for the 35 numbers
assert model.check_model()
infer = VariableElimination(model)
profile = {"TNM": 1, "Histology": 0, "PerfStatus": 0} # late-stage NSCLC, good PS
for tx, name in [(0, "surgery"), (1, "chemo-radio"), (2, "palliative")]:
p = infer.query(["Survival"], evidence={**profile, "Treatment": tx},
show_progress=False).values
print(f"do(Treatment={name:11s}): P(alive at 1y) = {p[0]:.2f}")
Output:
do(Treatment=surgery ): P(alive at 1y) = 0.50
do(Treatment=chemo-radio): P(alive at 1y) = 0.45
do(Treatment=palliative ): P(alive at 1y) = 0.25
Three small numbers the registrar can act on. The same network gives you , , or any other query without retraining. That is the practical headline of a Bayesian network: one factorised joint, free probabilistic queries forever.

The next sections unpack what the seven CPTs are doing, why d-separation lets you read independence claims off the picture without any algebra, why the same posterior cannot tell you the causal effect of treatment without one extra assumption, and where structure learning stops being science and starts being a black art.
What Just Happened? The Factorisation, Read Off the Graph
A Bayesian network is two things at once: a directed acyclic graph (DAG) over random variables, and the joint distribution that factorises along it:
For our toy graph, that single line expands to seven factors that you can read straight off the picture above:
Three priors with one parameter each, a 2×2 conditional with two free numbers, a 2×2×2 conditional with four, a 3×2×2×2 conditional with sixteen, and a 2×2×3×2 conditional with eleven. The total is 35 free parameters. A fully connected graph over the same seven binary-or-ternary variables would need numbers. The graph is not just a picture: it is a parameter-saving device, because every absent edge encodes a conditional independence.
CPTs Are Just Tables of Numbers
The Treatment node is the deepest in the network. Its conditional is a single 3×2×2×2 tensor, three rows times eight columns, twenty-four numbers in total. Every column has to sum to one.

The dark surgery cell at "good PS, early stage, NSCLC" (0.70) and the dark palliative cell at "poor PS, late stage, SCLC" (0.80) are the network's encoded clinical priors. In the real LCA, the equivalent CPT was learned from the LUCADA records of 126,986 English patients, then used to query the survival node under counterfactual treatment evidence. This style of model is generative: you can sample from it, you can condition on it, and you can do both consistently because the same CPTs power both directions.
Conditional Independence, by Inspection
The graph also tells you which variables are conditionally independent without doing any algebra. Three primitive cases on three nodes do all the work; once you have these, you have the d-separation algorithm for any DAG.

In the tail-to-tail case, is a common cause: marginally and are dependent because they share a root, but observing makes them independent. In the head-to-tail case is a mediator: same conclusion, conditioning on blocks the chain. The head-to-head case is the one that catches everyone the first time. Marginally and are independent, because they do not share a parent. Conditioning on the collider makes them dependent. The classic example is the fuel-gauge graph: observing that the fuel gauge reads empty makes a flat battery and an empty tank correlated, even though they are independent causes a priori. Explaining away is the colloquial name. We will revisit it in our toy network in a moment.
The general rule, called the d-separation criterion (Pearl 1988), is mechanical: a path is blocked at a non-collider that is in the conditioning set, or at a collider whose descendants are not in the conditioning set. Two sets and are independent given if and only if every path between them is blocked. You can read off arbitrary independence claims with no integrals.
Going Deeper: Parameter Learning, Inference, and Causal Queries
Learning Parameters: MLE in the Discrete Case Is Just Counting
When all parents are observed, the maximum likelihood estimate for a discrete CPT is the empirical conditional frequency. For each parent configuration , count the rows where and the child takes value , divide by the count where . That is the entire algorithm.
from pgmpy.parameter_estimator import DiscreteMLE
empty_model = DiscreteBayesianNetwork(edges)
empty_model.fit(data, estimator=DiscreteMLE())
print(empty_model.get_cpds("PerfStatus").values[0].round(3))
# array([[0.854, 0.665], # P(good PS | Smoking, Age): recovered
# [0.662, 0.404]]) # ground truth: [[0.85, 0.65], [0.70, 0.40]]
Four thousand synthetic patients are enough to recover three of the four conditional probabilities to within 0.02 of the truth. The fourth (poor smoker, young) is off by 0.04 because it has the smallest support in the dataset. This is the entire reason discretisation is so common in clinical Bayesian networks: with discrete parents and discrete children, parameter learning collapses to counting, and finite-sample uncertainty has a closed form.
Bayesian Smoothing Avoids Zero Probabilities
Counting works until a parent configuration has zero observations, at which point MLE returns . The Bayesian fix is a Dirichlet prior on each conditional. The most common choice is BDeu with equivalent sample size :
from pgmpy.parameter_estimator import DiscreteBayesianEstimator
bayes_model = DiscreteBayesianNetwork(edges)
bayes_model.fit(
data,
estimator=DiscreteBayesianEstimator(prior_type="BDeu", equivalent_sample_size=10),
)
The equivalent sample size is the strength of the prior in pseudo-counts. adds the equivalent of ten extra patients distributed uniformly across the parent-child cells, just enough to push every probability away from zero without dominating the data. This is the same Dirichlet-multinomial conjugate update you have seen in Bayesian inference from MLE, extended to a discrete table.
Inference Is Variable Elimination
Once the CPTs are in place, every probabilistic query is a sum over the unobserved variables, weighted by the product of CPTs. For a small network like ours, variable elimination is exact and fast: pick an elimination order, multiply factors that share variables, sum out the eliminated variable, repeat. The cost is exponential only in the largest factor produced during elimination, not in the network size.
from pgmpy.inference import VariableElimination
infer = VariableElimination(model)
infer.query(["Survival"], evidence={"TNM": 1, "PerfStatus": 0}).values
# array([0.425, 0.575]) # P(alive | late stage, good PS), averaging over Treatment
Three lines, no Markov chains, no sampling. For larger networks (hundreds of nodes, dense connectivity), exact inference becomes intractable and you fall back to MCMC or variational methods, but for clinical-scale networks of a dozen variables, variable elimination is what runs in the room.
Causal Queries: Conditioning on Treatment Is Not the Same as Setting It
The headline output of the LCA was a survival probability under a counterfactual treatment choice. That is a causal question, not just a probabilistic one, and the standard observational query is not in general the same as Pearl's interventional .
The two coincide in our toy network only because of how we condition. Treatment has three observed parents (PerfStatus, TNM, Histology), and the back-door criterion (Pearl 2009) says that conditioning on a sufficient parent set turns the observational query into the interventional one. Our query in the Quick Win section fixes all three parents, so it is a legitimate -query. If we had left PerfStatus or TNM unobserved, we would be measuring a confounded association instead of a causal effect.

The "BN's own pick" bar (0.42) is what you get if you let the network's own treatment policy decide. The three -bars show what would happen if you overrode that policy. The drop from to is the causal contrast the LCA was designed to surface.
Explaining Away in the Toy Network
The collider trick is not abstract. Survival has three parents in our network: TNM, Treatment, and PerfStatus. Watch what happens when we condition on Survival and then also on Treatment:
infer.query(["PerfStatus"], evidence={"Survival": 1}).values
# array([0.485, 0.515]) # P(poor PS | dead): slightly elevated
infer.query(["PerfStatus"], evidence={"Survival": 1, "Treatment": 2}).values
# array([0.193, 0.807]) # P(poor PS | dead, palliative): sharply elevated
Knowing only that the patient died nudges your belief about poor performance status from a baseline 0.45 to 0.52. Once you also learn that the treatment was palliative, your belief jumps to 0.81: the palliative pathway explains away the death, leaving a strong inference that the patient must have presented with poor performance status. This is the head-to-head pattern from the d-separation panel above, in clinical clothes.
Discretisation Is the Cost of Tractability
The CPT for Treatment has 24 numbers because we discretised all three of its parents. If we had kept FEV1 absolute and FEV1 percent as continuous variables, as the LUCADA data model does, the CPT would have to be replaced with a conditional density over a four-dimensional support. The standard fix is to split the continuous variable into bins (<1.0, 1.0-1.5, 1.5-2.0, >2.0 in the LCA), at the cost of throwing away within-bin variation. The alternative, conditional Gaussian distributions or kernel density estimates, gives you continuity but loses the closed-form Dirichlet-multinomial update and forces a Monte Carlo or variational inference pass even for small networks. The linear-Gaussian case keeps the joint tractable; outside that regime, discretisation is the path of least resistance.
Foundations: Pearl, the Black Art of Structure Learning, and the LCA Paper
Pearl 1988 and the Causal Hierarchy
Bayesian networks are inseparable from Judea Pearl's Probabilistic Reasoning in Intelligent Systems (1988), which introduced the d-separation criterion, the message-passing algorithms for tree-structured networks, and the philosophical commitment that the direction of an edge in a DAG matters even when the joint distribution does not change. In a directed graph , intervening on changes ; in it does not. The factorisation alone cannot tell the two apart.
The Bayesian network is more than a parsimonious specification of a probability distribution. It is a graphical representation of a manufacturing process by which the data could have been generated.
-- Pearl, Causality (2009), §1.4
The 2000 edition of Causality extends d-separation into the do-calculus, the three rules that let you derive interventional from observational distributions whenever a sufficient adjustment set exists. The LCA paper builds on this directly: the LUCADA Bayesian network was used "for carrying out causal interventions on the suggested cancer treatment plan variable" (Sesen et al. 2014, figure 4 caption). That is do-calculus in clinical clothing.
Structure Learning Is Black Art
So far we have assumed the DAG. In practice, getting the right edges is the hard part. The two-class taxonomy is constraint-based versus score-based.
- Constraint-based algorithms (PC, FCI) test for conditional independence in the data and use d-separation in reverse: an edge between and is removed if some conditioning set makes them independent. The output is a partially directed graph (a CPDAG); some edges remain unoriented because data alone cannot pick the direction.
- Score-based algorithms (hill climbing, K2, exact dynamic programming) define a score on DAGs (BIC, BDeu, AIC) and search the space of structures. Hill climbing is the practical workhorse: start from the empty graph or a random DAG, evaluate every legal single-edge addition, removal, and reversal, accept the one that increases the score the most, repeat until no move helps.
from pgmpy.estimators import HillClimbSearch, BIC
hc = HillClimbSearch(data[["Smoking", "PerfStatus", "TNM", "Treatment", "Survival"]])
learned = hc.estimate(scoring_method=BIC(data), max_indegree=4)
print(list(learned.edges()))

Six accepted edges, score climbing every step, terminating when no remaining add/remove/reverse improves BIC. That is the clean version. The dirty version is everything you cannot see in this animation: the search space is super-exponential in the node count (1.4 million DAGs over five nodes, a 19-digit number over ten), local optima are dense, the score landscape is sensitive to the prior strength , and at finite sample sizes the algorithm cannot tell some pairs of DAGs apart in principle.
Statistical Indistinguishability: The Ceiling on What Data Can Tell You
Three DAGs , , and all imply the same single conditional independence and exactly zero marginal independencies. They are Markov equivalent: their factorisations cover the same family of joint distributions. No amount of observational data can pick between them.

Verma and Pearl (1990) proved that two DAGs are observationally equivalent if and only if they have the same skeleton and the same v-structures (head-to-head colliders without a connecting edge). Anything outside that invariant is unidentifiable from data alone. To break the tie you need either a randomised experiment, an instrumental variable, or a structural prior. The LCA paper handled this by building expert-elicited and temporal constraints into the score-based search: death cannot cause lung cancer, treatment cannot precede diagnosis, and so on. Without those priors, the algorithm would happily place an arrow from one-year survival back to TNM stage.
The LCA Numbers, in Context
The Sesen et al. (2014) paper reports four headline metrics on a 4,020-patient subset of LUCADA:
| Metric | Rule-based CDS | Probabilistic (BN) CDS |
|---|---|---|
| Exact concordance with recorded treatment | 0.57 | 0.27 |
| Partial concordance | 0.79 | 0.76 |
| 1-year survival prediction AUC | not applicable | 0.81 ± 0.03 |
| Treatment-recommendation pattern | follows guideline rules | favours multimodal surgery |
The probabilistic concordance looks worse on the surface (0.27 vs 0.57) but the clinical interpretation is the opposite. The BN was trained to maximise survival, not to imitate the recorded plan. It systematically suggested aggressive multimodal surgical regimens (induction-chemo-then-surgery, surgery-with-adjuvant-chemo) for early-stage patients where guidelines and observed practice favoured surgery alone. The 0.81 survival AUC is the metric the BN was actually designed for, and 0.81 on a real-world cohort with thirteen variables is non-trivial. The 0.27 number is what happens when you hold a survival model accountable to a guideline-driven gold standard. The two are answering different questions.
Limitations and When to Reach for Something Else
Bayesian networks are interpretable, generative, and queryable, but they are not a free lunch.
- Discretisation pain. Continuous variables either get binned (losing information) or break the closed-form Dirichlet update. Linear-Gaussian and conditional-Gaussian mixtures recover tractability but at the cost of expressiveness; outside those, you are doing Monte Carlo inference even on small networks.
- CPT explosion with many parents. A node with discrete parents needs parameters in its CPT. Modelling treatment as a function of fifteen patient features is hopeless without parameter sharing (logistic-style parameterisation, noisy-OR, or tree-structured CPTs).
- Structure learning is unsolved at scale. Beyond a few dozen nodes, hill climbing and PC both lose to specialised score-equivalence algorithms (GES, RFCI), and even those need carefully elicited priors. The LCA paper explicitly calls structure learning "more of a black art than science", echoing a sentiment that has not aged badly.
- Causal direction is not identifiable from data alone. Markov equivalence is a hard ceiling. Any system that promises to "discover causality from observational data" without expert priors or interventions is selling something.
- No deep representation. The CPT is a literal lookup table. Bayesian networks do not learn embeddings; for high-dimensional unstructured data (text, images), a Bayesian neural network or a Gaussian process gives you the Bayesian story without the discretisation tax.
When to reach for a Bayesian network: low-dimensional, interpretable, regulated domains (clinical decision support, fault diagnosis, risk modelling) where transparency matters more than raw predictive accuracy and where domain experts can provide structural priors. When to skip it: anywhere the joint is high-dimensional, continuous, and you do not need to expose the factorisation to a human.
Interactive Tools
- Bayes' Theorem Calculator: Build intuition for the conditional-update machinery that runs every variable elimination query in this post.
- Medical Statistics Calculator: Sensitivity, specificity, predictive values: the metrics a clinical decision support system has to report alongside its survival predictions.
- Markov Chain Simulator: A first-order Markov chain is a Bayesian network where every node depends only on its predecessor; this tool gives you the dynamic counterpart to the static DAG above.
- Kaplan-Meier Calculator: estimate and compare survival curves interactively
- Medical Statistics Calculator: compute sensitivity, specificity, and diagnostic metrics
Related Posts
- Bayesian Model Comparison: The Evidence Framework: The marginal-likelihood machinery that the BDeu prior and structure scores all descend from.
- Bayesian Neural Networks: Laplace and the Evidence Framework: The neural counterpart to graphical models; same Bayesian tooling, different parametric story.
- MCMC Metropolis-Hastings: The Island Hopping Guide: When variable elimination becomes intractable, MCMC is the standard fallback for posterior queries.
- From MLE to Bayesian Inference: The conjugate-prior background that makes the Dirichlet-multinomial update in this post work.
- Text Classification with TF-IDF and Naive Bayes: Naive Bayes is the simplest possible Bayesian network: a single class node with all features as conditionally-independent children.
- Clinical Decision Support, Before and After Language Models: What happened to the rule-based half of the Lung Cancer Assistant once retrieval removed the cost of encoding a guideline by hand.






