Sam Austinon December 1, 202612 min read

Bayesian Networks for Beginners: Reasoning Under Uncertainty with pgmpy

Bayesian Networks for Beginners: Reasoning Under Uncertainty with pgmpy
Contents

Figure 1: Bayesian Networks for Beginners: Reasoning Under Uncertainty with pgmpy — a rainy street, which is exactly the kind of evidence a small network is built to reason about

Your phone says 30% chance of rain, your neighbor's lawn is soaked, and your sprinkler schedule is a mystery. So did it rain? Humans guess at this stuff all day, and Bayesian networks let a computer guess properly.

I first tried them on a toy diagnosis problem. My hand-written probability code ballooned into 200 lines of nested loops and one very confused spreadsheet. Then I found pgmpy, and the same model shrank to about 30 lines.

Let me hand you that shortcut.

What Is a Bayesian Network?

A Bayesian network is a graph that models how uncertain things influence each other. Each circle (a node) represents a random variable, like "Rain" or "Fever." Each arrow (an edge) says one variable directly influences another.

Every node also carries a conditional probability table (CPT). The table tells you how likely each outcome is, given the states of the node's parents. Nodes with no parents just list plain probabilities.

Why bother with a graph? Ever tried to write out the joint probability of 20 variables? That table needs over a million entries. The network exploits conditional independence to cut that down to a few small tables.

The Math You Actually Need

Don't panic. You need two ideas, and you probably know both already.

Conditional Probability

P(A | B) means "the probability of A, given that B happened." P(wet grass | rain) sits high. P(wet grass | no rain, sprinkler off) sits near zero.

Bayes' Theorem

Bayes' theorem flips a conditional around:

P(A | B) = P(B | A) × P(A) / P(B)

You see the effect (wet grass) and want the cause (rain). The theorem lets you work backward. A Bayesian network just applies this rule over and over across a whole graph, so you never do it by hand.

Why Bayesian Networks Beat Simple Rules

You can build a diagnosis system with a pile of if-then rules. I tried. It collapsed the moment two symptoms overlapped. Here's why networks win:

  1. They handle missing data. You skip a variable, and the network still reasons with what you gave it.
  2. They update beliefs. New evidence shifts every related probability automatically.
  3. They explain themselves. You trace the arrows and see why the model reached a conclusion.
  4. They combine expert knowledge with data. You draw the structure yourself, then learn the numbers from real data.

Neural networks often give you better raw accuracy on huge datasets. But IMO, Bayesian networks win when data runs thin, or when someone asks "why did the model say that?" and you need a real answer.

Meet pgmpy

pgmpy is a Python library for probabilistic graphical models [3]. It lets you define networks, fill in probability tables, and run inference with a few function calls. You install it with pip install pgmpy.

FYI, pgmpy renamed its main class in recent versions. Older tutorials use BayesianNetwork, while newer releases use DiscreteBayesianNetwork. If one name throws an import error, try the other.

Build Your First Network

We'll model the classic lawn puzzle. Rain might make the grass wet. The sprinkler might make the grass wet. And rain makes you less likely to run the sprinkler.

Step 1: Define the Structure

You list the edges as pairs of parent and child:

from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination

model = DiscreteBayesianNetwork([
    ("Rain", "Sprinkler"),
    ("Rain", "WetGrass"),
    ("Sprinkler", "WetGrass"),
])

Three nodes, three arrows. Rain points at both Sprinkler and WetGrass, and Sprinkler also points at WetGrass.

Step 2: Add the Probability Tables

Rain has no parents, so its table is short. I assume a 20% chance of rain on any given day:

cpd_rain = TabularCPD(
    "Rain", 2, [[0.8], [0.2]],
    state_names={"Rain": ["no", "yes"]},
)

The sprinkler depends on rain. On dry days it runs 40% of the time, and on rainy days it almost never runs:

cpd_sprinkler = TabularCPD(
    "Sprinkler", 2,
    [[0.6, 0.99],
     [0.4, 0.01]],
    evidence=["Rain"], evidence_card=[2],
    state_names={"Sprinkler": ["off", "on"], "Rain": ["no", "yes"]},
)

Wet grass depends on both parents. Each column covers one combination of Rain and Sprinkler:

cpd_wet = TabularCPD(
    "WetGrass", 2,
    [[1.0, 0.1, 0.2, 0.01],
     [0.0, 0.9, 0.8, 0.99]],
    evidence=["Rain", "Sprinkler"], evidence_card=[2, 2],
    state_names={
        "WetGrass": ["no", "yes"],
        "Rain": ["no", "yes"],
        "Sprinkler": ["off", "on"],
    },
)

The column order trips up every beginner, me included. pgmpy walks the evidence variables in the order you list them, with the last one changing fastest. So the columns read: (no rain, off), (no rain, on), (rain, off), (rain, on).

Step 3: Attach and Validate

model.add_cpds(cpd_rain, cpd_sprinkler, cpd_wet)
print(model.check_model())  # True if everything lines up

Always run check_model(). It catches columns that don't sum to 1 and mismatched variable names before they wreck your results.

Ask the Network Questions

Now the fun part. Inference means asking the model questions about its variables, given the evidence you have. pgmpy's VariableElimination class handles the heavy lifting:

infer = VariableElimination(model)
print(infer.query(["Rain"], evidence={"WetGrass": "yes"}))

Before you saw the grass, the chance of rain sat at 20%. After you see wet grass, it jumps to roughly 36%. The evidence made rain more plausible, but the sprinkler still explains a lot of the wetness.

The Explaining-Away Effect

Now tell the model the sprinkler ran:

print(infer.query(["Rain"], evidence={"WetGrass": "yes", "Sprinkler": "on"}))

The rain probability collapses to under 1%. Why? The sprinkler already explains the wet grass, so rain loses its job as the suspect.

This pattern, called explaining away, shows what makes Bayesian networks special. Simple correlation counting never captures it, and I still enjoy watching the numbers drop. :)

Variable Elimination vs. Other Inference Methods

pgmpy offers more than one way to answer a query. Here's how I think about the choice:

  1. Variable elimination: gives exact answers and works well on small to medium networks. Start here.
  2. Belief propagation: gives exact answers on tree-shaped networks and reuses work across multiple queries.
  3. Sampling methods: give approximate answers, but they scale to networks where exact inference would crawl.

Exact inference becomes expensive as networks grow and tangle. Sampling trades a bit of precision for speed. For learning purposes, stick with variable elimination and don't overthink it.

If you like the idea of trading exactness for speed, it is the same bargain behind simulated annealing, where a controlled dose of randomness buys you a way out of local optima.

Learning a Network From Data

You don't always know the probabilities. Sometimes you have a dataset and a rough idea of the structure. pgmpy can estimate the CPTs from data with a few lines:

from pgmpy.estimators import MaximumLikelihoodEstimator

model.fit(data, estimator=MaximumLikelihoodEstimator)

Here data means a pandas DataFrame with one column per variable. You can even learn the structure itself, but I'd call that an advanced move. Structure learning finds correlations, and correlations lie about causes. Draw the arrows yourself when you can.

Common Beginner Mistakes

I made every one of these, so you can skip them:

  • Mixing up column order in CPDs. Check your evidence order twice, then check it again.
  • Drawing arrows backward. An arrow should point from cause to effect, or the logic breaks.
  • Forgetting to validate. One bad column sum causes errors that look unrelated.
  • Adding too many parents. A node with six parents needs a CPT with dozens of columns. Keep the graph sparse.
  • Treating probabilities as certainties. A 36% chance of rain is not a forecast. It's a belief that shifts with new evidence.

Ever stared at a table of zeros and ones and wondered why inference failed? Usually a hard zero in a CPT blocked an outcome the evidence needed. Use small nonzero values when you feel unsure.

Best Book to Read

CoverBookDescriptionGet it
Cover of “Probabilistic Graphical Models: Principles and Techniques” Probabilistic Graphical Models: Principles and Techniquesby Daphne Koller and Nir Friedman the reference that connects Bayesian networks, Markov networks and inference algorithms into one framework, with the theory behind variable elimination spelled out properly [2]. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read it after the lawn example runs. The chapter on inference looks far less intimidating once you have watched a CPT column order break your own model.

Wrapping Up

A Bayesian network combines a graph of cause and effect with probability tables, and it updates its beliefs as evidence arrives. With pgmpy, you define the structure, fill in the CPDs, validate the model, and query it in a few lines of Python. Explaining away alone makes the effort worthwhile.

Start with the lawn example above and run it yourself. Then swap in your own problem, like "why is my code failing?" with nodes for typos, bad inputs, and caffeine levels. If the model blames caffeine, trust the math and make another coffee.

If you want the same style of step-by-step build for other classical AI techniques, the Monte Carlo Tree Search walkthrough and the constraint satisfaction guide follow the same pattern: small model, real code, one surprising result.

Frequently Asked Questions

What is a Bayesian network in simple terms?

A Bayesian network is a graph where each node is an uncertain variable and each arrow is a direct influence. Every node stores a conditional probability table describing how likely its states are given its parents, so the whole graph encodes a joint probability distribution in a compact form.

What is a conditional probability table (CPT)?

A CPT lists the probability of every state of a variable for each combination of states of its parents. A root node with no parents holds a plain probability distribution, while a node with three binary parents holds a table with eight columns, one per parent combination.

Does pgmpy use BayesianNetwork or DiscreteBayesianNetwork?

Both names appear in tutorials. Older pgmpy releases exposed BayesianNetwork, and newer releases use DiscreteBayesianNetwork for models with discrete variables. If an import fails, try the other name, then check the installed version in the docs.

What is explaining away in a Bayesian network?

Explaining away happens when two causes can produce the same effect. Observing the effect makes the causes compete, so evidence for one cause lowers the probability of the other. In the lawn example, seeing the sprinkler on drops the chance of rain below one percent.

When should I use a Bayesian network instead of a neural network?

Bayesian networks are strong when data is scarce, when you already know the causal structure, and when someone needs to see why a conclusion was reached. Neural networks usually win on raw accuracy with large datasets, but they answer questions with weights rather than traceable probabilities.

Sources

  • [1] Judea Pearl, Probabilistic Reasoning in Intelligent Systems: Networks of Plausible Inference (1988) - the book that established Bayesian networks as a practical reasoning framework: sciencedirect.com
  • [2] Koller and Friedman, Probabilistic Graphical Models: Principles and Techniques (2009) - the standard graduate reference on representation and exact inference: mitpress.mit.edu
  • [3] Ankan and Panda, pgmpy: Probabilistic Graphical Models using Python (SciPy 2015) - the paper describing the library used in this article: conference.scipy.org
  • [4] pgmpy documentation, Discrete Bayesian Networks and Inference - API reference for DiscreteBayesianNetwork, TabularCPD and VariableElimination, including the evidence ordering rules: pgmpy.org
  • [5] Eugene Charniak, Bayesian Networks without Tears (AI Magazine, 1991) - a short, readable introduction to the intuitions behind the formalism: aaai.org

What are You Looking For?

esc