🕸️ Bayesian Networks
💥 Joint distributions that are too large
In the chapter on probability we saw that a joint distribution (a table with a probability for every possible combination of variables) contains everything you can know about those variables: you can derive every marginal or conditional probability from it. Below you see such a table for four yes/no variables on a summer day: whether it is cloudy, whether the sprinkler is on, whether it rains and whether the grass is wet.
Four variables already give 16 rows, and every extra yes/no variable doubles the table. Suppose you want to build a medical diagnosis system with 16 yes/no variables: symptoms, test results, lifestyle factors and so on. Then the table has rows, and you have to estimate 65,535 probabilities from data (one fewer than the number of rows, because all the probabilities add up to 1, which fixes the last one automatically). If you want to see at least 10 examples for every row to estimate its probability reliably, you need more than half a million patients. And that is only for 16 variables with two values each. Real systems have hundreds of them, often with more than two possible values.
So the full table is usually far too large to write down, let alone to learn from data.
Fortunately, in the real world not everything depends on everything else. Whether it rains depends on the clouds. Whether the grass is wet depends on the rain and on the sprinkler. But once you know whether it rained and whether the sprinkler was on, the clouds add nothing more to the question of whether the grass is wet. In this way, most variables have only a handful of direct influences.
Bayesian networks exploit exactly that. You draw which variables influence each other directly, and you only keep probabilities for those direct influences. That way you describe the same probability distribution with a fraction of the numbers.
🌐 Bayesian networks
🌧️ The sprinkler example
Below you see the same probability distribution as in the table above, but now as a Bayesian network. Every circle is a variable and every arrow a direct influence: cloud cover influences both the rain and the sprinkler (you are less likely to turn the sprinkler on when it is cloudy), and rain and sprinkler both make the grass wet.
Click a node to view and adjust its probability table. Notice that "Wet grass" has the largest table, because that node depends on the most other variables.
Instead of one big table, every node now has a small table of its own. It gives the probability of the node for every combination of values of the nodes that send an arrow to it. From now on we write such a probability with the value next to it, as in the demo: is the probability that it is cloudy and the probability that it is not cloudy. In the chapter on probability those same probabilities are written simply as and .
- Cloudy has no incoming arrows. You fill in only one probability: .
- Sprinkler and Rain each depend only on Cloudy. Each gets two probabilities: one for when it is cloudy and one for when it is not.
- Wet grass depends on Sprinkler and Rain. That gives four combinations, so four probabilities.
From the complement rule we know that the probability that something does not happen equals 1 minus the probability that it does happen. That is why the probability of ✅ is enough for each row: .
| Node | Parents | Rows in the probability table | Parameters |
|---|---|---|---|
| Cloudy | none | 1 | |
| Sprinkler | Cloudy | 2 | |
| Rain | Cloudy | 2 | |
| Wet grass | Sprinkler, Rain | 4 | |
| Total | 9 |
Together that makes probabilities. Because together these probabilities define the model, we call them the parameters of the model. The full table above has 15 of them (16 rows, minus one because they add up to 1). That seems a modest gain, but you will soon see that the difference becomes huge with more variables.
In general: a yes/no node with incoming arrows has a table with rows (one per combination of values of those nodes), and therefore parameters.
📖 Definitions
A Bayesian network is a directed graph: a diagram with nodes that are connected by arrows. An arrow from A to B means: "A has a direct influence on B".
A Bayesian network is a graphical model that consists of:
- 🟢 A set of nodes that each represent a variable (for example "Cloudy", "Rain", "Wet grass").
- ↘️ A set of directed arrows between nodes. An arrow from A to B means that A has a direct influence on B.
- 🧮 For each node, a conditional probability table that says how likely each value of the node is, given the values of its parents.
The arrows must not form a cycle: following the arrows, you can never get back to the node where you started.
This way you model explicitly which variables depend directly on each other. This saves parameters in the model, and therefore also the data needed to estimate those parameters.
The parents of a node are all the nodes with an arrow pointing to that node. In the sprinkler example, "Cloudy" is the parent of "Sprinkler" and of "Rain", and "Wet grass" has two parents: "Sprinkler" and "Rain".
Usually you draw the arrows from cause to effect, because then the network reads most naturally and the probabilities are easiest to estimate. That is not strictly necessary: sometimes you only know that two variables are related, not that one causes the other. Formally, an arrow only says that in the model one variable depends directly on the other.
🔗 What depends on what?
The biggest saving lies in what is not in the network: which direct connections are missing. "Wet grass" has only "Sprinkler" and "Rain" as parents, and no arrow from "Cloudy". That means: as soon as you know whether the sprinkler was on and whether it rained, the clouds no longer change the probability of wet grass. In mathematical terms:
The clouds do influence the grass, but only through the rain and the sprinkler. This is called conditional independence.
Two variables are conditionally independent given a third if, once you know that third one, they tell you nothing more about each other. In a Bayesian network this means: if you know the parents of a node, information about its grandparents or more distant ancestors adds nothing more.
Try it yourself in the network below:
- Click ✅ or ❌ on "Cloudy". The probability of wet grass changes along with it, because the clouds influence sprinkler and rain.
- Now also fix "Sprinkler" and "Rain" to ✅ or ❌.
- Switch between ✅ and ❌ on "Cloudy" again: the probability of wet grass no longer moves. You can even change the probabilities of "Cloudy" and "Wet grass" without one still affecting the other. Once the parents are fixed, the grandparent no longer matters.
- Use the drop-down menu to find the same effect in the other networks: which node stops mattering once you fix the parents of another node?
Such fixed values are called evidence: things you have measured or seen. This is how an AI system uses a Bayesian network: it fills in what it knows (sensor readings, symptoms, test results) and the network computes how likely the rest becomes. A doctor, for example, enters a fever, a cough and a negative flu test, and reads off how likely flu or another condition still is.
📉 Taming exponential growth
Back to the diagnosis system with 16 yes/no variables. How many parameters do you save there?
- Full joint distribution: parameters.
- Bayesian network: suppose every variable has at most 3 parents. Then no node has a probability table with more than rows, and so at most 8 parameters (per row only the probability of ✅). For 16 nodes that makes at most . In reality even slightly fewer: because the arrows cannot form a cycle, you can always order the nodes so that every arrow points from an earlier node to a later one. The first node then has no parents, the second at most one and the third at most two, which brings the total to .
From 65,535 to 111: almost 600 times fewer numbers, and therefore also that much less data to estimate them.
Explore the difference below. Set how many variables there are (), how many values each variable can take () and the maximum number of parents a variable has ().
- For the sprinkler example, set to 4 and to 2 (the demo then shows 11 instead of 9: it counts the maximum, while Sprinkler and Rain have only one parent here).
- Then increase : the savings factor grows faster and faster. In the chart below the sliders you see the number of parameters of the full table rise exponentially, while the Bayesian network (with a fixed maximum number of parents) grows roughly linearly.
The y-axis of the chart below is logarithmic: every step on the axis means multiplying by the same factor (for example 1, 10, 100, 1,000, ...) instead of adding the same amount. That is why exponential growth shows up as a straight line on such an axis: the straight line for the full joint distribution therefore means exponential growth.
🧮 Computing with a Bayesian network
A Bayesian network contains fewer numbers than the full table, but not less information. Everything you could compute from the large table, you can also get from the network.
✖️ From small tables to one big probability
How likely is one complete situation, for example (Cloudy=✅, Sprinkler=❌, Rain=✅, Wet grass=✅)? You walk through the network from top to bottom and, at every node, multiply by the probability you read off in its table, given the values of its parents:
Multiplied: . That is exactly the probability in that row of the large table. This way you can rebuild the whole table row by row: the network contains the same probability distribution, in a more compact form. You can see this as a form of compression: just as a zip file contains the same data as the original but is smaller, a Bayesian network contains the same probability distribution as the full table, but with fewer parameters.
Because you can recover the full joint distribution, a Bayesian network also lets you compute every other probability you learned about in the chapter on probability: marginal probabilities, conditional probabilities and Bayes' theorem.
The probability of a complete combination of values is the product of the probabilities from all the conditional probability tables: for each node you take the probability of its value, given the values of its parents. A node without parents simply contributes its own probability.
For the sprinkler example, the chain rule reads:
In a Bayesian network, every factor conditions only on the parents of that node. In general, for variables:
Here is the product symbol (multiply all the terms, just as adds them all up) and is the set of parents of in the network. If a node has no parents, you simply use .
Compare this with the general chain rule from the chapter on probability, which holds for any variables:
There every factor conditions on all the preceding variables. In a Bayesian network every condition that is not a parent drops out, thanks to the conditional independences that the network encodes. That is exactly what keeps the tables small.
In this notation, mind the difference between a variable and a value: the capital stands for the variable with all its possible values, so the formula holds for every combination of values. If you want to compute a concrete probability, you fill in values, such as .
🔮 Inference: asking the network questions
With the network you can now answer all kinds of questions:
- "What is the probability that the grass is wet?" (without any further information)
- "It is cloudy. What is the probability that the grass gets wet?" (from cause to effect)
- "The grass is wet. What is the probability that it rained?" (from effect to cause)
That computation is called inference.
Inference is computing the probability of variables you do not know, based on the variables you have observed. To do so, the network combines all the arrows and probability tables.
Take the smallest network we have: rain and snails on the path. The probability of rain is 30%. If it rains, the probability that you come across snails is 80%; otherwise it is only 10%.
From cause to effect. What is the probability of snails if you do not know yet whether it rains? There are two "routes" to snails: via rain and without rain. You compute the probability of each route with the chain rule and add them up (that is marginalizing over rain):
So the probability of snails is 31%. That is the percentage the demo shows for "Snails out and about" as long as you do not fix anything.
From effect to cause. You see snails on the path. What is the probability that it rained? Now "Snails" is observed and you ask about "Rain", against the direction of the arrow. So you want the conditional probability , and you compute it as in the chapter on probability: the joint probability of rain and snails, divided by the probability of snails. You already computed both numbers above: the joint probability is the "route via rain" (0.24), and the probability of snails is the sum of both routes (0.31). Intuitively: of all the days with snails on the path, 24 out of 31 are rainy days.
The second line is exactly Bayes' theorem: the likelihood from the probability table, times the prior probability , divided by the total probability of the evidence . So the snails make rain a lot more likely: from 30% (prior probability) to 77% (posterior probability). Click ✅ on "Snails out and about" above to check.
In larger networks this computation quickly adds up, because then you have to marginalize over many unobserved variables at once. The computer does that for you: clever algorithms use the structure of the network so they do not have to go through every combination, and for very large networks they switch to approximations.
🔀 Explaining away
An important property of Bayesian networks is explaining away. The idea is intuitive: when you find an explanation for a problem, other explanations become less likely. You do this yourself all the time, for example when you track down a fault. This mechanism plays a big role in fault diagnosis, medical diagnosis and many other applications.
🚗 Example: a car that will not start
Imagine you get into your car in the morning and it will not start. In this simplified example there are two possible causes:
- 🔋 Dead battery: with an empty or broken battery the engine does not start
- ⛽ Empty tank: without fuel the car does not start either
We assume that these two causes are independent of each other: whether your battery is dead has nothing to do with whether your tank is empty. In the real world such an independence assumption is not always literally true, but here it keeps the network simple.
You can model this with a simple Bayesian network of three variables.
For this example we choose the following values: and . The probability that the car will not start depends on both causes, which we store neatly in the table for "🚗 Car will not start":
- ✅ Neither problem: only a 2% chance that the car still will not start (because of another, rare cause), so P(🚗 car will not start=✅ | 🔋 dead battery=❌, ⛽ empty tank=❌) = 0.02
- ⚠️ One problem (a dead battery or an empty tank): a 95% chance, so P(🚗 car will not start=✅ | 🔋 dead battery=✅, ⛽ empty tank=❌) = 0.95 and also P(🚗 car will not start=✅ | 🔋 dead battery=❌, ⛽ empty tank=✅) = 0.95
- 🚨 Both problems: a 99% chance, so P(🚗 car will not start=✅ | 🔋 dead battery=✅, ⛽ empty tank=✅) = 0.99
Now let us follow the reasoning step by step.
Step 1: The car will not start
You notice that the car will not start (set to ✅ below). Without further information you think: "Hmm, my battery is probably dead, but maybe my tank is empty too."
Above you see that setting "🚗 Car will not start" to ✅ makes both possible causes much more likely:
- The probability that your battery is dead goes up (from 15% to 71.6%)
- The probability that your tank is empty also goes up (from 5% to 24.0%)
Step 2: You notice that the battery is dead
Now click ✅ on "Dead battery" in the simulator above (for example, you notice that the headlights and the dashboard stay dark as well). What happens to the probability that your tank is empty?
Intuitively you reason: "Ah, the dead battery probably explains why the car will not start. Then an empty tank is less likely to be the cause."
The probability of an empty tank now goes down (from 24.0% back to 5.2%)!
🌊 The explaining-away effect
This is the explaining-away effect!
- A dead battery and an empty tank are independent (one has no influence on the other).
- But as soon as you observe their common effect (the car will not start), they become conditionally dependent.
- Observing one cause (dead battery) explains the effect (the car will not start), which makes the other cause (empty tank) less likely.
- One cause "explains the other away"!
You reason the same way in all kinds of fault diagnosis, and doctors do it too when they make a diagnosis. As soon as one explanation for a problem is confirmed, alternative explanations become less likely. That holds even when the underlying causes themselves are completely independent of each other.
Explaining away is the phenomenon where confirming one possible cause reduces the probability of other possible causes.
It works in two steps:
- Seeing the effect makes all possible causes more likely.
- Then confirming one cause lowers the probability of the other causes, because the effect has already been "explained".
So two independent variables that can cause a common effect become conditionally dependent as soon as that effect is observed.
You see the same effect in the sprinkler network. Try it yourself in the simulator below, where "Wet grass" is already set to ✅.
- Without evidence: probability of sprinkler = 25%, probability of rain = 50%
- With only "Wet grass": probability of sprinkler = 38%, probability of rain = 74.9% (both up!)
- Now click ✅ on "Rain": the probability of sprinkler drops to 17%
The rain explains the wet grass, which makes the sprinkler less likely as an explanation. Part of that drop does come from ☁️ Cloudy here, the common cause of rain and sprinkler: rain makes clouds more likely, and in cloudy weather the sprinkler is rarely on. You see the explaining away on its own if you also set "Cloudy" to ❌: with only wet grass, the probability of the sprinkler is then 77%, and with rain added only 42%.
🏗️ Designing a network
A Bayesian network does not appear by itself: someone has to decide which arrows to draw and which probabilities go in the tables.
🎯 How many arrows?
Every arrow you draw is a trade-off:
- ➖ Too few arrows: The model is small and fast, but misses relationships. If you leave out the arrow from Cloudy to Rain, the network acts as if those two have nothing to do with each other, and the predictions get worse.
- ➕ Too many arrows: The model can describe more nuances, but every extra parent doubles the probability table of a node. You then need much more data to estimate all those probabilities reliably, and the computations take longer. In the extreme case everything depends on everything else and you are back at the full table.
A good Bayesian network is therefore sparse: you only draw arrows where there is a real, direct influence.
🤔 Where do the arrows and probabilities come from?
In practice there are three ways to build a Bayesian network.
1. 👨⚕️ Expert knowledge. A domain expert (a doctor, engineer or scientist) draws the structure and estimates the probabilities:
- Structure: "Flu causes fever, so there is an arrow from Flu to Fever."
- Probabilities: "About 80% of flu patients have a fever, so P(Fever=✅ | Flu=✅) is about 0.8."
Translating expertise into a network like this is called knowledge elicitation.
2. 📊 Learning from data. If you have a dataset with many observations of all the variables, an algorithm can build (part of) the network by itself.
- Learning the probabilities is the easiest part. Once the structure is fixed, you simply count how often each combination occurs in the data. Suppose you recorded for 1,000 days whether it was cloudy and whether the sprinkler was on. On the 500 cloudy days the sprinkler was on 50 times, so P(Sprinkler=✅ | Cloudy=✅) = 50/500 = 0.1 = 10%. This is called maximum likelihood estimation. If a combination never occurs in the data, you estimate its probability at 0. That is often too extreme: you do not want to rule out rare situations completely. That is what smoothing is for: you pretend that every combination already occurred a few times, so that no probability becomes exactly 0. We look at this more closely in the next chapter, on naive Bayes.
- Learning the structure is much harder. The algorithm has to search the data for the variables that directly influence each other, and the number of possible networks grows faster than exponentially with the number of variables.
3. 🔄 Expert and data. In practice you combine both: an expert draws the arrows, and the data fills in the probabilities or adjusts the expert's estimates. That way you use domain knowledge and measurements together. In medical systems, for example, doctors decide which symptoms and diseases influence each other, and the probabilities are estimated from patient databases.
⚡ Strengths and limitations
💪 Strengths
Bayesian networks are popular because they are powerful and explainable at the same time.
- 🧠 Intuitive and interpretable: You see which variables influence each other, and why a probability rises or falls. You can explain why the model makes a certain prediction by showing the relevant arrows and probabilities.
- 📊 Handling uncertainty: Unlike rule-based systems, Bayesian networks deal well with incomplete or contradictory information. You can often still reason when some variables have not been observed.
- 🔀 Bidirectional reasoning: You can reason from cause to effect as well as the other way around. A doctor can ask both "what is the probability of these symptoms given this disease?" and "what is the most likely cause of these symptoms?".
- 📉 Data-efficient: By making the structure explicit, Bayesian networks can make better predictions with less data than models that have to learn every dependency themselves.
- 🧩 Modular: You can change a node or a relationship without redesigning the whole model, because every node has its own probability table.
- 🧑🏫 Expert knowledge + data: You can combine expert knowledge (the structure of variables and arrows) with data (the parameters in the conditional probability tables) in one model.
🚨 Limitations
But there are limitations too:
- 🏗️ Structure required: You have to know or learn the dependency structure. Sometimes that is obvious, but sometimes it is hard or debatable. A wrong structure leads to wrong conclusions. In the worst case everything depends on everything else and the network no longer offers any advantage over the full joint distribution.
- 📈 Scalability: For large, densely connected networks, computing exact probabilities becomes impossible: there are simply too many combinations to go through. In that case the probabilities are estimated with approximation methods that are faster but less precise.
- 🔢 Discretization: The basic technique works with discrete variables, which have a finite number of possible values, so that they fit in a probability table. There are extensions for continuous variables (such as Gaussian Bayesian networks), but they are more complex.
- 🌀 No cycles: You cannot model feedback loops. You cannot draw an arrow from variable A to variable B if B already has an arrow to A, or to a variable that eventually leads back to A through arrows.
🌍 Where do you come across them?
- 🩺 Medical diagnosis: one of the first major applications. In the late 1980s, the Pathfinder system helped pathologists recognize lymph node diseases from more than a hundred features, and in doing so reached the level of experienced specialists.
- 🖥️ Troubleshooters in software: the wizards in Windows 98 that helped solve printer problems, among other things, were Bayesian networks that inferred the most likely cause from your answers. The same research also helped lay the foundation for the Office Assistant, the well-known paperclip: a Bayesian model tried to understand what you asked it, although its unsolicited tips simply came from fixed rules.
- 🧬 Forensics and genetics: how strongly does DNA evidence point to a suspect, or to a family relationship? Bayesian networks combine the probabilities of all the genes involved and all the possible explanations.
- 🧠 Psychology: cognitive psychologists use Bayesian networks as a model of how people themselves reason about causes. They know the explaining-away effect as discounting: a confirmed cause makes us less inclined to look for a second one.
- 📧 Language and text: the next chapter shows the simplest Bayesian network in action, as a spam filter. The Markov chains with which speech recognition and autocomplete predict the next word are Bayesian networks too, with their nodes in a row.
🏗️ Build your own Bayesian network
Experiment with your own Bayesian networks in the simulator below.
- Click the selector on the left to choose a ready-made network.
- Add your own nodes with the "+ New variable" button and decide which parents the node has.
- If needed, also adjust the other nodes so that they have the new node as a parent.
- Set the probabilities by clicking a node and adjusting its conditional probability table.
- Click "Auto layout" to get a clearer view of the network.
- Set evidence by clicking the ✅❌ buttons and watch how the probabilities change.
🧪 Hands-on
In the demos you fixed evidence and the network computed how likely the rest became. In this Jupyter notebook you do that yourself in Python, with the pyAgrum library. First you build the sprinkler network from this chapter and ask it the same questions. Then you build a Wi-Fi troubleshooter: a network with 22 variables that works out why your laptop or smartphone cannot get a connection, and which check you should do first. You do not need to know how to program: you run the code step by step and change a small piece here and there.

🕹️ Demos
Experiment further with the full simulators and demos featured above.



🗣️ Feedback
Just like machine learning algorithms, we also love learning from your feedback to improve the course.
Let us know how informative and how difficult you found this chapter, and where it could be better.