Het sproeiernetwerk en een probleemoplosser met 22 variabelen voor wifi problemen, gebouwd in Python met pyAgrum.
Uitvoeren in Google ColabColab vereist een Google-account, maar je kan de notebook ook .
Leesmodus. Hieronder staat de hele notebook, met de uitvoer van de code erbij. Je kan de volledige inhoud dus gewoon hier lezen. Om code aan te passen en de gevolgen te zien, kan je naar Google Colab (externe link) gaan.
In the chapter Bayesian networks, you set observations in the demos and watched the network work out how likely everything else became. This notebook shows what that looks like in code, with a library that does the computing for you.
You will do that twice:
- 🌧️ to build the sprinkler network from the chapter and ask it the same questions;
- 📶 to build a troubleshooter for the KU Leuven Wi-Fi: a network of 22 yes/no variables that works out why your laptop or phone doesn't get online, and which check to do next.
Prior knowledge: the chapters Probability and Bayesian networks. You don't need any programming experience: you can run the whole notebook without changing a single line, and the exercises only ask you to change small pieces.
Estimated time: about 40 minutes.
This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/bayesian-networks, and you can open it directly in Google Colab (externe link).
🚀 First time in a notebook?
Then the short introductory notebook explains everything step by step. The most important things:
- Make your own copy: File → Save a copy in Drive (in the menu at the top left), and work in that copy.
- Run a cell by clicking in it and pressing Shift+Enter, or with the ▶ button to its left. The result appears below the cell.
- Run the cells in order, from top to bottom, because a cell uses what the cells above it made. Does something behave strangely? Choose Runtime → Restart session and run everything again from the top.
Prefer not to use Google? Download the notebook file and open it in Jupyter (externe link) or Visual Studio Code (externe link). For the drawings of the networks, your computer also needs Graphviz (externe link); Colab already has it.
🐍 Python in this notebook
New to Python? The introductory notebook explains the basics: variables, lists, dictionaries, loops and functions. On top of those, this notebook uses:
| Code | Meaning |
|---|---|
f"{rain:.1%}" | An f-string: Python fills in the value of rain between the braces. After the colon comes how to show it: .1% shows 0.749 as 74.9%. |
{**login, "PasswordChanged": "yes"} | A new dictionary with everything in login, plus one more key (or a new value for a key it already has). login itself stays as it is. |
[name for name in names if ...] | A list built in one line: every name in names, or only the ones for which the condition after if holds. With braces and a colon, {key: value for ...}, it builds a dictionary. Inside sum(...), it adds the values up. |
sorted(chance, key=chance.get, reverse=True) | The keys of the dictionary chance, sorted by their value, largest first. |
asks_password = "?" # @param ["?", "no", "yes"] | A comment that Colab turns into a dropdown in a form next to the code (or in its place, when the code is hidden). In other notebook programs, it's just a comment. A first line # @title Some title { display-mode: "form" } hides the code of the cell in Colab: double-click the title to see it. |
📦 Install pyAgrum
You will use pyAgrum (externe link), a free Python library for Bayesian networks, developed mainly at Sorbonne University in Paris. The first cell below installs it, at the version this notebook was tested with; if it says that you may need to restart, you can ignore that. (pyAgrum has no ready-made version for Windows laptops with an ARM processor yet: on such a laptop, use Colab.)
The second cell loads the library under the short name gum, and its drawing part as gnb. Its last lines give the drawings the look of the demos in the chapter.
# pyAgrum, at the version this notebook was tested with
%pip install --quiet pyagrum==3.2.1import pandas as pd
import pyagrum as gum
import pyagrum.lib.notebook as gnb
# the look of the drawings: blue bars, one decimal, white nodes, observations in light orange
STYLE = {"histogram_color": "#1e88e5", "histogram_edge_color": "#1e88e5", "histogram_horizontal_visible_digits": "1",
"default_node_bgcolor": "white", "default_node_fgcolor": "black", "evidence_bgcolor": "#fff3e0",
"figure_facecolor": "white", "tensor_with_colors": "False", "show_inference_time": "False"}
for key, value in STYLE.items():
gum.config["notebook", key] = value🌧️ The sprinkler network
🏗️ Build the network
Start with the network from the chapter: whether it's cloudy, whether the sprinkler is on, whether it rains, and whether the grass is wet.
gum.fastBN builds the network from one line of text with the arrows. Every variable gets its states between braces the first time it appears, as in Cloudy{yes|no}, and a ; separates two chains of arrows.
Then fill every conditional probability table (cpt in pyAgrum), one row at a time, with the numbers from the chapter. A node without parents has one row, filled by fillWith. For the other nodes, the dictionary between the square brackets says which row: [{"Cloudy": "yes"}] is the row for cloudy weather. The list gives the probability of each state, in the order of the braces.
fastBN fills every table with random numbers, so a forgotten row would go unnoticed. That's why the code first sets every table to 0, and ends with check(): an empty result, (), means that every row adds up to 1.
sprinkler = gum.fastBN("Cloudy{yes|no}->Sprinkler{yes|no}->WetGrass{yes|no}; Cloudy->Rain{yes|no}->WetGrass")
for name in sprinkler.names():
sprinkler.cpt(name).fillWith(0) # start with empty tables
sprinkler.cpt("Cloudy").fillWith([0.5, 0.5]) # P(Cloudy=yes), P(Cloudy=no)
sprinkler.cpt("Sprinkler")[{"Cloudy": "yes"}] = [0.1, 0.9] # P(Sprinkler=yes | Cloudy=yes), P(Sprinkler=no | Cloudy=yes)
sprinkler.cpt("Sprinkler")[{"Cloudy": "no"}] = [0.4, 0.6]
sprinkler.cpt("Rain")[{"Cloudy": "yes"}] = [0.8, 0.2]
sprinkler.cpt("Rain")[{"Cloudy": "no"}] = [0.2, 0.8]
sprinkler.cpt("WetGrass")[{"Sprinkler": "yes", "Rain": "yes"}] = [0.99, 0.01]
sprinkler.cpt("WetGrass")[{"Sprinkler": "yes", "Rain": "no"}] = [0.9, 0.1]
sprinkler.cpt("WetGrass")[{"Sprinkler": "no", "Rain": "yes"}] = [0.9, 0.1]
sprinkler.cpt("WetGrass")[{"Sprinkler": "no", "Rain": "no"}] = [0.0, 1.0]
print(sprinkler.check()) # (): every table is complete
print(sprinkler)()
BN{nodes: 4, arcs: 4, domainSize: 16, dim: 9, mem: 144o}The last line is a summary. dim: 9 counts the numbers in the tables: the 9 parameters of the chapter, one per row (the probability of no follows from the one of yes). domainSize: 16 is the number of rows in the full joint table, which needs 15 numbers. (mem is the memory it takes.)
Ask for one table, and you see it as in the chapter: one row for every combination of the parents, in pyAgrum's own order.
sprinkler.cpt("WetGrass")|
|
| ||
|---|---|---|---|
|
| 0.9900 | 0.0100 | |
| 0.9000 | 0.1000 | ||
|
| 0.9000 | 0.1000 | |
| 0.0000 | 1.0000 | ||
🖼️ Draw the network
gnb.showInference draws the network with a bar for every state: how likely it is, given what you observed. Nothing is observed yet, so these are the probabilities before you look outside.
gnb.showInference(sprinkler)🔮 Ask questions
gum.getPosterior computes the probability of every state of one target variable, given the observations evs (short for evidence). Its result works like a table: [{"Rain": "yes"}] picks the probability that it rains. The cell asks the two kinds of questions from the chapter: from cause to effect, and from effect to cause.
# from cause to effect: it's cloudy. How likely is wet grass?
wet = gum.getPosterior(sprinkler, target="WetGrass", evs={"Cloudy": "yes"})[{"WetGrass": "yes"}]
print(f"P(WetGrass=yes | Cloudy=yes) = {wet:.1%}")
# from effect to cause: the grass is wet. How likely is it that it rained?
rain = gum.getPosterior(sprinkler, target="Rain", evs={"WetGrass": "yes"})[{"Rain": "yes"}]
print(f"P(Rain=yes | WetGrass=yes) = {rain:.1%}")P(WetGrass=yes | Cloudy=yes) = 74.5% P(Rain=yes | WetGrass=yes) = 74.9%
74.9% is the number from the chapter: wet grass makes rain a lot more likely than the 50% before you looked.
🔀 Explaining away
In the chapter, wet grass made the sprinkler more likely, until you learned that it had rained: the rain explains the wet grass away. The cell computes P(Sprinkler=yes) in three situations, and draws the network for wet grass.
situations = {
"nothing observed": {},
"wet grass": {"WetGrass": "yes"},
"wet grass and rain": {"WetGrass": "yes", "Rain": "yes"},
}
for description, evidence in situations.items():
sprinkler_on = gum.getPosterior(sprinkler, target="Sprinkler", evs=evidence)[{"Sprinkler": "yes"}]
print(f"{description}: P(Sprinkler=yes) = {sprinkler_on:.0%}")
gnb.showInference(sprinkler, evs={"WetGrass": "yes"})nothing observed: P(Sprinkler=yes) = 25% wet grass: P(Sprinkler=yes) = 38% wet grass and rain: P(Sprinkler=yes) = 17%
🔗 What depends on what?
In the chapter, once you knew the sprinkler and the rain, the clouds told you nothing more about the grass: conditional independence. isIndependent(a, b, given) checks such statements on the arrows alone: True means independent.
print("WetGrass and Cloudy, given Sprinkler and Rain: ", sprinkler.isIndependent("WetGrass", "Cloudy", ["Sprinkler", "Rain"]))
print("WetGrass and Cloudy, given nothing: ", sprinkler.isIndependent("WetGrass", "Cloudy", []))
print("Sprinkler and Rain, given Cloudy: ", sprinkler.isIndependent("Sprinkler", "Rain", ["Cloudy"]))
print("Sprinkler and Rain, given Cloudy and WetGrass: ", sprinkler.isIndependent("Sprinkler", "Rain", ["Cloudy", "WetGrass"]))WetGrass and Cloudy, given Sprinkler and Rain: True WetGrass and Cloudy, given nothing: False Sprinkler and Rain, given Cloudy: True Sprinkler and Rain, given Cloudy and WetGrass: False
The last line is explaining away once more: once you know the weather, sprinkler and rain are independent, but as soon as you also observe their common effect, the wet grass, they depend on each other.
Try it yourself
- First predict, then check: in 🏗️ Build the network, change the Sprinkler row for
{"Cloudy": "no"}from[0.4, 0.6]into[0.8, 0.2]. How far does the sprinkler drop now once you know it rained? Run that cell and the cells below it again. (Change the row back afterwards, and run the cell once more.) - How likely is it that it's cloudy, given wet grass? Copy the last two lines of 🔮 Ask questions, and change every
Rainin them intoCloudy. - Put a
#in front of one row of WetGrass in 🏗️ Build the network, and run it again. What doescheck()say? (Then remove the#, and run the cell once more.)
📶 A troubleshooter for campus Wi-Fi
Your laptop or phone doesn't get online on the KU Leuven Wi-Fi (campusroam or eduroam). Is Wi-Fi switched off? Is the room too crowded? Does the laptop still use your old password? And what do you check first? In this part, you build a Bayesian network that answers such questions for the campus Wi-Fi.
🧭 What the network knows
Every node is a yes/no question about one moment: a student connects a laptop or phone to the Wi-Fi on campus. Its probability says how often the answer is yes at such a moment: WifiOff 0.003 means that Wi-Fi is switched off in 3 of 1,000 connections.
The nodes form four groups, in the colors of the drawing further on:
- 🟨 context (3 nodes): what you know about the situation, such as a packed lecture hall;
- 🟥 causes (8): what can go wrong, from Wi-Fi switched off to an account that isn't active yet;
- 🟦 symptoms (4): what you see, such as a device that isn't connected;
- 🟩 checks (7): what you can test, each with the seconds it takes.
The arrows go from the context to the causes (a packed room makes congestion more likely), and from the causes to the symptoms and checks.
The numbers are made up: plausible guesses, not real statistics.
🧰 Helper functions
You describe every node with one of two helpers:
happens(name, meaning, p)for a node without parents: it is yes with probabilityp;caused_by(name, meaning, parents, other)for a node with parents: each parent that is yes makes this node yes on its own, with its own probability inparents, andotheris the chance that something not in the network does. (This trick is called noisy-OR.)
build turns the list of nodes into a pyAgrum network, and fills every row of every table from those few numbers, as you did by hand for the sprinkler.
Both cells below hold helpers: the first builds the network, the second shows results as bars, tables and drawings. In Colab, their code is hidden: run them like any other cell, and double-click a title to read the code.
Helpers that build the network(code, in Colab verborgen)
# @title Helpers that build the network { display-mode: "form" }
import itertools
def happens(name, meaning, p):
"""A node without parents: it is "yes" with probability p."""
return {"name": name, "meaning": meaning, "parents": {}, "other": p, "cost": None}
def caused_by(name, meaning, parents, other, cost=None):
"""A node with parents. Each parent that is "yes" makes this node "yes" on its own, with its probability
in parents; other is the chance that something not in the network does. cost: the seconds a check takes."""
return {"name": name, "meaning": meaning, "parents": parents, "other": other, "cost": cost}
def build(name, nodes):
"""A pyAgrum network from the node descriptions (parents before children): fills every row of every table."""
bn = gum.BayesNet(name)
for node in nodes:
bn.add(gum.LabelizedVariable(node["name"], node["meaning"], ["no", "yes"]))
for parent in node["parents"]:
bn.addArc(parent, node["name"])
bn.cpt(node["name"]).fillWith(0) # start with an empty table
for answers in itertools.product(["no", "yes"], repeat=len(node["parents"])):
row = dict(zip(node["parents"], answers)) # one row: a state for every parent
p_no = 1 - node["other"] # the node stays "no" only if nothing makes it "yes"
for parent, p in node["parents"].items():
if row[parent] == "yes":
p_no *= 1 - p
bn.cpt(node["name"])[row] = [p_no, 1 - p_no]
print("check():", bn.check()) # (): every row adds up to 1
return bnHelpers to show the results(code, in Colab verborgen)
# @title Helpers to show the results { display-mode: "form" }
from pyagrum.lib.bn2graph import BNinference2dot
def show_suspects(evidence, top=6):
"""The most likely causes: their chance in any connection (before) and given the evidence (now)."""
before = suspects({})
print(f"{'cause':20} {'before':>7} {'now':>7}")
for cause, p in list(suspects(evidence).items())[:top]:
print(f"{cause:20} {before[cause]:7.1%} {p:7.1%} {'█' * round(p * 40)}")
def compare(situations, causes):
"""A table: the chance of each cause (columns) in each situation (rows: a description and its evidence)."""
rows = {}
for description, evidence in situations.items():
chance = suspects(evidence)
rows[description] = {cause: f"{chance[cause]:.1%}" for cause in causes}
return pd.DataFrame.from_dict(rows, orient="index")
def draw(nodes, evidence):
"""Draw only these nodes of the Wi-Fi network, with a bar for every state, given the evidence."""
ids = [wifi.idFromName(node) for node in nodes]
part = gum.DAG()
for node_id in ids:
part.addNodeWithId(node_id)
for tail, head in wifi.arcs():
if tail in ids and head in ids:
part.addArc(tail, head)
gnb.showGraph(BNinference2dot(wifi, evs=evidence, dag=part), size="8")
COLORS = {"context": "#fde68a", "cause": "#fecaca", "symptom": "#bfdbfe", "check": "#bbf7d0"}
def draw_groups(groups):
"""Draw a whole network as boxes, colored by group, from left to right."""
lines = ['digraph { rankdir=LR; ranksep=0.4; nodesep=0.08; '
'node [shape=box, style="rounded,filled", fontname=Helvetica, margin="0.06,0.02", height=0.3];']
for group, nodes in groups.items():
for node in nodes:
lines.append(f'{node["name"]} [fillcolor="{COLORS[group]}"];')
lines += [f'{parent} -> {node["name"]};' for parent in node["parents"]]
gnb.showDot("\n".join(lines + ["}"]), size="10")🟥 Context and causes
This is the part an expert writes (here, the authors of this notebook): one line per node, with its name, what it means, and its numbers. Most causes simply happen in a share of the connections: Wi-Fi switched off in 0.3%, a weak signal in 2%. Others also depend on the context: a packed room causes congestion with a chance of 8%, and something else causes it with a chance of 0.5%.
Changed a number below? Run that cell again, and then 🏗️ Build the Wi-Fi network.
CONTEXT = [
happens("CrowdedRoom", "You sit in a packed lecture hall or library.", 0.30),
happens("PasswordChanged", "You changed your KU Leuven password in the last two weeks.", 0.04),
happens("NewStudent", "You started at KU Leuven less than a month ago.", 0.04),
]
CAUSES = [
happens("WifiOff", "Wi-Fi is switched off, or airplane mode is on.", 0.003),
happens("WeakSignal", "You are far from an access point, or behind thick walls.", 0.02),
caused_by("Congestion", "Too many devices on the access points in this room.", {"CrowdedRoom": 0.08}, other=0.005),
caused_by("OldPassword", "The device still uses your old password.", {"PasswordChanged": 0.10}, other=0.001),
caused_by("WrongSettings", "Wrong Wi-Fi settings, such as a username without @kuleuven.be.",
{"NewStudent": 0.10}, other=0.002),
caused_by("AccountProblem", "Your KU Leuven account isn't active yet, has expired or is blocked.",
{"NewStudent": 0.05}, other=0.0005),
happens("VPNProblem", "A VPN app on the device blocks all traffic.", 0.002),
happens("CampusOutage", "The campus network itself has a problem.", 0.001),
]🟦 Symptoms and checks
A symptom or a check lists the causes that can make it yes, each with its own probability. Take NotConnected: Wi-Fi switched off causes it 99% of the time, a weak signal only 30% of the time. The checks range from a look at the Wi-Fi icon (5 seconds) to setting up the Wi-Fi again with the geteduroam app (2 minutes). Some are questions (is the Wi-Fi bad for a friend too?), others are repairs that double as a test (does switching off the VPN fix it?).
SYMPTOMS = [
caused_by("NotConnected", "The device isn't connected to the Wi-Fi.",
{"WifiOff": 0.99, "WeakSignal": 0.3, "Congestion": 0.1, "OldPassword": 0.95, "WrongSettings": 0.95,
"AccountProblem": 0.95, "CampusOutage": 0.3}, other=0.002),
caused_by("AsksPassword", "The device keeps asking for your password.",
{"OldPassword": 0.8, "WrongSettings": 0.6, "AccountProblem": 0.8}, other=0.002),
caused_by("NoInternet", "Connected, but no web page opens.", {"VPNProblem": 0.95, "CampusOutage": 0.8},
other=0.001),
caused_by("VerySlow", "Pages load very slowly, or the connection keeps dropping.",
{"Congestion": 0.8, "WeakSignal": 0.6}, other=0.005),
]
CHECKS = [
caused_by("WifiIconOff", "Look at the Wi-Fi icon: is Wi-Fi off, or airplane mode on?", {"WifiOff": 0.95},
other=0.002, cost=5),
caused_by("WeakBars", "Open the list of Wi-Fi networks: does campusroam show only one or two bars?",
{"WeakSignal": 0.95}, other=0.05, cost=10),
caused_by("FriendAlsoFails", "Ask a friend next to you: is the Wi-Fi bad on their device too?",
{"CampusOutage": 0.95, "Congestion": 0.8, "WeakSignal": 0.3}, other=0.02, cost=30),
caused_by("WebLoginFails", "On mobile data, log in at account.kuleuven.be: does it fail?",
{"AccountProblem": 0.95}, other=0.02, cost=60),
caused_by("RetypeFixes", "Forget the network, join again and type your current password: does it work now?",
{"OldPassword": 0.95}, other=0.02, cost=60),
caused_by("GeteduroamFixes", "Set up the Wi-Fi again with the geteduroam app: does it work now?",
{"OldPassword": 0.95, "WrongSettings": 0.95}, other=0.02, cost=120),
caused_by("VPNOffFixes", "Switch off the VPN app: does it work now?", {"VPNProblem": 0.95}, other=0.01, cost=30),
]🏗️ Build the Wi-Fi network
build turns the four lists into one network.
wifi = build("CampusWifi", CONTEXT + CAUSES + SYMPTOMS + CHECKS)
print(wifi.size(), "nodes and", wifi.sizeArcs(), "arrows:", len(CONTEXT), "context,", len(CAUSES), "causes,",
len(SYMPTOMS), "symptoms and", len(CHECKS), "checks")check(): () 22 nodes and 28 arrows: 3 context, 8 causes, 4 symptoms and 7 checks
The tables are ordinary pyAgrum tables, like the ones of the sprinkler. VerySlow has two causes, congestion (0.8) and a weak signal (0.6), plus 0.005 for something else. Those three numbers fill the whole table: with both causes, for example, pages are very slow in 92.0% of the connections, more than with either cause alone.
wifi.cpt("VerySlow")|
|
| ||
|---|---|---|---|
|
| 0.9950 | 0.0050 | |
| 0.1990 | 0.8010 | ||
|
| 0.3980 | 0.6020 | |
| 0.0796 | 0.9204 | ||
📏 How big is this network?
The chapter compared a network with the full joint table. Here is that comparison for the Wi-Fi network: the full table (a row for every combination of answers to its 22 yes/no questions), the tables of the network (dim()), and the numbers typed in the cells above.
joint = 2 ** wifi.size() - 1 # numbers in the full joint table: its rows, minus 1
typed = sum(len(node["parents"]) + 1 for node in CONTEXT + CAUSES + SYMPTOMS + CHECKS) # one per parent, plus other
day = 24 * 60 * 60 # seconds
print("Writing down one number per second takes, for")
print(f" the full joint table: {joint:,} numbers: {joint / day:.0f} days")
print(f" the tables of the network: {wifi.dim()} numbers: {wifi.dim() / 60:.0f} minutes")
print(f" the numbers we typed: {typed} numbers: {typed} seconds")Writing down one number per second takes, for the full joint table: 4,194,303 numbers: 49 days the tables of the network: 181 numbers: 3 minutes the numbers we typed: 50 numbers: 50 seconds
So the 50 numbers we typed do the work of a full table that would take 49 days to write down, at one number per second.
This is the whole network, in the colors of the four groups, from the context on the left to the symptoms and checks on the right.
draw_groups({"context": CONTEXT, "cause": CAUSES, "symptom": SYMPTOMS, "check": CHECKS})🔍 From symptom to suspects
To ask the network a question, pyAgrum needs an inference engine: gum.LazyPropagation computes exact answers. (gum.getPosterior in the sprinkler part made one behind the scenes, for every question.) suspects(evidence) uses one to compute the probability of every cause, most likely first.
Start with a common complaint: the device is not connected, and that's all you know. show_suspects shows the most likely causes, with their chance in any connection (before) and in connections with this complaint (now).
def engine_for(evidence):
"""pyAgrum's inference engine for the Wi-Fi network, with the evidence filled in."""
engine = gum.LazyPropagation(wifi) # a new engine every time, so that it uses the network as it is now
engine.setEvidence(evidence)
engine.makeInference()
return engine
def suspects(evidence):
"""P(cause present | evidence) for every cause, most likely first."""
engine = engine_for(evidence)
causes = [node["name"] for node in CAUSES]
# round(..., 9): the last digits of a result can differ from run to run, the first 9 never do
chance = {cause: round(engine.posterior(cause)[{cause: "yes"}], 9) for cause in causes}
return {cause: chance[cause] for cause in sorted(chance, key=chance.get, reverse=True)}
show_suspects({"NotConnected": "yes"})cause before now WeakSignal 2.0% 23.7% █████████ WrongSettings 0.6% 21.5% █████████ OldPassword 0.5% 17.9% ███████ Congestion 2.9% 13.2% █████ WifiOff 0.3% 11.2% ████ AccountProblem 0.2% 9.0% ████
No cause stands out: six causes each explain between 9.0% and 23.7% of these connections. Nobody typed those shares in: the network computes them with Bayes' theorem. An old password is the problem in only 0.5% of all connections, but it almost always breaks the connection, so it explains 17.9% of these complaints.
🔀 Explaining away, twice
In the sprinkler network, the rain explained away the sprinkler: once you knew it had rained, the sprinkler was no longer needed to explain the wet grass. The Wi-Fi network does that too. compare puts the chances of a few causes in a table, for one situation after another.
🔑 A new password
The device is not connected and keeps asking for the password. Three causes fit: the device still uses an old password (OldPassword), its Wi-Fi settings are wrong (WrongSettings), or your account isn't active (AccountProblem). Then you remember changing your KU Leuven password last week.
login = {"NotConnected": "yes", "AsksPassword": "yes"}
compare({
"before you look": {},
"not connected, asks for the password": login,
"... and you changed your password last week": {**login, "PasswordChanged": "yes"},
}, ["OldPassword", "WrongSettings", "AccountProblem"])| OldPassword | WrongSettings | AccountProblem | |
|---|---|---|---|
| before you look | 0.5% | 0.6% | 0.2% |
| not connected, asks for the password | 42.1% | 38.7% | 21.4% |
| ... and you changed your password last week | 94.2% | 4.5% | 2.4% |
The symptoms make all three causes a lot more likely: 42.1%, 38.7% and 21.4%. The password change is a clue for the old password (94.2%), and so it explains the other two away: wrong settings drop to 4.5%, an account problem to 2.4%. The drawing shows that last situation, with the observations in light orange.
draw(["PasswordChanged", "NewStudent", "OldPassword", "WrongSettings", "AccountProblem", "NotConnected", "AsksPassword"],
{**login, "PasswordChanged": "yes"})🐌 A packed lecture hall
The device is online, but pages load very slowly. Two causes compete: congestion and a weak signal. Then you look around: you sit in a packed lecture hall. Or, at another moment, in a quiet room.
slow = {"NotConnected": "no", "VerySlow": "yes"}
compare({
"before you look": {},
"online, but very slow": slow,
"... in a packed lecture hall": {**slow, "CrowdedRoom": "yes"},
"... in a quiet room": {**slow, "CrowdedRoom": "no"},
}, ["Congestion", "WeakSignal"])| Congestion | WeakSignal | |
|---|---|---|
| before you look | 2.9% | 2.0% |
| online, but very slow | 61.6% | 25.3% |
| ... in a packed lecture hall | 83.3% | 11.9% |
| ... in a quiet room | 21.3% | 50.1% |
The packed lecture hall makes congestion more likely (83.3%), and so it explains away the weak signal: from 25.3% to 11.9%. In a quiet room, it's the other way around: congestion drops to 21.3%, and a weak signal rises to 50.1%.
🩺 Which check next?
A good help desk doesn't check everything: it picks the check that helps most. To measure that, doubt adds up how unsure the network is about each of the 8 causes: 0 for a cause that is surely there or surely not, up to 1 for a cause that is a coin flip.
For every check, chances(evidence, check) predicts how likely each answer is, and doubt how much doubt is left after that answer. best_checks ranks the checks by the doubt they remove on average, per minute.
def chances(evidence, node):
"""P(every state of the node | evidence), as {state: probability}."""
posterior = engine_for(evidence).posterior(node)
return {state: round(posterior[{node: state}], 9) for state in wifi.variable(node).labels()}
def doubt(evidence):
"""0 when we are sure about every cause (present or not); a cause that is a coin flip adds 1."""
return sum(4 * p * (1 - p) for p in suspects(evidence).values())
def best_checks(evidence, top=5):
"""The checks not done yet, best first: the doubt each removes on average, per minute."""
now = doubt(evidence)
rows = []
for node in CHECKS:
check, seconds = node["name"], node["cost"]
if check not in evidence:
answers = chances(evidence, check) # how likely each answer is
after = sum(p * doubt({**evidence, check: answer}) for answer, p in answers.items() if p > 1e-9)
rows.append({"check": check, "doubt removed": now - after, "seconds": seconds,
"per minute": (now - after) / seconds * 60})
columns = ["check", "doubt removed", "seconds", "per minute"] # also when no check is left
ranking = pd.DataFrame(rows, columns=columns).set_index("check").sort_values("per minute", ascending=False)
return ranking.head(top).round(3).rename_axis(index=None, columns="check")Back to the device that isn't connected and keeps asking for the password, now with the answers to a help desk's first questions: the student didn't change the password in the last two weeks, isn't new, and sits in a quiet room.
intake = {"NotConnected": "yes", "AsksPassword": "yes", "PasswordChanged": "no", "NewStudent": "no", "CrowdedRoom": "no"}
show_suspects(intake, top=3)
print(f"\nDoubt now: {doubt(intake):.2f}")
best_checks(intake)cause before now WrongSettings 0.6% 49.6% ████████████████████ OldPassword 0.5% 33.0% █████████████ AccountProblem 0.2% 16.5% ███████ Doubt now: 2.59
| check | doubt removed | seconds | per minute |
|---|---|---|---|
| RetypeFixes | 1.235 | 60 | 1.235 |
| WebLoginFails | 0.691 | 60 | 0.691 |
| GeteduroamFixes | 0.608 | 120 | 0.304 |
| WifiIconOff | 0.017 | 5 | 0.203 |
| WeakBars | 0.030 | 10 | 0.180 |
Wrong settings are now the main suspect (49.6%), yet retyping the password comes first: in one minute, it settles whether an old password (33.0%) is to blame. That is still possible without a recent change: think of a laptop that nobody used since a password change months ago. Setting up the Wi-Fi again with geteduroam removes less doubt (0.608) in twice the time: when it works, you still don't know whether it fixed the settings or the password.
Another device isn't connected either, but doesn't ask for a password. Now the quick checks come first: a look at the Wi-Fi icon takes 5 seconds, and settles whether Wi-Fi is simply off.
best_checks({"NotConnected": "yes", "AsksPassword": "no"}, top=3)| check | doubt removed | seconds | per minute |
|---|---|---|---|
| WifiIconOff | 0.634 | 5 | 7.611 |
| WeakBars | 0.838 | 10 | 5.027 |
| FriendAlsoFails | 0.250 | 30 | 0.500 |
🎮 Play the help desk
Your turn at the help desk. Pick what the student tells you in the form of the cell below (in Colab), leave ? for what you don't know, and run the cell: it shows the main suspects and the best next checks. Do the best check in your head, pick its answer, and run the cell again. Stop as soon as one cause reaches 90%: that is your verdict. Without Colab, change the text between the quotes.
Try it yourself
- The form starts with a device that isn't connected and asks for the password. Decide first what is really wrong, say wrong settings (WrongSettings), and answer every check the way it would turn out then. How many checks does the network need before that cause reaches 90%?
- Set every dropdown back to
?, and thennot_connectedtonoandno_internettoyes: the device is connected, but no web page opens. Is it a VPN app, or the campus network? Which check comes first? - Set every dropdown back to
?, and give two answers that contradict each other:wifi_icon_off=yes, butnot_connected=no. The network still answers, because no combination is impossible. Which of the two answers does it believe? Compare the now column with before.
🎮 The help desk(code, in Colab verborgen)
# @title 🎮 The help desk { display-mode: "form" }
# @markdown **What the student sees**
not_connected = "yes" # @param ["?", "no", "yes"]
asks_password = "yes" # @param ["?", "no", "yes"]
no_internet = "?" # @param ["?", "no", "yes"]
very_slow = "?" # @param ["?", "no", "yes"]
# @markdown **What the student knows**
crowded_room = "?" # @param ["?", "no", "yes"]
password_changed = "?" # @param ["?", "no", "yes"]
new_student = "?" # @param ["?", "no", "yes"]
# @markdown **The checks done so far**
wifi_icon_off = "?" # @param ["?", "no", "yes"]
weak_bars = "?" # @param ["?", "no", "yes"]
friend_also_fails = "?" # @param ["?", "no", "yes"]
web_login_fails = "?" # @param ["?", "no", "yes"]
retype_fixes = "?" # @param ["?", "no", "yes"]
geteduroam_fixes = "?" # @param ["?", "no", "yes"]
vpn_off_fixes = "?" # @param ["?", "no", "yes"]
form = {"NotConnected": not_connected, "AsksPassword": asks_password, "NoInternet": no_internet,
"VerySlow": very_slow, "CrowdedRoom": crowded_room, "PasswordChanged": password_changed,
"NewStudent": new_student, "WifiIconOff": wifi_icon_off, "WeakBars": weak_bars,
"FriendAlsoFails": friend_also_fails, "WebLoginFails": web_login_fails, "RetypeFixes": retype_fixes,
"GeteduroamFixes": geteduroam_fixes, "VPNOffFixes": vpn_off_fixes}
evidence = {node: answer for node, answer in form.items() if answer != "?"}
ranking = best_checks(evidence, top=3)
show_suspects(evidence)
print("\nBest next checks:")
for check, row in ranking.iterrows():
print(f" {check} ({row['seconds']:.0f} s): {wifi.variable(check).description()}")cause before now OldPassword 0.5% 42.1% █████████████████ WrongSettings 0.6% 38.7% ███████████████ AccountProblem 0.2% 21.4% █████████ Congestion 2.9% 3.0% █ WeakSignal 2.0% 2.2% █ WifiOff 0.3% 0.4% Best next checks: RetypeFixes (60 s): Forget the network, join again and type your current password: does it work now? WebLoginFails (60 s): On mobile data, log in at account.kuleuven.be: does it fail? GeteduroamFixes (120 s): Set up the Wi-Fi again with the geteduroam app: does it work now?
By Thomas Winters (externe link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/bayesian-networks.
