Machines, Data & Learning
An interactive, connected companion to CS7.301 — Machine, Data and Learning. Written to be read before, during and after the lectures.
This is not just a pile of notes. It is one long story about one question:
How can a machine act well in a world it doesn't fully understand, using only data and experience?
Every topic in your syllabus is one piece of the answer. Overfitting, genetic algorithms, utility theory, Markov decision processes, decision trees and Bayesian networks can look like unrelated topics in a slide deck. They are not. They are four ideas that keep meeting each other:
Meet Bolt
To keep the ideas connected, one character appears in every chapter: Bolt, a small food-delivery robot on a university campus. It carries late-night maggi from the canteen to the hostels. Bolt's problems grow as the book goes on, and each one needs the next tool:
| Chapter | Bolt's problem | The tool you'll learn |
|---|---|---|
| 1 | What does it even mean for Bolt to be "smart"? | Agents, environments, rationality |
| 2 | Predict delivery time from distance without memorising last week's noise | Generalization, overfitting, bias–variance |
| 3 | Tune 11 model weights when there is no gradient to follow | Hill climbing, simulated annealing, genetic algorithms |
| 4 | "My bump sensor fired. Is there really a pothole?" Is a risky shortcut worth it? | Probability, Bayes' rule, utility |
| 5 | Plan a route when wheels slip, and when Bolt isn't even sure where it is | Decision theory, MDPs, value iteration, POMDPs |
| 6 | Learn readable rules for "will this order be late?" | Decision trees, entropy, information gain |
| 7 | Diagnose why Bolt stopped: battery, motor or software? | Bayesian networks and inference |
How to read this book
The layout copies the Brown University version of the Rust Book, because that layout is good for learning:
- Sidebar (☰ top-left): every chapter, in order. Read them in order the first time, because later chapters build on earlier ones.
- Arrow keys ← → move between pages. s opens search.
- Themes (the paintbrush): Light, Rust, Coal, Navy, Ayu.
- Quizzes appear at the end of sections. They are written like exam questions. A quiz you can't finish tells you what to re-read. Your best scores are kept in this browser (the bar-chart icon, top right).
- Highlights and notes: select any text to highlight it in one of four colours or attach a note. Click a highlight to change or remove it. The highlighter icon (top right) lists every highlight in the book, and lets you export or import them as a file. They are saved only in your browser.
- Interactive widgets let you play with each idea: drag a slider until the model overfits, watch a genetic algorithm evolve, step value iteration one sweep at a time. Don't skip them. Ten seconds of playing is worth a page of reading.
- Python code is runnable and was tested with
numpy(andscipyfor one LP example). Copy it, run it, break it.
You will also see coloured boxes:
The idea explained without formulas, the way a friend would explain it.
How this idea links to other chapters. These boxes hold the story together.
Common question types, standard tricks and frequent mistakes.
Practical advice for the coding assignments, which are worth 35% of your grade.
The running example for this chapter.
How the book maps to your syllabus
| Syllabus unit | Course outcome | Where in this book |
|---|---|---|
| Unit 1 — Overview of AI and ML | CO-1 | Chapter 1 |
| Unit 2 — Data, generalization, overfitting, underfitting, bias–variance | CO-1, CO-2 | Chapter 2 |
| Unit 3 — Local search, genetic algorithms | CO-3 | Chapter 3 |
| Unit 5 — Probability and utility theory | CO-4 | Chapter 4 |
| Unit 6 — Decision theory, MDPs, modelling observation errors | CO-5 | Chapter 5 |
| Unit 7 — Decision tree learning, information gain | CO-6 | Chapter 6 |
| Unit 8 — Bayesian networks | CO-5 | Chapter 7 |
The syllabus jumps from Unit 3 to Unit 5. There is no Unit 4 in the document you were given, so this book doesn't invent one. "Modelling observation errors" in Unit 6 means sensor models, belief states and POMDPs, covered in §5.5.
The two references are Russell & Norvig, Artificial Intelligence: A Modern Approach (AIMA) and Python Machine Learning by Example (Liu). Where a section follows AIMA closely, it says which AIMA chapter to read. Many examples here, such as the 4×3 grid world, the burglar alarm and the tennis dataset, are the standard ones from AIMA and Mitchell. That's on purpose: your professors will probably use the same ones.
How your grade is built, and what that means for studying
| Component | Weight | What it rewards | How to prepare |
|---|---|---|---|
| Assignments | 35 | Implementing ideas in code and explaining your results | Every "Lab" section and Appendix B |
| Quizzes | 15 | Quick, precise understanding | The in-book quizzes |
| Mid exam | 20 | Chapters 1–4 (roughly) | Hand-computation drills + Appendix A |
| End exam | 30 | Everything, with weight on MDPs, trees and Bayes nets | Appendix C study plan |
MDL exams reward being able to compute by hand. Typical questions: one round of value iteration, the information gain of an attribute, a posterior with Bayes' rule, one GA crossover and mutation, the expected utility of a lottery, a bias–variance argument. Every chapter here includes worked examples of exactly these. Do them with a pen before you look at the answer.
A note on the math
You need high-school probability, a little calculus (derivatives) and comfort with summations like \(\sum_i x_i\). Every formula is introduced in words first. If an equation scares you, read the sentence above it again. The equation is only a short way of writing that sentence.
Ready? Let's start with the biggest question: what is AI, anyway?
Overview of AI and ML
Before we can teach a machine anything, we need to agree on what "intelligent" means. You might expect an answer like "it thinks like a human." The answer this course uses is different, and much more useful to an engineer.
This chapter does two things:
- §1.1 Agents and environments defines AI as building rational agents, systems that act to get the best expected outcome. This one definition explains why the rest of the syllabus exists.
- §1.2 What is machine learning? zooms in on one way to build such agents: learning behaviour from data instead of hand-writing it.
The campus wants Bolt to deliver food "intelligently." What should the engineers actually build? A list of if-statements? A neural network? Before choosing, they need a precise way to say what good behaviour is. That is where we start.
What Is Intelligence? Agents and Environments
Ask ten people what AI is and you'll get ten answers. Russell and Norvig sort the possible definitions into a 2×2 grid. It's worth a minute, because the grid shows which definition this course picks and why.
| …like a human | …rationally (optimally) | |
|---|---|---|
| Thinking… | Cognitive modelling: copy how human brains reason | "Laws of thought": logic, correct inference |
| Acting… | The Turing test: be indistinguishable from a human | Rational agents: do the right thing ✅ |
Modern AI, and this course, lives in the bottom-right cell. We don't care whether a system feels human or reasons in neat logic. We care whether it acts so as to achieve the best expected outcome. There are three reasons:
- It is measurable. "Best outcome" can be written as a number (reward, utility, loss) and optimized. "Human-like" can't.
- It is more general. Correct logical inference is one way to act well. Reflexes, learning and gambling wisely under uncertainty are others.
- Humans are not the gold standard. We are bad at probability (Chapter 4 will show you just how bad). We'd like machines to do better than us, not copy our mistakes.
Agents
An agent is anything that perceives its environment through sensors and acts on it through actuators.
Formally, the agent's behaviour is an agent function that maps the whole percept sequence seen so far to an action. The agent program is the concrete code that implements the function on real hardware. When you train a model you are, in effect, searching for a good agent program.
- Sensors: GPS, wheel encoders, a bump sensor, a camera, the order queue.
- Actuators: wheels, a lid lock, a speaker ("Your maggi has arrived!").
- Environment: campus paths, rain, crowds, stairs, potholes.
Rationality and the PEAS description
A rational agent chooses, for every percept sequence, the action expected to maximize its performance measure, given what it has perceived and what it knows. Four details in that sentence matter:
- Performance measure: rationality is always relative to a goal we choose. Choose badly and you get "rational" nonsense. Reward a vacuum robot for "amount of dirt sucked up" and it learns to dump dirt and re-suck it. Writing down the objective is the hardest and most important design step in ML.
- Expected: rational ≠ omniscient. If Bolt takes the usual path and a tree falls on it, Bolt wasn't irrational. It did the best it could with the information it had. Chapters 4–5 make "expected" precise with probability and utility.
- Given what it has perceived: an agent can't use information it never sensed. It can, however, choose to gather information. Chapter 5 computes exactly how much that is worth (the value of information).
- What it knows: built-in knowledge plus what it has learned. A learning agent gets more rational with experience, which is the whole point of ML.
Engineers specify an agent's task with PEAS:
| Letter | Meaning | Bolt |
|---|---|---|
| P | Performance measure | on-time deliveries, food still hot, no collisions, low battery use |
| E | Environment | campus paths, weather, pedestrians |
| A | Actuators | wheels, lid lock, speaker |
| S | Sensors | GPS, camera, encoders, bump sensor |
Properties of environments
The kind of environment decides which algorithm you need. This table is a map of the whole course, so read it carefully:
| Dimension | Easy end | Hard end | Where it shows up |
|---|---|---|---|
| Observable? | Fully: sensors show the complete state | Partially: noisy or missing sensing | MDP (full) vs POMDP (partial), §5.2 vs §5.5 |
| Deterministic? | Deterministic: action ⇒ one known outcome | Stochastic: outcomes have probabilities | Search (Ch 3) vs MDPs (Ch 5) |
| Episodic? | Episodic: each decision independent | Sequential: today's action shapes tomorrow | One-shot decisions (§5.1) vs MDPs (§5.2) |
| Static? | Static: world waits while you think | Dynamic: world changes meanwhile | Why fast approximate algorithms matter |
| Discrete? | Discrete states/actions | Continuous | Grid world vs real robot |
| Agents | Single agent | Multi-agent (cooperative/competitive) | Mostly single-agent in this course |
| Known? | Known rules/model | Unknown: must learn the model | Planning vs learning |
Chess is fully observable, deterministic, sequential, static (without a clock), discrete and multi-agent. Bolt's world is partially observable, stochastic, sequential, dynamic, continuous and multi-agent, which is about as hard as it gets. Real AI works by simplifying the hard cases into tractable models. A grid world approximates continuous space. An MDP assumes full observability. A Bayes net assumes some variables are independent. Every model is wrong, but some are useful.
Five kinds of agent programs
As agents get more sophisticated, each type adds one ingredient:
- Simple reflex agent: if condition then action, using only the current percept. "If the bump sensor fires, stop." Fast, but helpless when the right action depends on history.
- Model-based reflex agent: keeps an internal state, a model of the parts of the world it can't currently see. "I saw a pedestrian enter the corridor 2 s ago, so they're probably still there." This is the seed of belief states (§5.5).
- Goal-based agent: has an explicit goal and plans action sequences to reach it. This needs search (Ch 3).
- Utility-based agent: goals are binary (delivered / not delivered), but outcomes have degrees: fast vs slow, hot vs cold, risky vs safe. A utility function scores how good each state is, and the agent maximizes expected utility (Ch 4–5).
- Learning agent: any of the above plus a learning element that improves the agent from feedback. It has a critic (how am I doing?), a learning element (change myself), a performance element (act) and a problem generator (try new things: exploration).
This list is the course outline in disguise. Utility-based agents need probability and utility (Ch 4), and when decisions are sequential they need MDPs (Ch 5). Model-based agents under uncertainty need Bayesian networks (Ch 7) and belief states (§5.5). Learning agents need everything in Ch 2 (generalization) and Ch 6 (trees). Goal-based agents and learners both need search (Ch 3).
A very short history (so the names make sense)
- 1950: Turing asks "Can machines think?" and proposes the imitation game.
- 1956: the Dartmouth workshop coins "Artificial Intelligence."
- 1960s–80s: symbolic AI and expert systems: hand-written rules. They break down because the world is uncertain and rules don't scale.
- 1980s–90s: the probabilistic revolution. Pearl's Bayesian networks (Ch 7), decision theory, MDPs (Ch 5). Decision trees (ID3, 1986; Ch 6) and genetic algorithms (Holland, 1975; Ch 3) become popular.
- 2000s: statistical ML. The focus is on generalization from data (Ch 2).
- 2012–now: deep learning, large models and reinforcement learning (which is built on MDPs). The fundamentals in this course are exactly the vocabulary these systems are described in.
What Is Machine Learning?
Here is the oldest way to make Bolt smart: an engineer sits down and writes rules. If it's raining and the order is from Hostel C, take the covered walkway. This works until it doesn't. There are too many situations, the rules contradict each other, and the campus changes every semester.
Machine learning flips the process. Instead of writing the program, we write a program that writes the program from examples.
Tom Mitchell's definition (1997): A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E.
For Bolt's delivery-time predictor: T = predict how many minutes a delivery takes, P = average squared error in minutes², E = a log of past deliveries. If the predictions get more accurate as the log grows, Bolt is learning.
Notice that P, the performance measure, appears again. It is the same idea as the agent's performance measure in §1.1. In ML it is usually called a loss (lower is better) or a reward/utility (higher is better). Chapter 2 is about choosing and minimizing a loss. Chapters 4–5 are about maximizing a utility. Same coin, two sides.
The three main kinds of learning
| Type | What you're given | What you learn | Bolt example | In this course |
|---|---|---|---|---|
| Supervised | Inputs with correct answers \((x, y)\) | A function \(h(x) \approx y\) | Predict delivery time from distance; predict "late?" from weather | Ch 2, Ch 6 |
| Unsupervised | Inputs only \(x\) | Structure: clusters, densities, a compressed representation | Group hostels into zones with similar order patterns | (touched on in Ch 7: learning distributions) |
| Reinforcement | States, actions and occasional rewards | A policy: which action to take in each state | Learn routes from "+10 for a fast delivery, −50 for a crash" | Foundations: MDPs in Ch 5 |
Supervised learning splits further by the type of \(y\):
- Regression: \(y\) is a number (delivery time = 13.4 minutes).
- Classification: \(y\) is a category (late / on time; spam / not spam).
The vocabulary you'll use every day
| Term | Meaning | Bolt |
|---|---|---|
| Example / instance / sample | One data point | One past delivery |
| Feature / attribute \(x\) | A measured input | distance, rain (yes/no), hour of day |
| Label / target \(y\) | The answer we want to predict | minutes taken |
| Hypothesis / model \(h\) | A candidate function from \(x\) to \(y\) | \(h(x) = 3 + 4.2\cdot\text{distance}\) |
| Hypothesis space \(\mathcal{H}\) | The set of all models we're willing to consider | all straight lines; all degree-5 polynomials; all decision trees |
| Parameters / weights \(w\) | The numbers that pick one \(h\) out of \(\mathcal{H}\) | the 3 and the 4.2 above |
| Hyperparameters | Settings chosen before training that shape \(\mathcal{H}\) or the training process | polynomial degree, tree depth, GA mutation rate |
| Loss \(L\) | How wrong a prediction is | \((h(x)-y)^2\) |
Once you pick a hypothesis space \(\mathcal{H}\) and a loss, "learning" means searching \(\mathcal{H}\) for the \(h\) with the lowest loss. Sometimes the search is a formula (least squares, §2.1). Sometimes it is gradient descent. Sometimes there is no gradient and you use hill climbing or a genetic algorithm (Ch 3). Sometimes it is a greedy recursive split (ID3, Ch 6). Keep "learning is search" in mind. It is the thread that ties Chapter 2 to Chapter 3.
The ML workflow, end to end
Every practical ML project, including every assignment in this course, follows roughly this pipeline:
- Define the problem. What are T, P and E? What does success look like as a number?
- Collect and understand data. Plot it. Look for missing values, outliers and leaks.
- Split the data into training, validation and test sets before doing anything clever (§2.4 explains why this is sacred).
- Choose a hypothesis space and a loss. Start simple: a line, a shallow tree.
- Train: search for the parameters that minimize training loss.
- Validate: measure error on data the model hasn't seen. Tune hyperparameters.
- Test once on the held-out test set and report that number honestly.
- Deploy and monitor. The world drifts (new hostel, new semester), so keep checking.
The fundamental problem: generalization
This is the most important paragraph in the chapter. Pay attention.
Bolt doesn't care about predicting last week's deliveries. Those already happened! It cares about tomorrow's deliveries, which it has never seen. So the real goal of learning is not to minimize error on the training data. The goal is to minimize error on new data from the same source. This is called generalization.
The trap: if you let the model be flexible enough, it can drive training error to zero by memorizing every example, noise included, and then fail badly on new data. This is overfitting, and avoiding it is the central drama of Chapter 2.
"My model has 100% training accuracy, so it's perfect." No. Training accuracy is a measure of memory, not intelligence. A lookup table has 100% training accuracy. Always ask: what is the error on data the model never saw?
Why no single model wins: inductive bias
Here is a deep fact: learning is impossible without assumptions. Suppose you've seen Bolt's delivery times for distances 1, 2 and 3 km. What's the time for 4 km? Infinitely many functions pass through your three points and disagree at 4 km. To predict anything you must prefer some functions over others, for example "smooth ones" or "simple ones." That preference is the model's inductive bias.
- Linear regression assumes the relationship is a straight line.
- Decision trees (ID3) prefer short trees with informative splits near the root.
- Bayes nets assume certain conditional independencies.
The No Free Lunch theorem makes this formal: averaged over all possible problems, every learning algorithm performs the same. An algorithm only wins when its inductive bias matches the problem you actually have. Choosing that bias well is the art of ML. Chapter 2 gives you the tools (bias–variance and validation) to choose it scientifically.
The campus hands you a log of past deliveries: distance and minutes taken. The relationship is curved: short trips are dominated by waiting for the lift, and long trips slow down on the hill near the library. Should Bolt fit a line? A cubic? A degree-12 polynomial? Next chapter, you'll see that this innocent question contains the whole theory of generalization.
Data and Generalization
This chapter is the heart of CO-1 and CO-2. If you understand it deeply, every model you meet later will make sense, from a decision tree to a billion-parameter network. The question is simple to ask and surprisingly subtle to answer: how can a model that has only seen the past be trusted about the future?
The plan:
- §2.1 Data, models and loss: the three ingredients of supervised learning, and least squares from first principles.
- §2.2 Overfitting and underfitting: what goes wrong when a model is too simple or too flexible, with a slider you can play with.
- §2.3 The bias–variance tradeoff: the mathematical reason why it goes wrong, derived step by step and measured in simulation. This is the classic MDL assignment.
- §2.4 Validation and regularization: the practical cures. Train/validation/test splits, cross-validation and penalizing complexity.
Bolt has a log of past deliveries: distance (km) and minutes taken. We want a function that predicts minutes from distance for future orders. The data is noisy: the same 2 km trip took 11 minutes once (empty paths) and 16 minutes another time (the lift was broken). Our model must capture the pattern and ignore the noise. Distinguishing the two is the whole game.
Data, Models and Loss
Supervised learning has exactly three ingredients. Learn to spot them in any problem and half the battle is won.
- Data: examples \(\{(x_1,y_1), \dots, (x_n,y_n)\}\).
- A model family (hypothesis space) \(\mathcal{H}\): the shapes of function you're willing to consider.
- A loss function \(L(\hat y, y)\): how much you're penalized for predicting \(\hat y\) when the truth is \(y\).
Learning = pick the \(h \in \mathcal{H}\) that makes the average loss on the data small. Let's look at each ingredient.
Ingredient 1: data, and the assumption that makes learning possible
Why should the past say anything about the future? Only because we assume they come from the same process. Formally:
The i.i.d. assumption. Every example (training and future) is drawn independently from the same, fixed but unknown probability distribution \(P(x, y)\).
Each part of this assumption matters:
- Same distribution: if Bolt is trained on summer data and deployed in the monsoon, all bets are off. This is called distribution shift, and it is the #1 reason real models fail.
- Independent: if the 20 training deliveries were all from one rainy evening, they're not independent, and the model learns "evenings are slow" when really it's "that evening was slow."
- Unknown: if we knew \(P(x,y)\) we wouldn't need data. We'd compute the best prediction directly. Data is our only window into \(P\).
A useful way to think about the data-generating process for regression:
$$ y = f(x) + \varepsilon, \qquad \mathbb{E}[\varepsilon] = 0,\ \ \operatorname{Var}(\varepsilon) = \sigma^2 $$Here \(f\) is the true underlying pattern (the "signal") and \(\varepsilon\) is noise: everything that affects delivery time that our features don't capture (lift queues, a chatty security guard). No model can predict \(\varepsilon\), so \(\sigma^2\) is a floor on achievable error. It is called the irreducible error, and it will reappear in the bias–variance decomposition.
Ingredient 2: the model family
For Bolt's delivery times, a natural family is polynomials of degree \(d\):
$$ h_w(x) = w_0 + w_1 x + w_2 x^2 + \dots + w_d x^d = \sum_{j=0}^{d} w_j x^j $$The degree \(d\) is a hyperparameter: it controls how flexible (how "complex") the family is. \(d=0\) is a flat line, \(d=1\) a straight line, \(d=3\) can bend twice, and \(d=14\) can wiggle through 15 points exactly.
A polynomial is curved in \(x\) but linear in the weights \(w\). If we build a feature vector \(\phi(x) = (1, x, x^2, \dots, x^d)\), the model is just \(h(x) = w^\top \phi(x)\), a dot product. That's why "polynomial regression" is solved with exactly the same linear-regression machinery. This trick, make features nonlinear and keep the model linear in its weights, is used everywhere in ML.
Ingredient 3: the loss
For regression, the standard choice is squared error, \(L(\hat y, y) = (\hat y - y)^2\). Averaged over the data it gives the mean squared error:
$$ \text{MSE}(w) = \frac{1}{n}\sum_{i=1}^{n} \big(h_w(x_i) - y_i\big)^2 $$Why squared, and not absolute error \(|\hat y - y|\)?
- It is smooth, so calculus works and gives a closed-form solution (below).
- It punishes big mistakes much more than small ones. A 10-minute error costs 100, but two 5-minute errors cost only 50.
- Its minimizer is the mean: the constant \(c\) that minimizes \(\sum (c - y_i)^2\) is \(\bar y\). So squared loss makes the model predict the average outcome for each \(x\), which is exactly \(f(x)\) under our noise model. Absolute loss gives the median, which is more robust to outliers.
For classification you'll meet 0–1 loss (1 if wrong, 0 if right, so its average is the error rate) and, for trees, measures based on entropy (Chapter 6).
Training = minimizing the loss: least squares from scratch
Stack the features of all \(n\) examples into a design matrix \(X\) (one row per example) and the targets into a vector \(y\). For a straight line, row \(i\) of \(X\) is \((1, x_i)\). Then the vector of predictions is \(Xw\), and
$$ \text{MSE}(w) = \tfrac{1}{n}\,\lVert Xw - y\rVert^2 = \tfrac1n (Xw - y)^\top (Xw - y). $$This is a bowl-shaped (convex) function of \(w\). Its minimum is where the gradient is zero:
$$ \nabla_w \text{MSE} = \tfrac{2}{n} X^\top (Xw - y) = 0 \quad\Longrightarrow\quad \boxed{\,X^\top X\, w = X^\top y\,} $$These are the normal equations. Solve them and you have the best line. No iteration needed.
For \(h(x) = w_0 + w_1 x\), the normal equations reduce to the formulas you may remember from statistics:
$$ w_1 = \frac{\sum_i (x_i - \bar x)(y_i - \bar y)}{\sum_i (x_i - \bar x)^2}, \qquad w_0 = \bar y - w_1 \bar x. $$Mini example. Points \((1,2), (2,3), (3,7)\). Then \(\bar x = 2,\ \bar y = 4\). Numerator \(= (-1)(-2) + 0\cdot(-1) + (1)(3) = 5\). Denominator \(= 1 + 0 + 1 = 2\). So \(w_1 = 2.5\), \(w_0 = 4 - 2.5\cdot 2 = -1\), and the line is \(\hat y = -1 + 2.5x\). Training MSE \(= \frac13[(1.5-2)^2 + (4-3)^2 + (6.5-7)^2] = \frac13(0.25+1+0.25) = 0.5\).
Let's do it in Python
We'll simulate Bolt's world, so we know the true \(f\) and can check our work. Bolt itself never sees true_time. It only sees the noisy samples.
import numpy as np
rng = np.random.default_rng(42)
def true_time(d):
"""The 'real' (unknown to Bolt) average delivery time in minutes for distance d km."""
return 6 + 4 * d + 3 * np.sin(1.4 * d)
def make_deliveries(n):
d = rng.uniform(0, 5, n) # distances in km
t = true_time(d) + rng.normal(0, 2.0, n) # noisy observed minutes (sigma = 2)
return d, t
d_train, t_train = make_deliveries(20)
d_test, t_test = make_deliveries(1000) # "the future"
# Fit a straight line t = w0 + w1*d by least squares (normal equations)
X = np.column_stack([np.ones_like(d_train), d_train]) # design matrix, shape (20, 2)
w = np.linalg.solve(X.T @ X, X.T @ t_train)
print("w0 = %.2f min, w1 = %.2f min/km" % (w[0], w[1]))
def mse(pred, y):
return np.mean((pred - y) ** 2)
print("train MSE:", round(mse(X @ w, t_train), 2))
X_test = np.column_stack([np.ones_like(d_test), d_test])
print("test MSE:", round(mse(X_test @ w, t_test), 2))w0 = 8.55 min, w1 = 3.03 min/km
train MSE: 5.35
test MSE: 7.43
Read these numbers carefully, because they already tell the whole story of the chapter:
- The noise has \(\sigma = 2\), so the irreducible error is \(\sigma^2 = 4\). No model can average below about 4 on new data.
- Our line's test MSE is 7.43, well above 4. The line is too rigid to follow the sine-shaped bend in \(f\). That extra error is bias (§2.3).
- The training MSE (5.35) is lower than the test MSE (7.43). Training error is an optimistic estimate of future error, because the weights were chosen to fit these particular points. Never forget this.
- Use
np.linalg.lstsq(X, y)ornp.linalg.solve(X.T@X, X.T@y). Never computenp.linalg.inv(X.T@X)explicitly: it is slower and numerically unstable. - For polynomials of high degree, rescale \(x\) to about [−1, 1] first. \(5^{12} \approx 2.4\times 10^8\), and mixing such huge columns with a column of ones makes \(X^\top X\) nearly singular.
- In scikit-learn,
PolynomialFeatures(degree)+LinearRegression()does the same thing. Writing it yourself once is the best way to understand it.
Empirical risk vs. true risk
Here is the formal version of what we just saw. What we want to minimize is the true risk (expected loss on the whole distribution):
$$ R(h) = \mathbb{E}_{(x,y)\sim P}\big[L(h(x), y)\big] $$But \(P\) is unknown, so we minimize the empirical risk (average loss on the training set) instead:
$$ \hat R(h) = \frac1n \sum_{i=1}^n L(h(x_i), y_i) $$This strategy is called empirical risk minimization (ERM). For any fixed \(h\), \(\hat R(h)\) is an unbiased estimate of \(R(h)\) by the law of large numbers. But the \(h\) we pick is chosen to make \(\hat R\) small, so for that \(h\), \(\hat R\) is biased downward. The bigger and more flexible \(\mathcal{H}\) is, the more room there is to find an \(h\) that looks great on the sample by luck, and the bigger the gap \(R(\hat h) - \hat R(\hat h)\). That gap is the generalization gap, and the next section shows it growing before your eyes.
"Choose \(w\) to minimize a function" is an optimization (search) problem. Here we got lucky: MSE is convex, so calculus solves it in one shot. In Chapter 3 the objective will be bumpy or have no gradient at all (e.g. an error you can only query from a server), and we'll need hill climbing and genetic algorithms. The §3.4 lab uses a GA to choose exactly these polynomial weights.
Overfitting and Underfitting
In §2.1 a straight line was too rigid for Bolt's curved data. The obvious fix is a more flexible model. Let's see what happens when we take that fix too far.
Play first, theory second
Below, 13 training deliveries (solid dots) come from a hidden true curve (dashed green) plus noise. The hollow dots are 200 future deliveries the model never sees during training. Drag the degree slider from 0 to 12 and watch two things: the shape of the orange curve, and the two error numbers.
You should have seen three regimes:
| Degree | What the curve does | Training error | Test error | Diagnosis |
|---|---|---|---|---|
| 0–1 | Flat or straight. Can't follow the bend. | High | High | Underfitting |
| ≈ 3–5 | Follows the trend, ignores individual wobbles | Low | Low, near the noise floor | Good fit |
| 9–12 | Snakes through every training point and swings wildly between them | Very low, near 0 | Huge | Overfitting |
Now press New sample of data a few times at degree 1, then at degree 12. The degree-1 line barely moves between samples. The degree-12 curve changes completely every time. Remember this observation, because it is the key to §2.3.
Definitions
Underfitting: the model is too simple to capture the real pattern. Training error and test error are both high, and close to each other.
Overfitting: the model is flexible enough to fit the noise in the training set as if it were signal. Training error is low but test error is high. The gap between them is large.
A cleaner way to say it: an overfit model has learned facts about this particular sample that are not true of the distribution. "Deliveries of exactly 2.31 km take 17 minutes" was true once. It is not a law of nature.
Two students prepare for an exam using last year's paper. Student A memorizes every answer word for word and scores 100% on last year's paper (training error = 0). Student B learns the underlying concepts and scores 85%. On this year's paper, which has new questions from the same syllabus (the same distribution), A collapses and B scores 85% again. A overfit. A third student, C, only learned one formula and uses it for everything. C scores 40% on both papers: that's underfitting.
The same experiment in numbers
Let's reproduce the slider in code with Bolt's real units. There are 15 training deliveries, and the noise is \(\sigma=2\), so the floor is \(\sigma^2=4\).
import numpy as np
rng = np.random.default_rng(42)
def true_time(d):
return 6 + 4 * d + 3 * np.sin(1.4 * d)
def make_deliveries(n):
d = rng.uniform(0, 5, n)
return d, true_time(d) + rng.normal(0, 2.0, n)
d_train, t_train = make_deliveries(15)
d_test, t_test = make_deliveries(2000)
def poly_features(d, degree):
z = (d - 2.5) / 2.5 # rescale to [-1, 1] for numerical stability
return np.vander(z, degree + 1, increasing=True) # columns: 1, z, z^2, ..., z^degree
print("degree | train MSE | test MSE")
for degree in range(0, 15):
X = poly_features(d_train, degree)
w, *_ = np.linalg.lstsq(X, t_train, rcond=None) # least-squares fit
tr = np.mean((X @ w - t_train) ** 2)
te = np.mean((poly_features(d_test, degree) @ w - t_test) ** 2)
print(f"{degree:6d} | {tr:9.2f} | {te:10.2f}")degree | train MSE | test MSE
0 | 23.08 | 31.10
1 | 3.08 | 6.74
2 | 2.36 | 6.18
3 | 1.39 | 4.20
4 | 1.39 | 4.17
5 | 1.37 | 4.49
6 | 1.33 | 4.83
7 | 1.31 | 4.87
8 | 1.26 | 58.11
9 | 1.26 | 12.09
10 | 0.85 | 1395032.27
11 | 0.50 | 12854203.78
12 | 0.27 | 11179305209.51
13 | 0.26 | 131824576.27
14 | 0.00 | 200298536873315.25
Look at what this table shows:
- Training error only ever goes down as the degree increases. That's guaranteed: a degree-\(d{+}1\) polynomial can always copy a degree-\(d\) one by setting its top weight to 0, so its best training fit can't be worse. At degree 14 there are 15 weights for 15 points, the curve passes through every point exactly, and training MSE = 0.00.
- Test error is U-shaped. It falls from 31 (degree 0) to about 4.2 (degrees 3–4, right at the noise floor of 4), then explodes.
- The explosion is enormous: \(10^{14}\). Why? The 15 training distances don't cover [0, 5] completely. Near the edges, a high-degree polynomial is extrapolating, and polynomials go to ±∞ fast. Overfit models are most dangerous exactly where data is thin.
What makes overfitting worse, and better
| Factor | Effect on overfitting | Why |
|---|---|---|
| More flexible model (higher degree, deeper tree, more parameters) | ⬆ worse | More ways to bend toward noise |
| More training data | ⬇ better | Noise averages out. It's hard to fit 10,000 random wobbles with 13 weights. |
| More noise \(\sigma^2\) | ⬆ worse | More fake "patterns" to latch onto |
| Regularization (§2.4), pruning (§6.4) | ⬇ better | Penalizes or removes complexity |
| Early stopping, validation-based selection | ⬇ better | Stops before memorization sets in |
Try the "more data" cure mentally. With 1,000 training deliveries instead of 13, even a degree-12 polynomial has nowhere to hide: every wiggle away from the true curve would contradict hundreds of points. So "too complex" is relative to the amount of data. A degree-12 polynomial is wildly complex for 13 points and perfectly reasonable for 10,000.
- Diagnosing from training error alone. You need both numbers, and the gap between them.
- Thinking underfitting is "safe." An underfit model is also wrong, just consistently wrong. Bolt predicting 15 minutes for every order is useless.
- Thinking overfitting = high degree. Overfitting is about flexibility relative to the data. Decision trees, neural nets, even a GA run for too long (§3.4) can all overfit.
A typical question gives you a table like the one below and asks for a diagnosis.
| Model | Train error | Validation error |
|---|---|---|
| A | 0.30 | 0.32 |
| B | 0.05 | 0.07 |
| C | 0.01 | 0.25 |
A has high error and a small gap: underfitting (high bias). C has low train error and a big gap: overfitting (high variance). B is the one to deploy. The usual follow-up asks what you'd do: for A, add features or complexity. For C, get more data, regularize or simplify.
The slider showed that a complex model changes a lot when the data changes. That observation is called variance. The simple model's systematic error, the fact that a line can't bend no matter what data you give it, is called bias. §2.3 turns these two words into precise formulas and proves that test error = bias² + variance + noise.
The Bias–Variance Tradeoff
§2.2 showed us that test error is U-shaped. This section explains why, with one of the most elegant derivations in ML. By the end you'll be able to say exactly which part of a model's error comes from being too simple, which from being too twitchy, and which is nobody's fault.
The thought experiment: parallel universes
Your training set is random. If the campus had logged a different 15 deliveries last week, which it easily could have, you'd have trained a different model. So the trained model \(\hat g_{\mathcal D}\) is itself a random variable that depends on the dataset \(\mathcal D\).
Imagine running the whole experiment in many parallel universes. Each universe has its own training set \(\mathcal D_1, \mathcal D_2, \dots\) from the same distribution, and its own trained model. Now look at a fixed input \(x\), say "3 km":
- The average prediction across universes is \(\bar g(x) = \mathbb{E}_{\mathcal D}\big[\hat g_{\mathcal D}(x)\big]\).
- Bias asks: is that average prediction right? \(\text{Bias}(x) = \bar g(x) - f(x)\).
- Variance asks: how much do the universes disagree? \(\text{Var}(x) = \mathbb{E}_{\mathcal D}\big[(\hat g_{\mathcal D}(x) - \bar g(x))^2\big]\).
The decomposition, derived step by step
Setup: a new test point has \(y = f(x) + \varepsilon\) with \(\mathbb{E}[\varepsilon]=0\) and \(\operatorname{Var}(\varepsilon)=\sigma^2\). The noise \(\varepsilon\) at the test point is independent of the training set \(\mathcal D\). We want the expected test error at \(x\), averaged over both the training set and the test noise:
$$ \text{Err}(x) = \mathbb{E}_{\mathcal D,\varepsilon}\Big[\big(y - \hat g_{\mathcal D}(x)\big)^2\Big]. $$To save ink, write \(f = f(x)\), \(\hat g = \hat g_{\mathcal D}(x)\) and \(\bar g = \bar g(x)\).
Step 1: split off the noise. Substitute \(y = f + \varepsilon\):
$$ \mathbb{E}\big[(f + \varepsilon - \hat g)^2\big] = \mathbb{E}\big[(f-\hat g)^2\big] + 2\,\mathbb{E}\big[\varepsilon\,(f-\hat g)\big] + \mathbb{E}[\varepsilon^2]. $$The middle term vanishes: \(\varepsilon\) is independent of \(\hat g\) and has mean 0, so \(\mathbb{E}[\varepsilon(f-\hat g)] = \mathbb{E}[\varepsilon]\,\mathbb{E}[f-\hat g] = 0\). The last term is \(\sigma^2\). So
$$ \text{Err}(x) = \mathbb{E}_{\mathcal D}\big[(f-\hat g)^2\big] + \sigma^2. $$Step 2: add and subtract the average model. This is the trick. Insert \(-\bar g + \bar g\) inside the square:
$$ \mathbb{E}\big[(f - \bar g + \bar g - \hat g)^2\big] = (f-\bar g)^2 + 2(f-\bar g)\,\mathbb{E}\big[\bar g - \hat g\big] + \mathbb{E}\big[(\bar g - \hat g)^2\big]. $$\((f-\bar g)\) is not random (both are fixed numbers at \(x\)), so it comes outside the expectation. And \(\mathbb{E}[\bar g - \hat g] = \bar g - \mathbb{E}[\hat g] = \bar g - \bar g = 0\) by definition of \(\bar g\). The cross term vanishes again!
Result:
$$ \boxed{\ \mathbb{E}\big[(y-\hat g_{\mathcal D}(x))^2\big] \;=\; \underbrace{\big(\bar g(x) - f(x)\big)^2}_{\text{bias}^2} \;+\; \underbrace{\mathbb{E}_{\mathcal D}\big[(\hat g_{\mathcal D}(x) - \bar g(x))^2\big]}_{\text{variance}} \;+\; \underbrace{\sigma^2}_{\text{irreducible noise}}\ } $$Average this over all test inputs \(x\) and you get the expected test MSE. Every term is non-negative, so to get low test error you need both low bias and low variance. Nothing can remove \(\sigma^2\).
- Bias² is the error of the average model. It measures what your model family can't represent, even with infinite data spread over infinite universes. A straight line can never bend, so its bias stays high no matter what.
- Variance is how much your model depends on the luck of the sample. A degree-12 polynomial bends toward every noisy point, so different samples give wildly different curves.
- Noise is the part of \(y\) your features can't explain. Lowering it needs better features (e.g. add "is the lift broken?"), not a better model.
The tradeoff
When you increase model complexity:
- Bias goes down. A richer family contains functions closer to \(f\).
- Variance goes up. More freedom means more ways to chase noise.
Their sum is U-shaped, and that is exactly the test-error curve from §2.2. The sweet spot is where the decrease in bias² no longer pays for the increase in variance.
Measure it yourself. The widget trains 30 models of the chosen degree on 30 independent datasets (30 universes). It draws them all, plus their average \(\bar g\), and computes bias² and variance numerically. The bar chart shows the decomposition for every degree.
Things to notice:
- At degree 0–1 the 30 fits are tightly bunched (low variance), but their average is far from green (high bias).
- At degree 3–4 the average almost sits on the true curve, and the spread is modest.
- At degree 8–10 the average is still close to the truth (low bias!), but individual fits fly everywhere. All the error is variance.
Simulating it in Python
This is the template for the classic MDL assignment. Read it until every line makes sense.
import numpy as np
rng = np.random.default_rng(0)
def true_time(d):
return 6 + 4 * d + 3 * np.sin(1.4 * d)
SIGMA = 2.0
def poly_features(d, degree):
return np.vander((d - 2.5) / 2.5, degree + 1, increasing=True)
d_grid = np.linspace(0.5, 4.5, 50) # where we measure bias and variance
n_datasets, n_points = 500, 25
print("degree | bias^2 | variance | bias^2+var+noise")
for degree in [0, 1, 3, 6, 10]:
preds = np.empty((n_datasets, len(d_grid)))
for k in range(n_datasets): # many parallel universes...
d = rng.uniform(0, 5, n_points)
t = true_time(d) + rng.normal(0, SIGMA, n_points)
w, *_ = np.linalg.lstsq(poly_features(d, degree), t, rcond=None)
preds[k] = poly_features(d_grid, degree) @ w
g_bar = preds.mean(axis=0) # the "average model"
bias2 = np.mean((g_bar - true_time(d_grid)) ** 2)
var = np.mean(preds.var(axis=0))
print(f"{degree:6d} | {bias2:7.3f} | {var:8.3f} | {bias2 + var + SIGMA**2:8.3f}")degree | bias^2 | variance | bias^2+var+noise
0 | 10.052 | 1.200 | 15.253
1 | 2.237 | 0.528 | 6.764
3 | 0.110 | 0.580 | 4.690
6 | 0.010 | 3.892 | 7.902
10 | 2.253 | 1402.825 | 1409.078
The pattern is textbook: bias² falls 10.05 → 2.24 → 0.11 → 0.01 while variance rises 0.53 → 0.58 → 3.89 → 1403. Degree 3 has the smallest total. Two subtleties are worth noticing:
- Degree 0 has more variance than degree 1 (1.20 vs 0.53). A flat line's height depends on which distances happened to be sampled, while a sloped line adapts to that. The tradeoff is a trend, not a law that holds at every single step.
- At degree 10, the measured bias² rises again (2.25). With variance that large, even 500 universes aren't enough to average out the wild fits, so \(\bar g\) is estimated badly. High variance makes everything harder to measure, bias included.
The typical assignment gives you a training set and a test set and asks you to:
- Split the training data into \(K\) parts (say 10 or 20). Each part plays one "universe."
- For each degree 1…\(d_{\max}\), fit one model per part. With scikit-learn that's
PolynomialFeatures+LinearRegression. - Predict on the same test points with all \(K\) models, then compute bias² and variance per test point and average them.
- Tabulate and plot bias², variance and total error against degree, then explain the tradeoff.
The trap: in the assignment you don't know \(f\). You only have noisy test labels \(y\). If you compute "bias²" as \((\bar g(x) - y)^2\), you are actually measuring \((\bar g - f)^2 + \)noise, so it absorbs \(\sigma^2\). Then irreducible error estimated as \(\text{MSE} - \text{bias}^2 - \text{variance}\) comes out close to 0 (sometimes slightly negative from rounding). Explain this in your report instead of being confused by it. Also say clearly whether your "bias" column is bias or bias², because rubrics check this.
Bias and variance beyond polynomials
The decomposition is exact for squared loss. The intuition applies everywhere, and you'll meet it in every chapter:
| Model | Knob | Low setting → | High setting → |
|---|---|---|---|
| Polynomial | degree | high bias | high variance |
| Decision tree (Ch 6) | max depth | high bias (a stump) | high variance (one leaf per example) |
| Ridge regression (§2.4) | penalty \(\lambda\) | high variance | high bias |
| k-nearest neighbours | k | high variance (k=1) | high bias (k=n) |
| Bayes net (Ch 7) | number of edges | high bias (too many independence assumptions) | high variance (huge CPTs from little data) |
- Ensembles such as bagging and random forests fight variance directly. They actually train several models on resampled data and average them, building a real-life \(\bar g\). Since \(\bar g\) has zero variance by definition, averaging helps. This is why random forests (built from the decision trees of Ch 6) work so well.
- In §3.4, a genetic algorithm must pick weights that generalize. Its fitness function must therefore include validation error, or the GA will happily evolve a high-variance model.
- "Derive the bias–variance decomposition." Reproduce the two steps above. State the assumptions (\(\mathbb{E}[\varepsilon]=0\), noise independent of \(\mathcal D\)) and show why each cross term is zero. That's where the marks are.
- "What happens to bias/variance if we get more data?" Variance ↓ (the fits stabilize). Bias stays roughly the same (it's a property of the model family). Noise is unchanged.
- "What happens if we add a useful feature?" Bias ↓ (and the effective noise ↓, since less of \(y\) is unexplained). Variance ↑ slightly (one more parameter).
Fighting Overfitting: Validation and Regularization
We now understand the disease. The model's flexibility has to match the data, and test error is bias² + variance + noise. This section covers the two standard cures:
- Validation: measure generalization honestly, so you can choose the complexity knob scientifically.
- Regularization: keep a flexible model but discourage it from using its flexibility unless the data really demands it.
The three-way split
You can't tune the degree by looking at training error, which always prefers the most complex model. You also can't tune it on the test set, for a subtle but critical reason:
Any data you use to make a decision becomes, in effect, training data. If you choose the degree because it does best on the test set, the test error of the chosen model is optimistically biased, in exactly the way training error is. The test set must be touched once, at the very end.
So we split the labelled data three ways:
| Set | Typical share | Used for | Analogy |
|---|---|---|---|
| Training | 60–80% | Fitting parameters \(w\) | Textbook exercises |
| Validation | 10–20% | Choosing hyperparameters (degree, \(\lambda\), tree depth, GA settings), early stopping | Mock exams |
| Test | 10–20% | One final, honest estimate of future error | The real exam, sat once |
Leakage is any way information from validation or test data sneaks into training. Classic examples:
- Normalizing features with the mean and std of the whole dataset before splitting. Compute them on the training set only.
- Duplicate or near-duplicate examples landing in both train and test.
- Tuning on the test set "just once more."
- Time-series data split randomly, so the model is trained on the future to predict the past.
Leakage gives beautiful numbers that collapse in deployment.
k-fold cross-validation
With only 40 labelled deliveries, holding out 10 for validation wastes data and gives a noisy estimate. k-fold cross-validation fixes both problems:
- Split the (non-test) data into \(k\) equal folds.
- For each fold \(i\): train on the other \(k-1\) folds and measure error on fold \(i\).
- Average the \(k\) errors. That's the CV estimate for this hyperparameter setting.
- Repeat for each candidate setting, pick the best, then retrain on all the non-test data with that setting.
The extreme case \(k=n\) is leave-one-out CV: almost unbiased but expensive. \(k=5\) or \(10\) is the usual compromise.
import numpy as np
rng = np.random.default_rng(2)
def true_time(d):
return 6 + 4 * d + 3 * np.sin(1.4 * d)
def make_deliveries(n):
d = rng.uniform(0, 5, n)
return d, true_time(d) + rng.normal(0, 2.0, n)
def poly_features(d, degree):
return np.vander((d - 2.5) / 2.5, degree + 1, increasing=True)
d_all, t_all = make_deliveries(40) # all the labelled data we have
d_test, t_test = make_deliveries(2000) # locked away until the very end
def kfold_mse(d, t, degree, k=5):
idx = np.arange(len(d))
folds = np.array_split(idx, k)
errs = []
for f in folds:
train = np.setdiff1d(idx, f)
w, *_ = np.linalg.lstsq(poly_features(d[train], degree), t[train], rcond=None)
errs.append(np.mean((poly_features(d[f], degree) @ w - t[f]) ** 2))
return np.mean(errs)
cv = {deg: kfold_mse(d_all, t_all, deg) for deg in range(0, 11)}
for deg, e in cv.items():
print(f"degree {deg:2d}: 5-fold CV MSE = {e:8.2f}")
best = min(cv, key=cv.get)
print("chosen degree:", best)
# retrain on ALL 40 points with the chosen degree, then touch the test set ONCE
w, *_ = np.linalg.lstsq(poly_features(d_all, best), t_all, rcond=None)
print("final test MSE: %.2f" % np.mean((poly_features(d_test, best) @ w - t_test) ** 2))degree 0: 5-fold CV MSE = 23.33
degree 1: 5-fold CV MSE = 8.28
degree 2: 5-fold CV MSE = 7.34
degree 3: 5-fold CV MSE = 5.77
degree 4: 5-fold CV MSE = 6.55
degree 5: 5-fold CV MSE = 7.73
degree 6: 5-fold CV MSE = 7.08
degree 7: 5-fold CV MSE = 13.51
degree 8: 5-fold CV MSE = 44.50
degree 9: 5-fold CV MSE = 20.84
degree 10: 5-fold CV MSE = 68.31
chosen degree: 3
final test MSE: 4.54
CV found the U-shape and chose degree 3, and the untouched test set confirms it: 4.54, close to the noise floor of 4. Notice that the CV numbers are noisy (degree 6 beats degree 5, degree 9 beats degree 8). CV estimates are random variables too. When two settings are close, prefer the simpler one. Some people use the one-standard-error rule: pick the simplest model whose CV error is within one standard error of the best.
Regularization: penalize complexity directly
Choosing the degree is a coarse knob: 3 or 4, nothing in between. Regularization gives a smooth knob. Keep a flexible model, but add a penalty for large weights to the loss:
$$ J(w) = \underbrace{\sum_{i=1}^n \big(w^\top\phi(x_i) - y_i\big)^2}_{\text{fit the data}} \;+\; \underbrace{\lambda \sum_{j\ge1} w_j^2}_{\text{stay simple}} \qquad\text{(ridge / L2 regularization)} $$Why do large weights mean complexity? Look back at the overfit curves. To snake through every point, a degree-12 polynomial needs huge coefficients of alternating sign that nearly cancel each other. In the run below the unregularized weights have norm about 5 million. Smooth functions only need modest weights. Penalizing \(\lVert w\rVert^2\) therefore penalizes wiggliness.
Setting the gradient to zero gives a closed form, almost the same as the normal equations:
$$ (X^\top X + \lambda I')\,w = X^\top y \qquad (I' = \text{identity with a 0 for the intercept, which we don't penalize}) $$A bonus: adding \(\lambda I'\) makes the matrix well-conditioned, so ridge also fixes the numerical problems of high-degree fits.
import numpy as np
rng = np.random.default_rng(42)
def true_time(d):
return 6 + 4 * d + 3 * np.sin(1.4 * d)
def make_deliveries(n):
d = rng.uniform(0, 5, n)
return d, true_time(d) + rng.normal(0, 2.0, n)
def poly_features(d, degree):
return np.vander((d - 2.5) / 2.5, degree + 1, increasing=True)
d_tr, t_tr = make_deliveries(15)
d_te, t_te = make_deliveries(2000)
def ridge_fit(X, y, lam):
"""Minimize ||Xw - y||^2 + lam * ||w[1:]||^2 (don't penalize the intercept)."""
P = np.eye(X.shape[1]); P[0, 0] = 0
return np.linalg.solve(X.T @ X + lam * P, X.T @ y)
X_tr, X_te = poly_features(d_tr, 12), poly_features(d_te, 12)
for lam in [0, 1e-4, 1e-2, 1, 100]:
w = ridge_fit(X_tr, t_tr, lam)
print(f"lambda={lam:<7g} train={np.mean((X_tr@w-t_tr)**2):6.2f} "
f"test={np.mean((X_te@w-t_te)**2):12.2f} |w|={np.linalg.norm(w):10.1f}")lambda=0 train= 0.27 test=11162182397.57 |w|= 5174896.9
lambda=0.0001 train= 1.27 test= 5.57 |w|= 40.7
lambda=0.01 train= 1.31 test= 4.31 |w|= 18.2
lambda=1 train= 1.81 test= 4.67 |w|= 16.9
lambda=100 train= 19.93 test= 27.22 |w|= 17.7
This is the same degree-12 model that was a disaster in §2.2. A tiny penalty, \(\lambda = 0.01\), takes test MSE from \(10^{10}\) to 4.31, which is as good as the hand-picked cubic. Too much penalty (\(\lambda=100\)) flattens the model into underfitting. \(\lambda\) is a bias–variance dial: small \(\lambda\) means low bias and high variance, large \(\lambda\) the reverse. And how do you choose \(\lambda\)? With cross-validation, of course.
L2 vs L1
| Ridge (L2): \(\lambda\sum w_j^2\) | Lasso (L1): \(\lambda\sum |w_j|\) | |
|---|---|---|
| Effect | Shrinks all weights smoothly toward 0 | Drives many weights to exactly 0 |
| Result | Small, spread-out weights | Sparse model, i.e. automatic feature selection |
| Closed form? | Yes | No (needs iterative optimization) |
| Bayesian view | Gaussian prior on \(w\) | Laplace prior on \(w\) |
The "Bayesian view" row is not a footnote. Minimizing squared error + \(\lambda\lVert w\rVert^2\) is exactly finding the most probable weights (MAP estimate) when you believe beforehand that weights are probably small (a Gaussian prior) and the noise is Gaussian. Regularization = data + prior belief, combined with Bayes' rule (Ch 4). Overfitting is what happens when you trust the data completely and have no prior at all.
Other weapons against overfitting
- Early stopping: when training iteratively (gradient descent, a GA over generations), monitor validation error and stop when it starts rising. You'll use this in the GA lab.
- Pruning: grow a big decision tree, then cut branches that don't help on validation data (§6.4).
- More data / data augmentation: the most reliable cure for variance.
- Ensembles: average many models (bagging, random forests).
- Simpler features: drop irrelevant inputs, since each one is a new way to fit noise.
Learning curves: is more data worth buying?
Plot training and validation error against training-set size for a fixed model:
- High-bias model: both curves plateau quickly at a high level, close together. More data won't help. Use a richer model.
- High-variance model: a large gap that slowly closes as data grows. More data will help.
This is the most practical diagnostic in the chapter: it tells you whether to spend next week collecting data or redesigning the model.
Chapter summary
- Learning minimizes empirical risk, but we care about true risk on unseen data from the same distribution (i.i.d.).
- Training error always falls with complexity. Test error is U-shaped.
- Expected test error = bias² + variance + σ². Simple models have high bias, flexible models high variance, and noise is irreducible.
- Choose complexity with a validation set or k-fold CV. Use the test set once.
- Regularization (\(\lambda\lVert w\rVert^2\)) is a smooth bias–variance dial, and is equivalent to a prior belief.
The engineers move Bolt's predictor onto a cheap microcontroller and lose access to the training data. All they can do is send a weight vector to a server and get back its training and validation error. There is no gradient and no formula, only "try a vector, get a score." How do you find good weights now? Welcome to Chapter 3: local search and genetic algorithms.
Local Search and Genetic Algorithms
In Chapter 2 we said "learning is search." That chapter cheated a little: squared error has a perfectly smooth, bowl-shaped landscape, so calculus jumped straight to the bottom. This chapter covers what to do when the landscape is rough, the gradient is unavailable, or the space is huge and discrete.
Many real problems look like this:
- Schedule exams for 3,000 students with no clashes (discrete, astronomically many options).
- Find the layout of a delivery route visiting 30 hostels (travelling salesman).
- Tune a model's weights when you can only query its error from a server: a black box with no gradient. This is the MDL genetic-algorithm assignment.
- Choose which of 20 orders Bolt should carry tonight (knapsack).
All of these share one structure: there is a state (a candidate solution), an objective that scores it, and a notion of neighbouring states. We don't care about the path to the answer, only the answer itself. That is what makes a problem a local search (or optimization) problem.
- §3.1 Hill climbing: the simplest local search, and the three ways it gets stuck.
- §3.2 Simulated annealing and beam search: escaping local optima with controlled randomness and with populations.
- §3.3 Genetic algorithms: evolution as an algorithm. Representation, selection, crossover and mutation, worked by hand.
- §3.4 Lab: evolving a model that generalizes: Chapter 2 and Chapter 3 meet. A GA tunes the weights of an overfit model through a black-box error server.
Bolt's predictor runs on a microcontroller. The engineers have an overfit 11-weight polynomial (degree 10) and a server that, given any weight vector, returns its training and validation error. There's no gradient and no access to the data, and every query costs time. Can we search the 11-dimensional weight space intelligently enough to find a vector that generalizes?
Search as Optimization: Hill Climbing
The state-space landscape
Picture every possible candidate solution laid out on the ground, with the height at each spot equal to the solution's objective value. Optimizing means finding the highest peak (the global maximum). If the objective is a cost, as in Chapter 2's MSE, you flip the picture and look for the lowest valley, the global minimum. The two are equivalent: maximize \(f\) = minimize \(-f\).
A local search algorithm needs three things:
- A state representation: what one candidate looks like (a weight vector, a bitstring, a permutation of hostels).
- An objective function \(f(\text{state})\): higher is better (or "cost", lower is better).
- A neighbourhood: which states are reachable by one small change (nudge one weight, flip one bit, swap two hostels).
Local search keeps only the current state (or a few) in memory and moves to neighbours. Two big advantages follow: it uses constant memory, and it works in spaces far too large to enumerate, including infinite or continuous ones.
Hill climbing
The simplest idea of all: look at your neighbours, move to the best one, and repeat until no neighbour is better.
function HILL-CLIMBING(problem):
current ← a starting state (often random)
loop:
neighbour ← the highest-valued successor of current
if value(neighbour) ≤ value(current):
return current # a peak (maybe only a local one!)
current ← neighbour
It's also called greedy local search, because it always grabs the best immediate improvement without thinking ahead. In continuous spaces, "move in the direction of steepest improvement" becomes gradient ascent/descent, which is the algorithm that trains almost all of modern ML. Hill climbing is its discrete ancestor.
Worked example: 8-queens
Place 8 queens on a chessboard so that no two attack each other (same row, column or diagonal). Here is a local-search formulation:
- State: one queen per column, so a state is 8 numbers: the row of each column's queen. There are \(8^8 \approx 16.7\) million states.
- Cost \(h\): the number of pairs of queens attacking each other. Goal: \(h = 0\).
- Neighbours: move one queen to another square in its column: \(8 \times 7 = 56\) neighbours.
import random
def conflicts(state):
"""Number of pairs of queens attacking each other. state[c] = row of the queen in column c."""
n, h = len(state), 0
for i in range(n):
for j in range(i + 1, n):
if state[i] == state[j] or abs(state[i] - state[j]) == j - i:
h += 1
return h
def hill_climb(n=8, rng=random):
state = [rng.randrange(n) for _ in range(n)]
steps = 0
while True:
best, best_h = None, conflicts(state)
for col in range(n): # all n*(n-1) neighbours: move one queen in its column
for row in range(n):
if row == state[col]:
continue
nb = state.copy(); nb[col] = row
h = conflicts(nb)
if h < best_h:
best, best_h = nb, h
if best is None: # no neighbour is better: local minimum
return state, conflicts(state), steps
state, steps = best, steps + 1
rng = random.Random(1)
results = [hill_climb(rng=rng) for _ in range(1000)]
solved = [r for r in results if r[1] == 0]
print("solved: %.1f%% of runs" % (100 * len(solved) / len(results)))
print("avg steps when solved: %.1f" % (sum(r[2] for r in solved) / len(solved)))
print("avg steps when stuck : %.1f" % (sum(r[2] for r in results if r[1] > 0) / (len(results) - len(solved))))
def random_restart(n=8, rng=random):
restarts = 0
while True:
state, h, _ = hill_climb(n, rng)
if h == 0:
return state, restarts
restarts += 1
state, restarts = random_restart(rng=rng)
print("solution:", state, "after", restarts, "restarts")solved: 15.6% of runs
avg steps when solved: 4.2
avg steps when stuck : 3.1
solution: [0, 5, 7, 2, 6, 3, 1, 4] after 1 restarts
These numbers match the classic result in AIMA §4.1 (14% solved, 4 steps on average when it works, 3 when it gets stuck). Hill climbing is very fast, a handful of steps, but it fails about 85% of the time. Why?
The three ways hill climbing gets stuck
- Local maxima: a peak that is higher than all its neighbours but lower than the global maximum. Hill climbing stops there, because every move looks worse.
- Plateaus: flat areas where all neighbours have the same value. There is no uphill direction to follow, so the algorithm wanders or stops. A shoulder is a plateau that does eventually rise again.
- Ridges: a sequence of local maxima arranged diagonally. Every single-step move goes downhill even though the ridge itself rises, because the neighbourhood moves are axis-aligned while the ridge is diagonal. This matters a lot for the GA lab: polynomial weights are tightly coupled, so changing one weight alone almost always makes things worse.
Try it on a bumpy 1-D landscape. Hill climbing from the left usually stops on the first or second hump. Then switch to random-restart.
Variants that help
| Variant | Idea | Fixes |
|---|---|---|
| Steepest-ascent | Evaluate all neighbours, take the best (what we did above) | — |
| First-choice | Generate random neighbours until one is better, then take it | Neighbourhoods too large to scan (thousands of neighbours) |
| Stochastic | Choose randomly among uphill moves, weighted by steepness | Sometimes finds better peaks |
| Sideways moves | Allow moves to equal-valued neighbours (with a limit, e.g. 100) | Plateaus and shoulders. 8-queens success rises from 14% to 94%! |
| Random-restart | "If at first you don't succeed, try, try again": restart from a random state until solved | Local maxima, in probability |
How many restarts do we need?
If one run succeeds with probability \(p\), the number of runs until the first success follows a geometric distribution, with expected value \(1/p\). For 8-queens, \(p \approx 0.14\), so about \(1/0.14 \approx 7\) runs (6 failures + 1 success). Expected total steps ≈ \(1 \times 4 + 6 \times 3 = 22\). That's tiny! Random-restart hill climbing is complete with probability 1: it will eventually find a solution if one exists, because every restart has a nonzero chance.
- Know the 3 failure modes by name, with a picture: local maxima, plateaus (and shoulders), ridges.
- "Expected number of restarts = \(1/p\)" is a free mark. Remember that it counts runs, including the successful one.
- Hill climbing is neither complete nor optimal. Random restart makes it complete (with probability 1) but not efficient in general.
- Be ready to run one step by hand: list all neighbours' values and pick the best.
Gradient descent on the MSE of Chapter 2 is hill climbing with an infinitely fine neighbourhood. It never gets stuck there because MSE for linear models is convex: one valley, no local minima. Neural network losses are not convex, which is why deep learning borrows the tricks in this chapter: random initialization (restarts), noise in stochastic gradient descent (annealing) and populations of models (ensembles).
Escaping Local Optima: Annealing and Beam Search
Hill climbing never goes downhill, so it can't leave a local peak. A purely random walk goes anywhere but never settles. The two ideas in this section sit between those extremes: sometimes accept a worse move (simulated annealing), or keep several candidates alive at once (beam search). Genetic algorithms, in §3.3, combine both ideas.
Simulated annealing
The name comes from metallurgy. To make strong steel you heat it until its atoms move freely, then cool it slowly. At high temperature the atoms jump around, even into higher-energy arrangements. As it cools they settle, and a slow cooling lets them find a very low-energy crystal structure. Quench it (cool it instantly) and the atoms freeze in a messy, brittle state: a local minimum.
Simulated annealing (SA) copies this:
function SIMULATED-ANNEALING(problem, schedule):
current ← initial state
for t = 1, 2, 3, ...:
T ← schedule(t) # temperature, decreasing over time
if T ≈ 0: return current
next ← a RANDOM neighbour of current
ΔE ← value(next) − value(current) # for maximization
if ΔE > 0: current ← next # uphill: always accept
else: current ← next with probability e^(ΔE / T) # downhill: sometimes
Understanding the acceptance probability \(e^{\Delta E/T}\)
For a bad move, \(\Delta E < 0\), so \(\Delta E / T < 0\) and \(e^{\Delta E/T}\) lies between 0 and 1. This one formula has two properties:
- Worse moves are less likely: a larger \(|\Delta E|\) means a smaller probability.
- Higher temperature means more adventurous: when \(T\) is large, \(\Delta E/T \approx 0\) and \(e^0 = 1\), so almost everything is accepted (a random walk). As \(T \to 0\), the probability of any downhill move goes to 0, which is pure hill climbing.
| \(T = 2\) | \(T = 0.5\) | \(T = 0.1\) | |
|---|---|---|---|
| \(\Delta E = -1\) (slightly worse) | \(e^{-0.5} = 0.607\) | \(e^{-2} = 0.135\) | \(e^{-10} \approx 0.00005\) |
| \(\Delta E = -3\) (much worse) | \(e^{-1.5} = 0.223\) | \(e^{-6} = 0.0025\) | \(e^{-30} \approx 0\) |
Imagine shaking a tray with a ping-pong ball on a bumpy surface, trying to get the ball into the deepest hole. Shake hard at first: the ball bounces out of shallow holes easily, but it's harder to bounce out of deep ones. Then shake more and more gently. The ball spends more time in deep holes, and when you stop it is very likely in the deepest one. Temperature is how hard you shake.
Cooling schedules
- Geometric: \(T_{t+1} = \alpha T_t\) with \(\alpha \in [0.8, 0.999]\). By far the most common in practice.
- Linear: \(T_t = T_0 - ct\).
- Logarithmic: \(T_t = c / \log(1+t)\). Theory says that if \(T\) is lowered slowly enough (logarithmically), SA finds the global optimum with probability approaching 1. That is far too slow to use, but it is a nice guarantee.
Choosing \(T_0\): pick it so that, at the start, a typical bad move is accepted perhaps 50–80% of the time.
Back on the bumpy landscape, select Simulated annealing. Watch the dot jump around wildly at first and settle as \(T\) drops. Try a very fast cooling rate (α = 0.9), which "quenches" the search, and compare it with a slow one (0.995).
SA on 8-queens
import math, random
def conflicts(state):
n, h = len(state), 0
for i in range(n):
for j in range(i + 1, n):
if state[i] == state[j] or abs(state[i] - state[j]) == j - i:
h += 1
return h
def simulated_annealing(n=8, T0=2.0, alpha=0.995, max_steps=20000, rng=random):
state = [rng.randrange(n) for _ in range(n)]
E, T = conflicts(state), T0
for step in range(max_steps):
if E == 0:
return state, step
col, row = rng.randrange(n), rng.randrange(n) # a RANDOM neighbour, not the best one
nb = state.copy(); nb[col] = row
dE = conflicts(nb) - E # we are minimizing conflicts
if dE <= 0 or rng.random() < math.exp(-dE / T): # always accept better; sometimes worse
state, E = nb, E + dE
T = max(T * alpha, 1e-3) # cool down
return state, None
rng = random.Random(0)
runs = [simulated_annealing(rng=rng) for _ in range(200)]
ok = [s for s, steps in runs if steps is not None]
print("solved: %d / %d runs" % (len(ok), len(runs)))
print("median steps: %d" % sorted(st for _, st in runs if st is not None)[len(ok) // 2])solved: 195 / 200 runs
median steps: 725
Compare with plain hill climbing's 15.6%: SA solves 97.5% of runs. Each SA step is cheaper (it evaluates one random neighbour, not all 56), but it needs many more steps. Because we're minimizing cost here, the test is \(e^{-\Delta E/T}\) with \(\Delta E = \text{cost}(\text{next}) - \text{cost}(\text{current})\). Read the sign convention of every formula carefully in exams.
Local beam search
Instead of one current state, keep \(k\) of them:
- Start with \(k\) random states.
- Generate all successors of all \(k\) states.
- If any is a goal, stop. Otherwise keep the best \(k\) successors from the whole pool and repeat.
This is not the same as \(k\) independent restarts running in parallel. In beam search the \(k\) states share information: if one state finds a great region, its successors crowd out the successors of poor states, so effort moves to where the action is. "Come over here, the grass is greener!"
The danger is lack of diversity: all \(k\) states can quickly collapse into the same small region, which is just an expensive hill climb. The fix is stochastic beam search: choose the \(k\) survivors randomly, with probability increasing with their value. Now think of the \(k\) states as organisms, their successors as offspring and value as fitness. That's natural selection, one step away from a genetic algorithm.
Comparison so far
| Algorithm | Memory | Escapes local optima? | Key knob |
|---|---|---|---|
| Hill climbing | 1 state | No | neighbourhood |
| Random-restart HC | 1 state | Yes, by restarting | number of restarts |
| Simulated annealing | 1 state | Yes, by accepting bad moves | temperature schedule |
| Local beam search | \(k\) states | Partly (can lose diversity) | \(k\) |
| Stochastic beam | \(k\) states | Better | \(k\), selection pressure |
| Genetic algorithm (next) | population | Yes, by crossover + mutation | pop size, \(p_c\), \(p_m\), selection |
- The exploration vs. exploitation tension shows up here first: high temperature explores, low temperature exploits. It comes back in MDPs and reinforcement learning (Ch 5): should Bolt try a new route (explore) or take the known-good one (exploit)?
- The acceptance probability \(e^{\Delta E/T}\) is a Boltzmann distribution. The same exponential form appears in the softmax function of neural nets and in Gibbs sampling for Bayes nets (§7.4).
Genetic Algorithms
Evolution is the most successful optimizer we know of. With no gradient, no plan and no understanding, it produced eyes, wings and brains, just by repeating three steps over and over: variation (offspring differ from their parents), selection (fitter individuals reproduce more) and inheritance (offspring resemble their parents). John Holland turned this into an algorithm in the 1970s. A genetic algorithm (GA) is stochastic beam search where successors are made by combining two parents, not by modifying one state.
The vocabulary
| Biology | GA | Bolt's knapsack (next code) |
|---|---|---|
| Individual / chromosome | One candidate solution, encoded as a string | 20 bits: carry order \(i\) or not |
| Gene | One position in the string | one bit |
| Allele | A value a gene can take | 0 or 1 |
| Population | The current set of candidates | 60 loading plans |
| Fitness | Objective value (higher is better) | total tips, if not overweight |
| Generation | One iteration of the loop | — |
| Genotype vs phenotype | Encoding vs what it means | bitstring vs the actual set of orders |
The algorithm
function GENETIC-ALGORITHM(population, FITNESS):
repeat:
new_population ← elite (the best few, copied unchanged) # optional elitism
while |new_population| < N:
x ← SELECT(population, FITNESS) # fitter ⇒ more likely
y ← SELECT(population, FITNESS)
child ← CROSSOVER(x, y) with prob p_c (else copy a parent)
child ← MUTATE(child) each gene with small prob p_m
add child to new_population
population ← new_population
until some individual is fit enough, or time/budget runs out
return the best individual seen
Now let's look at each component properly. Each one is a design decision that can make a GA succeed or fail.
1. Representation (encoding)
How you encode a solution decides what crossover and mutation mean. Here are the common choices:
- Binary strings: classic. Good for yes/no decisions (knapsack, feature selection). Numbers can be binary-encoded too: \(x \in \{0,\dots,31\}\) uses 5 bits.
- Real-valued vectors: each gene is a float. This is natural for weights, as in the GA lab.
- Permutations: orderings (routes for the travelling salesman). These need special operators, because ordinary crossover would visit some hostels twice and others never.
- Integer strings: the 8-queens state "16257483" (row of each column's queen).
A good encoding puts related genes close together and ensures that small genotype changes give small phenotype changes. With plain binary, 7 = 0111 and 8 = 1000 differ in all 4 bits. Gray code fixes this, because neighbouring integers differ in exactly one bit.
2. Fitness
Fitness is the objective. Selection only uses comparisons or proportions of fitness, so the design questions are:
- Constraints. What if a child is infeasible, such as an overloaded knapsack? Either repair it, or penalize it: fitness = value − (penalty × amount of violation).
- What do you really want? In the lab, minimizing training error would evolve an overfit model, so fitness must include validation error. A GA optimizes exactly what you write, not what you mean. Remember the dirt-sucking vacuum from §1.1.
- Cost. Fitness evaluation usually dominates the runtime (or, in the assignment, the query budget).
3. Selection
Selection decides who gets to reproduce. The core tension is selection pressure. Too little and the GA is a random search. Too much and the population fills with copies of one early-good individual (premature convergence), losing the diversity crossover needs.
Roulette-wheel (fitness-proportionate) selection
Individual \(i\) is chosen with probability \(p_i = f_i / \sum_j f_j\). Picture a roulette wheel where each individual's slice is proportional to its fitness.
This is the classic textbook example (Goldberg, 1989). Initial population:
| # | String | \(x\) | \(f(x)=x^2\) | \(p_i = f_i/\sum f\) | Expected copies \(N p_i\) |
|---|---|---|---|---|---|
| 1 | 01101 | 13 | 169 | 0.144 | 0.58 |
| 2 | 11000 | 24 | 576 | 0.492 | 1.97 |
| 3 | 01000 | 8 | 64 | 0.055 | 0.22 |
| 4 | 10011 | 19 | 361 | 0.309 | 1.23 |
| Σ = 1170, avg 292.5 | 1.000 | 4.00 |
Suppose the four spins pick #1, #2, #2, #4. Pair them as (#1, #2) and (#2, #4), and apply one-point crossover:
0110|1×1100|0with the cut after bit 4 gives01100(12) and11001(25).11|000×10|011with the cut after bit 2 gives11011(27) and10000(16).
New fitnesses: 144, 625, 729, 256. Sum = 1754, average 438.5, max 729 (up from 576). One generation raised the average fitness by 50%, without anyone "knowing" that bigger \(x\) is better.
Roulette has known problems:
- It needs non-negative fitness. Shift the values, or use another method.
- It is sensitive to scaling. If one individual has fitness 1000 and the rest have 10, it takes over immediately (premature convergence). Late in a run, when everyone has fitness 100 ± 1, selection is nearly uniform and the pressure is too low.
Tournament selection (the practical default)
Pick \(k\) individuals at random and return the best of them. \(k\) controls the pressure: \(k=1\) is random selection, and a large \(k\) is very greedy. Tournament selection only compares fitness values, so it doesn't care about scale or sign, and it is cheap and easy to parallelize. \(k = 2\) or \(3\) is common.
Rank selection and truncation
- Rank selection: sort by fitness, and make the selection probability depend on rank, not raw fitness. This fixes the scaling problems.
- Truncation selection: only the top \(\tau\)% (say 50%) may breed, uniformly. It's simple and strong, and it's what the lab code uses.
4. Crossover (recombination)
Crossover is what makes a GA more than parallel hill climbing. It combines good parts of different parents.
- One-point: choose a cut point, swap the tails. It keeps contiguous blocks of genes together.
- Two-point / k-point: swap the middle segment(s).
- Uniform: each gene comes from either parent with probability ½. Lots of mixing, and it ignores gene order.
- Arithmetic / blend (real genes): child \(= \alpha a + (1-\alpha) b\), a point on the line between the parents.
- Order crossover (OX) (permutations): copy a slice from parent 1, then fill the rest in parent 2's order, skipping duplicates.
Crossover is applied with probability \(p_c\) (typically 0.6–0.95). Otherwise the parents are copied unchanged.
Why should mixing two good solutions produce a better one? Holland's answer: good solutions contain short, useful building blocks, such as "genes 3–5 = 101" in the knapsack, meaning "carry these three light, high-tip orders together." A schema like **101*** describes all strings with that block. The schema theorem says that short, low-order schemata with above-average fitness get exponentially more copies in later generations. Selection amplifies them, and crossover rarely cuts short blocks apart. Crossover then assembles blocks from different parents. In the \(x^2\) example, parent 11000 has the good high bit and parent 10011 contributes low bits, and their child 11011 = 27 has both.
This is also why representation matters: if related genes are far apart, one-point crossover keeps cutting good combinations apart.
5. Mutation
Mutation makes small random changes:
- Bit-flip: each bit flips with probability \(p_m\), commonly \(p_m = 1/L\) for string length \(L\) (one flip per child on average).
- Gaussian: for real genes, add \(\mathcal{N}(0, \sigma^2)\) noise. Shrinking \(\sigma\) over time works like annealing.
- Swap / inversion: for permutations.
Why do we need it? Selection and crossover only rearrange existing genetic material. If no individual has a 1 in position 4, crossover can never create one. Mutation keeps every allele reachable and restores lost diversity. Crossover exploits what the population already knows. Mutation explores.
6. Replacement and elitism
- Generational: the children replace the whole population.
- Steady-state: only a few individuals are replaced each step, usually the worst.
- Elitism: copy the best \(e\) individuals unchanged into the next generation. The best fitness can then never decrease, which is cheap insurance. Keep \(e\) small (1–5%), or you'll lose diversity.
Play with it
The GA below evolves random strings toward a target sentence. Fitness is the number of characters in the right place. With 27 possible characters and 19 positions there are \(27^{19} \approx 1.6 \times 10^{27}\) strings, so random guessing would never succeed. Experiment:
- Set mutation rate = 0. The GA stalls once some needed letter has vanished from the population.
- Set mutation rate = 0.2. Too much noise destroys progress (a random walk).
- Turn crossover off. It still works (it becomes mutation + selection, like parallel stochastic hill climbing), but more slowly.
- Set tournament size = 1. With no selection pressure, nothing improves.
A real GA: Bolt's knapsack
Bolt can carry 35 kg. Twenty orders are waiting, each with a weight and a tip. Which subset maximizes the tips? With \(2^{20} \approx 10^6\) subsets this is still brute-forceable, which lets us check that the GA finds the true optimum. At 100 orders, brute force would be hopeless and a GA would still work fine.
import random
# Bolt's evening: which of 20 orders to carry? Each has a weight (kg) and a tip (rupees).
rng = random.Random(7)
weights = [rng.randint(1, 9) for _ in range(20)]
values = [rng.randint(5, 60) for _ in range(20)]
CAPACITY = 35
def fitness(chrom):
w = sum(wi for wi, g in zip(weights, chrom) if g)
v = sum(vi for vi, g in zip(values, chrom) if g)
return v if w <= CAPACITY else CAPACITY - w # overweight => negative (infeasible)
def tournament(pop, fits, k=3):
contenders = rng.sample(range(len(pop)), k)
return pop[max(contenders, key=lambda i: fits[i])]
def crossover(a, b): # one-point crossover
cut = rng.randrange(1, len(a))
return a[:cut] + b[cut:], b[:cut] + a[cut:]
def mutate(chrom, pm): # independent bit flips
return [1 - g if rng.random() < pm else g for g in chrom]
def genetic_algorithm(pop_size=60, generations=80, pc=0.9, pm=1/20, elite=2):
pop = [[rng.randint(0, 1) for _ in range(20)] for _ in range(pop_size)]
for gen in range(generations):
fits = [fitness(c) for c in pop]
ranked = sorted(range(pop_size), key=lambda i: fits[i], reverse=True)
if gen % 20 == 0:
print(f"gen {gen:3d}: best = {fits[ranked[0]]:4d}, mean = {sum(fits)/pop_size:7.1f}")
new_pop = [pop[i] for i in ranked[:elite]] # elitism: keep the best unchanged
while len(new_pop) < pop_size:
p1, p2 = tournament(pop, fits), tournament(pop, fits)
c1, c2 = crossover(p1, p2) if rng.random() < pc else (p1[:], p2[:])
new_pop += [mutate(c1, pm), mutate(c2, pm)]
pop = new_pop[:pop_size]
return max(pop, key=fitness)
best = genetic_algorithm()
print("GA best value:", fitness(best), "weight:", sum(w for w, g in zip(weights, best) if g))
# exact optimum by dynamic programming, to check the GA
dp = [0] * (CAPACITY + 1)
for w, v in zip(weights, values):
for c in range(CAPACITY, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
print("true optimum :", dp[CAPACITY])gen 0: best = 303, mean = 49.9
gen 20: best = 408, mean = 247.6
gen 40: best = 408, mean = 230.3
gen 60: best = 408, mean = 249.9
GA best value: 408 weight: 35
true optimum : 408
The GA hit the exact optimum (408) by generation 20, using \(20 \times 60 = 1200\) fitness evaluations instead of about a million. The mean fitness plateaus around 250 and not 408 because mutation keeps creating some infeasible children with negative fitness. That's the price of continued exploration, and it's healthy.
Tuning a GA: a practical cheat sheet
| Parameter | Typical | Too low | Too high |
|---|---|---|---|
| Population size \(N\) | 20–200 | Little diversity, premature convergence | Slow; wasted evaluations |
| Crossover rate \(p_c\) | 0.6–0.95 | Slow mixing of building blocks | (Rarely harmful) |
| Mutation rate \(p_m\) | \(1/L\) | Stagnation, lost alleles | Random search, good solutions destroyed |
| Selection pressure (tournament \(k\)) | 2–4 | Aimless drift | Premature convergence |
| Elitism \(e\) | 1–5% of \(N\) | Best solution can be lost | Population dominated by elites |
Symptoms: the population's average fitness catches up with the best within a few generations, then nothing improves. All individuals look alike. Fixes: lower selection pressure, raise mutation, use a larger population, inject random immigrants, or keep sub-populations separate (the "island model").
GA vs SA vs hill climbing
- GAs shine when good solutions are made of combinable parts (building blocks) and the landscape is rugged.
- If there's no meaningful way to combine two solutions, crossover is just a big random mutation, and SA or restarts may be just as good and simpler.
- GAs need many fitness evaluations. When evaluations are expensive (as with a rate-limited server), you have to use them cleverly: small populations, good initialization and caching.
- Compute roulette probabilities and expected copies \(N p_i\).
- Apply one-point / two-point / uniform crossover at given cut points.
- Apply mutation at given positions and recompute fitness.
- Explain why mutation is necessary (lost alleles) and why crossover helps (building blocks).
- AIMA's 8-queens GA: fitness = number of non-attacking pairs (max \(\binom{8}{2}=28\)). Values 24, 23, 20, 11 give selection probabilities 24/78 = 31%, 29%, 26%, 14%.
Lab: Evolving a Model That Generalizes
This lab is where Chapters 2 and 3 meet. It mirrors the shape of the classic MDL genetic-algorithm assignment. You are given an overfit weight vector for a degree-10 polynomial regressor (11 weights) and a black-box server: send it any weight vector and it returns the training and validation MSE. You never see the data. Your job is to evolve weights that do well on a hidden test set.
Bolt's delivery-time predictor was fitted to only 25 logged deliveries with a degree-10 polynomial. It is overfit: training MSE 1.99 but validation MSE 6.79. The data now lives on a server, and each query takes time. Make the predictor generalize.
Step 1: think before you code
Answer these design questions on paper first. Your report will be graded on them as much as on your final numbers.
| Decision | Options | What we'll use, and why |
|---|---|---|
| Representation | 11 real numbers; or binary-encoded | Real vector. Weights are continuous, and binary encoding would make a small change in a weight look like a big change in bits. |
| Fitness | −train; −val; −(train+val); add a gap penalty | −(train + val + |train − val|). Low error on both, plus a penalty on the gap, which is the signature of overfitting (§2.2). |
| Initial population | Random; mutants of the overfit vector | Mutants of the overfit vector. It's already a decent fit. Random 11-D vectors would mostly be absurd and waste queries. |
| Selection | Roulette; tournament; truncation | Truncation: the top half breeds. Fitness is negative, so roulette won't work directly. |
| Crossover | One-point; uniform; blend | Blend (\(\alpha a + (1-\alpha)b\)). Polynomial weights are strongly coupled, so mixing whole vectors keeps them consistent. |
| Mutation | Gaussian with fixed σ; shrinking σ | Gaussian with shrinking σ: big exploratory jumps early, fine-tuning later, as in annealing (§3.2). |
| Elitism | 0–few | 4 elites, so the best is never lost. |
The overfit vector's high-order weights are huge (hundreds to a thousand) and of alternating sign, carefully cancelling each other inside [−1, 1]. Change one of them by 20% and the cancellation breaks, so predictions explode. This is a textbook ridge (§3.1): good solutions lie along narrow diagonal directions in weight space, and single-gene moves fall off the ridge. Two things help: small additive mutations, and blend crossover, which moves along the line between two good vectors and so stays near the ridge.
Step 2: the code
The block between the dashed lines simulates the server, so you can run everything locally. In the real assignment you'd replace get_errors with the provided API call. Everything else carries over.
import numpy as np
# ---------------- the "server" (in the assignment this lives on a remote machine) --------------
_rng = np.random.default_rng(3)
def _true(z): # z = distance rescaled to [-1, 1]
return 14 + 8 * z + 3 * np.sin(3.5 * z)
def _sample(n):
z = _rng.uniform(-1, 1, n)
return z, _true(z) + _rng.normal(0, 2.0, n)
_ztr, _ytr = _sample(25) # training set (hidden from you)
_zva, _yva = _sample(25) # validation set (hidden from you)
_zte, _yte = _sample(5000) # the grader's secret test set
def _mse(w, z, y):
return float(np.mean((np.polyval(w[::-1], z) - y) ** 2))
QUERIES = 0
def get_errors(w):
"""Black box: send 11 weights, receive [train MSE, validation MSE]."""
global QUERIES
QUERIES += 1
return [_mse(w, _ztr, _ytr), _mse(w, _zva, _yva)]
# the overfit vector you're handed: an unregularized degree-10 fit to the training set
OVERFIT = np.linalg.lstsq(np.vander(_ztr, 11, increasing=True), _ytr, rcond=None)[0]
# -----------------------------------------------------------------------------------------------
rng = np.random.default_rng(0)
print("overfit vector: train=%.2f val=%.2f" % tuple(get_errors(OVERFIT)))
def fitness(w):
tr, va = get_errors(w)
return -(tr + va + abs(tr - va)) # higher is better; low errors AND a small gap
def crossover(a, b):
alpha = rng.random() # blend (arithmetic) crossover for real genes
return alpha * a + (1 - alpha) * b
def mutate(w, sigma, pm=0.3):
mask = rng.random(w.size) < pm # each gene mutates with probability pm
return w + mask * rng.normal(0, sigma, w.size)
POP, GENS, ELITE = 30, 150, 4
pop = [OVERFIT.copy()] + [mutate(OVERFIT, 1.0, pm=1.0) for _ in range(POP - 1)]
for gen in range(GENS):
sigma = 2.0 * 0.97 ** gen + 0.05 # big jumps early, fine-tuning late ("cooling")
fits = np.array([fitness(w) for w in pop])
order = np.argsort(-fits)
pop = [pop[i] for i in order]
if gen % 30 == 0:
print("gen %3d: best train=%.2f val=%.2f (sigma=%.2f)" % ((gen, *get_errors(pop[0]), sigma)))
parents = pop[:POP // 2] # truncation selection: the top half may breed
children = []
while len(children) < POP - ELITE:
i, j = rng.choice(len(parents), 2, replace=False)
children.append(mutate(crossover(parents[i], parents[j]), sigma))
pop = pop[:ELITE] + children # elitism: the best 4 survive unchanged
best = pop[0]
print("final: train=%.2f val=%.2f queries used: %d" % (*get_errors(best), QUERIES))
print("hidden TEST MSE overfit vector: %.2f" % _mse(OVERFIT, _zte, _yte))
print("hidden TEST MSE GA result : %.2f" % _mse(best, _zte, _yte))overfit vector: train=1.99 val=6.79
gen 0: best train=3.18 val=5.98 (sigma=2.05)
gen 30: best train=3.79 val=4.00 (sigma=0.85)
gen 60: best train=3.92 val=3.93 (sigma=0.37)
gen 90: best train=3.89 val=3.90 (sigma=0.18)
gen 120: best train=3.88 val=3.88 (sigma=0.10)
final: train=3.86 val=3.86 queries used: 4507
hidden TEST MSE overfit vector: 7.34
hidden TEST MSE GA result : 5.22
Step 3: read the results like a scientist
- Training error went up (1.99 → 3.86), and that is the point. The GA traded training fit for generalization. The noise floor is \(\sigma^2 = 4\), so a training MSE of 1.99 was too good to be true: the model had memorized noise.
- The gap closed (1.99 vs 6.79 → 3.86 vs 3.86). This is exactly what the \(|\text{train}-\text{val}|\) term in the fitness asked for.
- Hidden test error fell from 7.34 to 5.22, a 29% improvement on data the GA never touched.
- But test (5.22) is worse than validation (3.86). Why? We optimized against the validation set for 4,500 queries. It has become part of the training signal, and the GA has started to overfit it. This is §2.4's warning in action: any data you use to make decisions stops being an honest estimate. The grader's separate test set is the only honest judge.
- The shrinking σ is a cooling schedule, borrowed straight from simulated annealing.
- The fitness function's gap penalty is a hand-made regularizer (§2.4). An alternative is to penalize \(\lVert w \rVert^2\) inside the fitness, which is literally ridge regression solved by evolution.
- Overfitting the validation set via too many queries is the same disease as tuning on the test set. One cure is early stopping: stop when validation error stops improving meaningfully.
Step 4: what to put in your report
- Explain every design choice with a reason, as in the Step 1 table. "I used crossover" earns nothing. "I used blend crossover because the weights are coupled and need to change together" earns marks.
- Show generation traces. For a few generations, show the population, fitness, selected parents, children after crossover and children after mutation. Assignments often ask for exactly this.
- Plot best and mean fitness against generation. If the mean catches up with the best within a few generations, say so and call it premature convergence.
- Respect the query budget. Cache results in a dictionary keyed on the weight tuple, and never re-query the elites.
- Save everything to disk (JSON) after each generation. Servers go down and laptops sleep.
- Clip weights to the allowed range if there is one (e.g. [−10, 10]).
- Don't submit the vector with the lowest validation error blindly. Prefer one with low and balanced train/val errors. A vector with train 3.9 / val 3.9 usually beats one with train 1.5 / val 3.7.
- Explain the heuristics you tried that failed, and why. That shows understanding.
Exercises
- Change the fitness to
-vaonly. What happens to the train/val gap and to the test error? - Replace blend crossover with one-point crossover. Why does it do worse here? (Think about ridges.)
- Add an \(L_2\) penalty \(\lambda \lVert w \rVert^2\) to the fitness and sweep \(\lambda\). Compare with the ridge results of §2.4.
- Halve the query budget. Which settings (population size, generations) give the best result under the budget?
Probability and Utility
So far, Bolt has been learning functions and searching for solutions. From here on, Bolt must act in an uncertain world. This chapter gives it the two tools every rational agent needs: probability, to say how much to believe something, and utility, to say how much it wants something. Combine them and you get the most important equation in decision-making: choose the action with maximum expected utility.
$$\text{Decision theory} = \text{Probability theory} + \text{Utility theory}$$ Probability describes the world. Utility describes your goals. Expected utility combines them into a choice.
- §4.1 Probability: the axioms, random variables, joint distributions, marginalization, conditioning and the normalization trick.
- §4.2 Bayes' rule and independence: turning "how likely is the evidence given the cause" into "how likely is the cause given the evidence," and the independence assumptions that make reasoning tractable.
- §4.3 Utility theory: lotteries, the axioms of rational preference, expected utility, the utility of money and risk attitudes.
- Bolt's bump sensor fires. It is right 90% of the time when there's a pothole, but potholes are rare. How sure should Bolt be that there's really a pothole? (Bayes' rule, §4.2.)
- The shortcut across the lawn is 4 minutes faster but floods when it rains. There's a 30% chance of rain. Should Bolt risk it? (Expected utility, §4.3, then §5.1.)
Why does uncertainty appear at all? Look back at Chapter 2: \(y = f(x) + \varepsilon\). Noise is uncertainty. Probability is the language for things we can't predict exactly. Every later chapter uses it: MDPs (Ch 5) have probabilistic transitions, decision trees (Ch 6) measure uncertainty with entropy, and Bayesian networks (Ch 7) are compact descriptions of probability distributions.
Probability: The Language of Uncertainty
Why can't Bolt just use logic? Try writing the rule "if it rains, the delivery is late." It's false. Sometimes it rains and Bolt is on time. Add exceptions: "…unless the path is clear, and Bolt left early, and the lift works, and…". The list never ends. Logic fails for three reasons that AIMA names:
- Laziness: listing every exception is too much work.
- Theoretical ignorance: we don't know all the causes.
- Practical ignorance: even when we know the rules, we can't observe everything in the moment.
Probability summarizes all that ignorance in a number. "P(late | rain) = 0.65" means: given what I know, in situations like this, deliveries are late about 65% of the time.
Frequentist: a probability is a long-run frequency: flip the coin a million times. Bayesian (subjective): a probability is a degree of belief held by an agent, and it is updated when evidence arrives. AI mostly uses the Bayesian view, because agents must assign probabilities to one-off events ("Is there a pothole right here, right now?"). The good news: both views obey the same mathematical rules.
The basic vocabulary
| Term | Meaning | Example |
|---|---|---|
| Sample space \(\Omega\) | Set of all possible worlds (outcomes) | For two dice: 36 pairs |
| Event | A set of worlds | "the dice sum to 7" (6 worlds) |
| Random variable | A function from worlds to values | \(\textit{Weather} \in \{\text{sun, rain, cloud}\}\), \(\textit{Late} \in \{\text{true, false}\}\) |
| Proposition | A statement about random variables | \(\textit{Late}=\text{true} \wedge \textit{Rain}=\text{true}\), written \(late \wedge rain\) |
| Probability distribution | Probabilities for every value of a variable | \(\mathbf{P}(\textit{Weather}) = \langle 0.6, 0.2, 0.2\rangle\) |
| Joint distribution | Probabilities for every combination of values | \(\mathbf{P}(\textit{Rain}, \textit{Jam}, \textit{Late})\), a table of 8 numbers |
Notation: lower-case \(rain\) is short for \(\textit{Rain}=\text{true}\), and \(\neg rain\) for false. Bold \(\mathbf{P}\) denotes a whole distribution (a vector or table of numbers), and plain \(P\) a single number.
The axioms (Kolmogorov)
- \(0 \le P(\omega) \le 1\) for every world \(\omega\), and \(\sum_{\omega \in \Omega} P(\omega) = 1\).
- For an event \(\phi\): \(P(\phi) = \sum_{\omega \in \phi} P(\omega)\).
Everything else follows from these. For example:
- Complement: \(P(\neg a) = 1 - P(a)\).
- Inclusion–exclusion: \(P(a \vee b) = P(a) + P(b) - P(a \wedge b)\). You subtract the overlap because it was counted twice.
Suppose your beliefs violate the axioms, say you believe \(P(rain) = 0.6\) and \(P(\neg rain) = 0.6\). Then a bookie can offer you a set of bets you consider fair on each side, and you lose money no matter what happens. (de Finetti proved this.) The axioms aren't arbitrary math. They are the only consistent way to bet. The same style of argument justifies the axioms of utility in §4.3.
The full joint distribution: Bolt's evening
Three Boolean variables: Rain, Jam (a crowd blocking the hostel gate) and Late (the delivery is late). The full joint distribution lists a probability for each of the \(2^3 = 8\) worlds:
| \(jam\) | \(\neg jam\) | |||
|---|---|---|---|---|
| \(late\) | \(\neg late\) | \(late\) | \(\neg late\) | |
| \(rain\) | 0.090 | 0.010 | 0.040 | 0.060 |
| \(\neg rain\) | 0.096 | 0.064 | 0.064 | 0.576 |
The 8 numbers sum to 1. Any question about these three variables can be answered from this table. That's its power. Its weakness: with \(n\) Boolean variables it has \(2^n\) entries. At 30 variables that's a billion numbers. Chapter 7 (Bayesian networks) exists to fix this.
Marginalization (summing out)
To get the probability of one variable alone, add up every world where it holds:
$$ P(late) = 0.090 + 0.040 + 0.096 + 0.064 = 0.29 $$In general: \(\mathbf{P}(Y) = \sum_{z} \mathbf{P}(Y, z)\), summing over all values \(z\) of the other variables. This is called marginalizing, because people used to write the totals in the margins of the table.
Conditional probability
"Given that the delivery is late, how likely is it that it rained?" Conditioning means zooming in on the worlds where the evidence is true, and rescaling them to sum to 1:
$$ P(a \mid b) = \frac{P(a \wedge b)}{P(b)} \qquad (P(b) > 0) $$ $$ P(rain \mid late) = \frac{P(rain \wedge late)}{P(late)} = \frac{0.090 + 0.040}{0.29} = \frac{0.13}{0.29} \approx 0.448 $$Before learning anything, \(P(rain) = 0.2\). Learning that the delivery was late raised the belief in rain to 0.448. Evidence changes beliefs: that one sentence is the whole of probabilistic reasoning.
The product rule and the chain rule
Rearrange the definition: \(P(a \wedge b) = P(a \mid b)\,P(b)\). Apply it repeatedly and you get the chain rule:
$$ P(x_1, x_2, \dots, x_n) = P(x_1)\,P(x_2 \mid x_1)\,P(x_3 \mid x_1, x_2) \cdots P(x_n \mid x_1, \dots, x_{n-1}) = \prod_{i=1}^{n} P(x_i \mid x_1, \dots, x_{i-1}) $$This identity always holds. It is the foundation of Bayesian networks: they simplify each factor by dropping parents that don't matter (Ch 7).
The normalization trick
Often we want a whole conditional distribution, for example \(\mathbf{P}(Rain \mid jam, late)\). Both entries share the same denominator \(P(jam, late)\), so we can skip computing it:
$$ \mathbf{P}(Rain \mid jam, late) = \alpha\, \mathbf{P}(Rain, jam, late) = \alpha \langle 0.090,\ 0.096\rangle = \langle 0.484,\ 0.516 \rangle $$Here \(\alpha\) is just "whatever makes the vector sum to 1": \(\alpha = 1/(0.090+0.096)\). The order is \(\langle rain, \neg rain\rangle\). You'll see \(\alpha\) all through Bayes' rule, Bayes nets and POMDP belief updates.
To compute \(\mathbf{P}(X \mid e)\) for a query \(X\), evidence \(e\) and hidden variables \(Y\):
$$ \mathbf{P}(X \mid e) = \alpha \sum_{y} \mathbf{P}(X, e, y) $$In words: (1) keep the rows consistent with the evidence, (2) sum out the hidden variables, (3) normalize. Interesting fact: \(P(rain \mid late, jam) = 0.484 > P(rain \mid late, \neg jam) = 0.04/0.104 = 0.385\). A jam makes rain more likely here, because in this world rain makes jams more likely (people crowd under the gate shelter).
import numpy as np
# Full joint distribution P(Rain, Jam, Late), axes: [rain, jam, late], index 1 = true, 0 = false
P = np.zeros((2, 2, 2))
P[1, 1, 1], P[1, 1, 0] = 0.090, 0.010
P[1, 0, 1], P[1, 0, 0] = 0.040, 0.060
P[0, 1, 1], P[0, 1, 0] = 0.096, 0.064
P[0, 0, 1], P[0, 0, 0] = 0.064, 0.576
print("sums to", P.sum())
p_late = P[:, :, 1].sum() # marginalize out Rain and Jam
print("P(late) = %.3f" % p_late)
p_rain_late = P[1, :, 1].sum() # P(rain, late)
print("P(rain | late) = %.3f" % (p_rain_late / p_late))
# the normalization trick: compute unnormalized values for every value of Rain, then rescale
unnorm = P[:, 1, 1] # P(Rain, jam, late) for Rain = false, true
print("P(Rain | jam, late) =", np.round(unnorm / unnorm.sum(), 3), " (false, true)")sums to 1.0
P(late) = 0.290
P(rain | late) = 0.448
P(Rain | jam, late) = [0.516 0.484] (false, true)
Random variables, expectation and variance
For a numeric random variable \(X\):
$$ \mathbb{E}[X] = \sum_x x\,P(X=x), \qquad \operatorname{Var}(X) = \mathbb{E}\big[(X - \mathbb{E}[X])^2\big] = \mathbb{E}[X^2] - \mathbb{E}[X]^2 $$Key facts you've already used in the bias–variance derivation (§2.3):
- Linearity: \(\mathbb{E}[aX + bY + c] = a\mathbb{E}[X] + b\mathbb{E}[Y] + c\), always, even if \(X, Y\) are dependent.
- Independence: if \(X \perp Y\), then \(\mathbb{E}[XY] = \mathbb{E}[X]\mathbb{E}[Y]\). This is why the cross term \(\mathbb{E}[\varepsilon(f-\hat g)]\) vanished.
- \(\operatorname{Var}(aX + b) = a^2 \operatorname{Var}(X)\).
Expected value is the bridge to decisions. If action A gives utility 10 with probability 0.3 and utility 2 otherwise, its expected utility is \(0.3\cdot 10 + 0.7 \cdot 2 = 4.4\). §4.3 explains why we should maximize exactly this quantity.
Bayes' Rule and Independence
One line of algebra
Write the product rule both ways: \(P(a \wedge b) = P(a \mid b)P(b) = P(b \mid a)P(a)\). Divide by \(P(b)\):
$$ \boxed{\;P(\text{cause} \mid \text{effect}) = \frac{P(\text{effect} \mid \text{cause})\; P(\text{cause})}{P(\text{effect})}\;} $$Each piece has a name:
- \(P(\text{cause})\) is the prior: what you believed before the evidence.
- \(P(\text{effect} \mid \text{cause})\) is the likelihood: how well the cause explains the evidence.
- \(P(\text{effect})\) is the evidence (normalizer): \(= \sum_{c} P(\text{effect}\mid c)P(c)\), by marginalization.
- \(P(\text{cause} \mid \text{effect})\) is the posterior: what you should believe now.
Knowledge usually comes in the causal direction: "a pothole triggers the bump sensor 90% of the time." That's a property of the sensor, and it's stable. But decisions need the diagnostic direction: "the sensor fired, so is there a pothole?" That depends on how common potholes are, which changes from road to road. Bayes' rule converts stable causal knowledge plus a local prior into the diagnosis you need. Doctors, spam filters, robot localization and courtrooms all run on this one line.
The example everyone gets wrong
A disease affects 1% of people. A test detects it 90% of the time (sensitivity), and gives a false positive in 9% of healthy people. You test positive. What's the chance you have the disease?
Most people (including, in studies, most doctors) say about 90%. Let's compute it:
$$ P(D \mid +) = \frac{P(+\mid D)P(D)}{P(+\mid D)P(D) + P(+\mid \neg D)P(\neg D)} = \frac{0.9 \times 0.01}{0.9\times 0.01 + 0.09 \times 0.99} = \frac{0.009}{0.009 + 0.0891} \approx 0.092 $$About 9%, not 90%. Look at it with 1,000 people. 10 are sick, and 9 of them test positive. 990 are healthy, and about 89 of them test positive too. So of the 98 positives, only 9 are sick. The false positives from the huge healthy group swamp the true positives from the tiny sick group. Ignoring the prior like this is called the base-rate fallacy.
Play with it. Drop the base rate to 0.1% and even a 99%-sensitive test is nearly useless on its own. Raise it to 30% (testing only people with symptoms) and the same test becomes very informative. The prior matters as much as the test.
Potholes occur on 2% of path segments. Bolt's bump sensor fires on 95% of potholes, but also on 10% of smooth segments (speed bumps, a dropped water bottle). The sensor fires. Then
$$ P(pothole \mid fire) = \frac{0.95 \times 0.02}{0.95 \times 0.02 + 0.10 \times 0.98} = \frac{0.019}{0.117} \approx 0.16. $$Only 16%! Should Bolt slam the brakes? That depends on the costs of each mistake, which needs utility (§4.3) and decision theory (§5.1). Probability tells you what to believe, and utility tells you what to do about it.
Sequential updating: today's posterior is tomorrow's prior
After a positive test, your belief is 9.2%. Take a second, independent test, and use 9.2% as the new prior:
def posterior(prior, p_pos_given_h, p_pos_given_not_h):
"""P(H | positive test) by Bayes' rule."""
evidence = p_pos_given_h * prior + p_pos_given_not_h * (1 - prior)
return p_pos_given_h * prior / evidence
p = 0.01 # 1% of people have the disease
for test in range(1, 4): # the same test, repeated (independent errors)
p = posterior(p, 0.90, 0.09)
print(f"after positive test #{test}: P(disease) = {p:.3f}")after positive test #1: P(disease) = 0.092
after positive test #2: P(disease) = 0.503
after positive test #3: P(disease) = 0.910
Evidence accumulates: 1% → 9% → 50% → 91%. This is exactly how Bolt will track its position with a noisy sensor in §5.5 (POMDPs): predict, observe, apply Bayes' rule, repeat.
The odds form (fast mental math)
Odds = \(P/(1-P)\). Bayes' rule in odds form is just a multiplication:
$$ \underbrace{\frac{P(H\mid e)}{P(\neg H \mid e)}}_{\text{posterior odds}} = \underbrace{\frac{P(e \mid H)}{P(e \mid \neg H)}}_{\text{likelihood ratio}} \times \underbrace{\frac{P(H)}{P(\neg H)}}_{\text{prior odds}} $$For the disease test the likelihood ratio is \(0.9/0.09 = 10\). Prior odds \(1:99\) become posterior odds \(10:99\), so \(P = 10/109 \approx 0.092\). ✓ A second test makes it \(100:99\), about 50%. ✓
Independence
\(A\) and \(B\) are independent (\(A \perp B\)) if learning one tells you nothing about the other:
$$ P(A \mid B) = P(A) \iff P(A, B) = P(A)\,P(B). $$Independence is what makes probability tractable. If Bolt's 30 variables were all independent, the joint would need only 30 numbers instead of \(2^{30}\). Unfortunately, full independence is rare in interesting problems. Rain and Late are certainly not independent.
Conditional independence: the workhorse
Much more common: two things are dependent, but become independent once you know a third thing.
$$ A \perp B \mid C \iff P(A, B \mid C) = P(A \mid C)\,P(B \mid C). $$Example: two hostel residents, John and Mary, both call security when they hear Bolt's anti-theft alarm. Whether John calls and whether Mary calls are dependent: if John called, the alarm probably went off, so Mary probably called too. But given that the alarm went off, John's call tells you nothing more about Mary's. Each one only reacts to the alarm. So \(John \perp Mary \mid Alarm\). This exact example is the heart of Chapter 7.
Naive Bayes: Bayes' rule + conditional independence
Suppose we want \(P(\text{Class} \mid x_1, \dots, x_n)\) and we assume every feature is conditionally independent of the others given the class:
$$ P(\text{Class} \mid x_1,\dots,x_n) = \alpha\, P(\text{Class}) \prod_{i=1}^n P(x_i \mid \text{Class}). $$The assumption is "naive" because it's usually false, but the classifier works surprisingly well (spam filters were built on it). Each \(P(x_i \mid \text{Class})\) is just a count from data. Here it is on the tennis dataset you'll meet again in Chapter 6. Should we play tennis on a sunny, cool, high-humidity, strong-wind day?
from collections import Counter
# Mitchell's PlayTennis data: (Outlook, Temp, Humidity, Wind) -> Play
data = [("Sunny","Hot","High","Weak","No"), ("Sunny","Hot","High","Strong","No"),
("Overcast","Hot","High","Weak","Yes"), ("Rain","Mild","High","Weak","Yes"),
("Rain","Cool","Normal","Weak","Yes"), ("Rain","Cool","Normal","Strong","No"),
("Overcast","Cool","Normal","Strong","Yes"), ("Sunny","Mild","High","Weak","No"),
("Sunny","Cool","Normal","Weak","Yes"), ("Rain","Mild","Normal","Weak","Yes"),
("Sunny","Mild","Normal","Strong","Yes"), ("Overcast","Mild","High","Strong","Yes"),
("Overcast","Hot","Normal","Weak","Yes"), ("Rain","Mild","High","Strong","No")]
def naive_bayes(x):
labels = Counter(row[-1] for row in data)
scores = {}
for y, n_y in labels.items():
score = n_y / len(data) # prior P(y)
for i, value in enumerate(x): # times P(x_i | y) for each feature
score *= sum(1 for row in data if row[-1] == y and row[i] == value) / n_y
scores[y] = score
z = sum(scores.values())
return {y: round(s, 4) for y, s in scores.items()}, {y: round(s / z, 3) for y, s in scores.items()}
print(naive_bayes(("Sunny", "Cool", "High", "Strong")))({'No': 0.0206, 'Yes': 0.0053}, {'No': 0.795, 'Yes': 0.205})
By hand: \(P(\text{Yes}) \cdot P(\text{sunny}|\text{Yes}) \cdots = \frac{9}{14}\cdot\frac29\cdot\frac39\cdot\frac39\cdot\frac39 \approx 0.0053\) and \(P(\text{No}) \cdots = \frac{5}{14}\cdot\frac35\cdot\frac15\cdot\frac45\cdot\frac35 \approx 0.0206\). Normalizing gives P(No) ≈ 0.795, so don't play. This is a classic exam computation.
If some feature value never appears with a class in training (e.g. "Overcast" never occurs with "No"), then \(P(\text{Overcast}\mid\text{No}) = 0\), and that single zero wipes out the whole product. The fix is Laplace (add-one) smoothing: \(P(x_i = v \mid y) = \frac{\text{count}+1}{n_y + |\text{values}|}\). This is regularization again (§2.4): a prior belief that no event is impossible, which protects against overfitting to small counts.
- Naive Bayes is the simplest Bayesian network: a class node with an arrow to every feature (Ch 7).
- Bayes' rule with a sequence of observations is the belief update of POMDPs (§5.5).
- Regularization as a prior (§2.4) is Bayes' rule applied to model weights: posterior ∝ likelihood × prior.
Utility Theory
Probability tells Bolt what to believe. But beliefs alone don't choose actions. Is a 16% chance of a pothole worth braking for? That depends on how bad a pothole crash is compared with a slightly slower delivery. We need a way to put numbers on preferences. That number is utility.
Lotteries: the language of risky choices
Every uncertain action is a lottery: a set of possible outcomes with probabilities:
$$ L = [\,p_1, S_1;\ p_2, S_2;\ \dots;\ p_n, S_n\,], \qquad \sum_i p_i = 1. $$Bolt's shortcut across the lawn is the lottery \([0.7, \text{arrive in 16 min};\ 0.3, \text{soaked food}]\). The covered route is the "lottery" \([1.0, \text{arrive in 20 min}]\), an outcome that is certain.
Preference notation:
- \(A \succ B\): the agent prefers A to B.
- \(A \sim B\): the agent is indifferent.
- \(A \succsim B\): prefers A or is indifferent.
The axioms of rational preference
What should a "rational" agent's preferences look like? Von Neumann and Morgenstern proposed six constraints. Each sounds obviously reasonable:
| Axiom | Statement | In words |
|---|---|---|
| Orderability | Exactly one of \(A\succ B\), \(B \succ A\), \(A\sim B\) | You can always compare two options |
| Transitivity | \(A \succ B,\ B \succ C \Rightarrow A \succ C\) | No preference cycles |
| Continuity | \(A \succ B \succ C \Rightarrow \exists p: [p, A; 1-p, C] \sim B\) | Something in the middle is equivalent to some gamble between the extremes |
| Substitutability | \(A \sim B \Rightarrow [p, A; 1-p, C] \sim [p, B; 1-p, C]\) | Swapping in equivalent outcomes doesn't change things |
| Monotonicity | \(A \succ B \Rightarrow (p > q \iff [p, A; 1-p, B] \succ [q, A; 1-q, B])\) | More chance of the better outcome is better |
| Decomposability | Compound lotteries reduce to simple ones by multiplying probabilities | "No fun in gambling": only final odds matter |
Suppose Bolt's controller has the cyclic preferences A ≻ B, B ≻ C and C ≻ A. Give it C. It will pay ₹1 to swap C for B (it prefers B), pay ₹1 to swap B for A, and then pay ₹1 to swap A for C, because it prefers C to A! It's back where it started, ₹3 poorer, and the loop can run forever. Intransitive agents can be exploited without limit. So the axioms aren't moral rules: violating them makes you exploitable, just like the Dutch book for probabilities.
The expected utility theorem
Von Neumann–Morgenstern theorem. If an agent's preferences obey the six axioms, then there exists a real-valued utility function \(U\) over outcomes such that
$$ A \succ B \iff U(A) > U(B), \qquad\text{and}\qquad U([p_1, S_1; \dots; p_n, S_n]) = \sum_i p_i\, U(S_i). $$In other words, a rational agent behaves as if it is maximizing expected utility.
This is a remarkable result. Nobody told the agent to compute averages. Consistency alone forces it. It also gives the principle of maximum expected utility (MEU):
$$ a^* = \arg\max_a\ \mathbb{EU}(a) = \arg\max_a \sum_{s'} P(s' \mid a)\, U(s'). $$Utilities: arrive in 16 min → 100, arrive in 20 min → 80, soaked food → 0. With P(rain) = 0.3:
- \(\mathbb{EU}(\text{covered}) = 1.0 \times 80 = 80\).
- \(\mathbb{EU}(\text{shortcut}) = 0.7 \times 100 + 0.3 \times 0 = 70\).
So Bolt takes the covered route. At what rain probability \(p\) do the two break even? \((1-p)\cdot 100 = 80\), so \(p = 0.2\). Below 20% rain, take the shortcut. This threshold is the decision, and it moves if either the probabilities or the utilities change.
Properties of utility functions
Only the shape matters: affine invariance
If \(U' = aU + b\) with \(a > 0\), then \(U'\) produces exactly the same decisions, because expectations are linear. So utilities have no absolute scale, and we can normalize: best outcome = 1, worst = 0. Something like \(U(S) = 3U(S')\) means nothing. Utilities are not "three times as happy."
But you can't apply arbitrary increasing transformations. \(U' = U^2\) can reverse choices between lotteries. (For deterministic choices only the ranking matters, so any increasing transformation works. Such ranking-only functions are called ordinal or value functions.)
How to measure someone's utility: the standard lottery
Normalize: \(U(\text{best}) = 1\), \(U(\text{worst}) = 0\). For any outcome \(S\), ask: "for what \(p\) are you indifferent between \(S\) for sure and the lottery \([p, \text{best}; 1-p, \text{worst}]\)?" Then \(U(S) = p\). For example, if Bolt's operators are indifferent between "20-minute delivery" and "a 90% chance of a 16-minute delivery, 10% chance of soaked food," then \(U(\text{20 min}) = 0.9\).
The utility of money
Is utility just money? Consider:
- A: ₹10 lakh for sure.
- B: a coin flip: ₹30 lakh or nothing.
B has the higher expected monetary value (EMV ₹15 lakh), but almost everyone takes A. The first ₹10 lakh changes your life. Going from ₹10 lakh to ₹30 lakh is nice but less dramatic. Money has diminishing marginal utility: \(U\) is concave in money.
A casino flips a coin until the first heads. If that happens on flip \(k\), you win ₹\(2^k\). Expected money \(= \sum_k \frac{1}{2^k}2^k = 1 + 1 + 1 + \dots = \infty\). Yet nobody would pay more than about ₹20 to play. Daniel Bernoulli (1738) proposed \(U(x) = \log x\). Then the expected utility is \(\sum_k \frac{1}{2^k}\log_2 2^k = \sum_k \frac{k}{2^k} = 2\), which is the utility of a sure ₹\(2^2\) = ₹4. That's a sensible price. Concave utility resolves the paradox.
Risk attitudes and the certainty equivalent
For a lottery \(L\), the certainty equivalent \(CE\) is the sure amount you'd accept instead: \(U(CE) = \mathbb{EU}(L)\). The risk premium is \(EMV(L) - CE(L)\), the amount you'd give up to remove the risk.
| Shape of \(U\) | Attitude | \(CE\) vs \(EMV\) | Example |
|---|---|---|---|
| Concave (\(\sqrt x\), \(\log x\)) | Risk-averse | \(CE < EMV\), premium > 0 | Buying insurance |
| Linear | Risk-neutral | \(CE = EMV\) | A large company making many small bets |
| Convex (\(x^2\)) | Risk-seeking | \(CE > EMV\), premium < 0 | Buying lottery tickets; desperate situations |
Worked example: \(U(x) = \sqrt{x}\), \(L = [0.5, ₹100\text{k};\ 0.5, ₹0]\). Then \(EMV = 50\text{k}\), \(\mathbb{EU} = 0.5\sqrt{100} + 0.5\cdot 0 = 5\), and \(CE = 5^2 = 25\text{k}\), so the risk premium is 25k. This agent would accept any sure offer above ₹25k instead of the gamble. Check it below: set ρ = 0.5 and p = 0.5.
Notice the geometry. The orange point \((EMV, \mathbb{EU})\) sits on the chord between the lottery's two outcomes, and the curve's height there is \(U(EMV)\). For a concave curve the chord lies below the curve, so \(\mathbb{E}[U(X)] \le U(\mathbb{E}[X])\). That's Jensen's inequality, and it's why concave means risk-averse.
Humans are not perfectly rational: the Allais paradox
Choose between:
- A: 80% chance of ₹4000 vs. B: ₹3000 for sure. (Most people choose B.)
- C: 20% chance of ₹4000 vs. D: 25% chance of ₹3000. (Most people choose C.)
With \(U(0) = 0\): B ≻ A means \(U(3000) > 0.8\,U(4000)\). C ≻ D means \(0.2\,U(4000) > 0.25\,U(3000)\), i.e. \(U(3000) < 0.8\,U(4000)\). That's a contradiction, so no utility function fits both choices. Humans overweight certainty (the "certainty effect"). This is one reason we build AI on the normative theory and not on human imitation (recall §1.1).
Several attributes at once
Real outcomes have several dimensions: time, cost, safety, food temperature. Two useful ideas:
- Strict dominance: if option A is at least as good as B on every attribute and better on one, discard B without needing any utilities.
- Additive utility: if attributes are preferentially independent, \(U(x_1,\dots,x_n) = \sum_i w_i U_i(x_i)\). This is the familiar weighted-scoring approach, and it's valid when preferences for one attribute don't depend on the levels of the others.
- Loss is negative utility. Minimizing expected squared loss in Chapter 2 is MEU with \(U = -(\hat y - y)^2\). The whole of supervised learning is a decision-theoretic choice.
- In MDPs (Ch 5), utility is defined over sequences of states as a (discounted) sum of rewards, and the agent maximizes expected utility over time.
- The value of information (§5.1) asks how much your expected utility would rise if you learned something before acting.
- Name and state the six axioms. Give the money-pump argument for transitivity.
- Compute EU of each action → pick the max → find the break-even probability.
- Compute EMV, CE and risk premium for a given \(U\). Classify risk attitude from the curvature of \(U\).
- Show that \(U' = aU + b\) (\(a>0\)) preserves decisions, and that \(U^2\) need not.
Decision Theory and MDPs
Chapter 4 gave Bolt beliefs (probability) and desires (utility). This chapter puts them to work: first for one decision, then for sequences of decisions where each action changes the situation for the next. That second setting, the Markov decision process, is the mathematical core of planning under uncertainty and of reinforcement learning. Finally we drop the assumption that Bolt knows where it is, and handle observation errors with POMDPs.
- §5.1 Rational decisions and the value of information: MEU for one-shot choices, decision networks, and how much it is worth to look before you leap.
- §5.2 Markov decision processes: states, actions, stochastic transitions, rewards, discounting, policies and the Bellman equation.
- §5.3 Value iteration and policy iteration: the two classic algorithms, worked by hand and in code, with an interactive grid world.
- §5.4 Solving MDPs with linear programming: the primal and dual LP formulations, a standard MDL assignment topic.
- §5.5 Modelling observation errors: POMDPs: belief states, the belief update and why partial observability is so much harder.
Bolt drives through a grid of campus paths. Its wheels slip: when it tries to go north it actually goes north 80% of the time and veers sideways 20% of the time. One cell holds the destination (+1). Another is the open stairwell (−1, a disaster). Every step drains a little battery. What should Bolt do in each cell? Then the harder version: Bolt's GPS is unreliable indoors, so it doesn't even know which cell it is in.
Rational Decisions and the Value of Information
MEU for a single decision
An agent in its current state, with evidence \(e\), chooses action \(a\). The outcome \(s'\) is uncertain. The expected utility of the action is
$$ \mathbb{EU}(a \mid e) = \sum_{s'} P(\text{Result}(a) = s' \mid a, e)\; U(s'), $$and a rational agent picks \(a^* = \arg\max_a \mathbb{EU}(a \mid e)\). That's the whole theory of one-shot decisions. Everything difficult is in getting the probabilities (from models, data and Bayes' rule) and the utilities (from preferences).
From §4.2, \(P(pothole \mid fire) = 0.16\). Utilities: brake (lose 30 s) → 95 whether or not there's a pothole. Don't brake → 100 if no pothole, 20 if pothole (a damaged wheel).
- \(\mathbb{EU}(\text{brake}) = 95\)
- \(\mathbb{EU}(\text{continue}) = 0.84 \times 100 + 0.16 \times 20 = 84 + 3.2 = 87.2\)
Brake. The pothole is unlikely, but the asymmetric costs make braking rational. Beliefs and decisions are different things: you can believe "probably no pothole" and rationally act as if there were one.
Decision networks (influence diagrams)
A decision network extends a Bayesian network (Ch 7) with two new kinds of node:
- Chance nodes (ovals): random variables with conditional probability tables, as in Bayes nets.
- Decision nodes (rectangles): choices the agent controls.
- Utility nodes (diamonds): utility as a function of their parents.
Evaluating a decision network: for each value of the decision node, set it, compute the posterior of the utility node's chance parents given the evidence (Bayes-net inference, Ch 7), compute expected utility, and pick the best. If the decision has information parents, do this separately for each value of the information. That gives a policy: a rule mapping observations to actions.
The value of information
Bolt could check a weather forecast before choosing its route. How much should it be willing to "pay" for that, in time, battery or money? Decision theory gives a precise answer.
The value of perfect information about variable \(E\) is the expected improvement in the best expected utility from learning \(E\) before acting:
$$ \text{VPI}(E) = \Big(\sum_{e} P(E{=}e)\ \max_a \mathbb{EU}(a \mid E{=}e)\Big) \;-\; \max_a \mathbb{EU}(a). $$First term: "for each possible answer, I'd pick the best action for that answer," averaged over the possible answers. Second term: the best I can do without asking.
P(rain) = 0.3. Covered route: U = 70 (rain), 80 (dry). Open shortcut: U = 0 (rain), 100 (dry). The forecast is 80% accurate.
- Without info: EU(covered) = 0.3·70 + 0.7·80 = 77. EU(open) = 0.7·100 = 70. Best = 77 (covered).
- P(forecast says rain) = 0.3·0.8 + 0.7·0.2 = 0.38.
- If "rain": P(rain | F) = 0.24/0.38 = 0.632. EU(covered) = 0.632·70 + 0.368·80 = 73.7. EU(open) = 36.8. Best 73.7 (covered).
- If "dry": P(rain | ¬F) = 0.06/0.62 = 0.097. EU(covered) = 79.0. EU(open) = 90.3. Best 90.3 (open!).
- With info: 0.38·73.7 + 0.62·90.3 = 84.0.
- VOI = 84.0 − 77 = 7.0 utility units.
The forecast is valuable because it can change the decision: on "dry" days Bolt switches to the shortcut.
Slide the forecast accuracy to 0.5, a coin flip. The VOI drops to 0: a useless signal can't change any decision. Set P(rain) to 0.9 and accuracy to 0.7. The VOI is 0 again: Bolt would take the covered route whatever the forecast says, because even "dry" leaves too much rain risk.
Properties of VPI
- Non-negative: \(\text{VPI}(E) \ge 0\) in expectation. Information can't hurt a rational agent on average, because it can always ignore it. (A specific observation can lower your expected utility: bad news is bad news. The expected value of looking can't be negative.)
- Zero if it can't change the decision: if the best action is the same for every possible value of \(E\), then VPI = 0.
- Not additive: \(\text{VPI}(E_1, E_2) \ne \text{VPI}(E_1) + \text{VPI}(E_2)\) in general. Two forecasts that say the same thing are together worth little more than one.
- Order-independent: learning \(E_1\) then \(E_2\) is worth the same as \(E_2\) then \(E_1\).
A myopic information-gathering agent repeatedly asks for the observation with the highest VPI minus cost, while that difference is positive, and then acts. Doctors ordering tests, Bolt deciding whether to slow down and look more carefully, and decision trees choosing which attribute to test next (Ch 6: information gain!) all follow this pattern.
- Information gain in decision trees (§6.2) asks "which question reduces uncertainty most?" VPI asks "which question increases expected utility most?" They are cousins: IG cares about beliefs, VPI about decisions.
- In POMDPs (§5.5), actions like "look around" have no direct reward. Their value is entirely informational, and the POMDP framework computes it automatically.
Markov Decision Processes
In §5.1 Bolt made one decision and was done. Real life is a sequence: each action puts Bolt in a new situation that needs another decision, and the consequences of today's choice reach far into the future. Taking a shortcut near the stairwell might save time now and cost everything three steps later.
The 4×3 world
If the world were deterministic, the answer would be a plan: "Up, Up, Right, Right, Right." But with slipping, the same plan reaches +1 only \(0.8^5 \approx 33\%\) of the time. Bolt needs instructions for every cell it might end up in, not just a fixed sequence. That's a policy.
The definition
A Markov decision process is a tuple \((S, A, P, R, \gamma)\):
- \(S\): a set of states (here, the 11 open cells), with a start state.
- \(A(s)\): the actions available in state \(s\) (N, S, E, W).
- \(P(s' \mid s, a)\): the transition model, the probability of reaching \(s'\) by doing \(a\) in \(s\).
- \(R(s)\) (or \(R(s,a,s')\)): the reward, an immediate and possibly negative payoff.
- \(\gamma \in [0,1]\): the discount factor.
The word "Markov" carries a big assumption:
$$ P(s_{t+1} \mid s_t, a_t, s_{t-1}, a_{t-1}, \dots, s_0) = P(s_{t+1} \mid s_t, a_t). $$The future depends only on the present state and action, not on the history. The state must carry everything relevant. If Bolt's slip probability depended on how long it had been driving (wheels heating up), we'd have to add "time driving" to the state to restore the Markov property. Choosing what goes into the state is a modelling decision, just like choosing features in Chapter 2.
Policies
A policy \(\pi\) maps every state to an action: \(\pi(s) = a\). It is a complete contingency plan: wherever Bolt finds itself, the policy says what to do. Because of the Markov property, the current state is all a policy needs. Remembering history doesn't help.
An optimal policy \(\pi^*\) maximizes the expected utility of the resulting sequence of states. What "utility of a sequence" means needs a careful definition.
Utilities over time: rewards and discounting
Bolt collects rewards \(R(s_0), R(s_1), R(s_2), \dots\). The standard way to score the whole sequence is the discounted sum:
$$ U([s_0, s_1, s_2, \dots]) = R(s_0) + \gamma R(s_1) + \gamma^2 R(s_2) + \dots = \sum_{t=0}^{\infty} \gamma^t R(s_t). $$Why discount?
- Preference for sooner: a reward now beats the same reward later. Hot maggi now beats hot maggi tomorrow.
- Uncertainty about the future: \(\gamma\) can be read as "each step, there's a \(1-\gamma\) chance the world ends (battery dies)."
- Mathematics: with \(\gamma < 1\) and rewards bounded by \(R_{\max}\), the sum is finite even over an infinite horizon:
A \(\gamma\) near 0 gives a myopic agent that only cares about immediate reward. A \(\gamma\) near 1 gives a far-sighted one. With \(\gamma = 1\) (as in AIMA's 4×3 example) we need terminal states that are reached with probability 1, or utilities could be infinite. Under certain assumptions (stationary preferences), additive discounted rewards are the only sensible way to combine rewards over time.
The utility of a state, and the Bellman equation
The utility of a state under policy \(\pi\) is the expected discounted reward from starting there and following \(\pi\):
$$ U^\pi(s) = \mathbb{E}\Big[\sum_{t=0}^\infty \gamma^t R(S_t) \;\Big|\; S_0 = s,\ \pi\Big]. $$Write \(U(s) = U^{\pi^*}(s)\) for the utility under the optimal policy. Here is the key insight. The utility of a state is the reward you get now, plus the discounted expected utility of wherever you land next, assuming you act optimally:
$$ \boxed{\;U(s) = R(s) + \gamma \max_{a \in A(s)} \sum_{s'} P(s' \mid s, a)\; U(s')\;} $$This is the Bellman equation (Richard Bellman, 1957). Once you know \(U\), the optimal policy is just one-step lookahead:
$$ \pi^*(s) = \arg\max_{a} \sum_{s'} P(s' \mid s, a)\, U(s'). $$The Bellman equation turns an infinite-horizon problem into a local consistency condition: every state's value must agree with its neighbours' values. It's like saying "the best way from Hostel C to the canteen is: take the best first step, then follow the best way from wherever that leaves you." This idea of breaking a big optimization into the same small one repeated is dynamic programming.
There is one Bellman equation per state, so \(n\) equations in \(n\) unknowns. But they're non-linear because of the max, so we can't just solve them with linear algebra. §5.3 gives two algorithms that do.
Also: Q-values
It's often handy to define the value of doing action \(a\) in state \(s\) and then acting optimally:
$$ Q(s,a) = R(s) + \gamma \sum_{s'} P(s' \mid s,a)\, U(s'), \qquad U(s) = \max_a Q(s,a), \qquad \pi^*(s) = \arg\max_a Q(s,a). $$Q-values are the foundation of Q-learning, the reinforcement-learning algorithm that learns them from experience without knowing \(P\).
How the reward shapes behaviour
The living reward \(R(s)\) for non-terminal cells completely changes Bolt's "personality." For the 4×3 world with \(\gamma=1\) (AIMA Fig. 17.2):
| Living reward \(R(s)\) | Optimal behaviour |
|---|---|
| \(R < -1.6284\) | Life is so painful that Bolt heads for the nearest exit, even diving into the −1 stairwell from next to it. |
| \(-1.6284 < R < -0.4278\) | Rushes to +1 by the shortest route, even going North from (3,0) right past the pit. |
| \(-0.4278 < R < -0.0850\) | Takes the shortest route to +1 but turns away from the pit at (3,0). Accepts some risk elsewhere. |
| \(-0.0850 < R < -0.0221\) | The standard answer (R = −0.04): takes the long, safe way round from the bottom row. |
| \(-0.0221 < R < 0\) | Very cautious: bumps into walls on purpose (e.g. at (2,1) and (3,0)) to avoid any chance of −1. |
| \(R > 0\) | Life is good, so Bolt avoids both exits forever and keeps collecting reward. With γ = 1 the utilities are infinite. |
You can check every row with the interactive grid world in §5.3. These thresholds were also verified by sweeping R in the §5.3 code.
Just like the loss in Chapter 2 and the fitness in Chapter 3, the reward is what the agent actually optimizes. With a positive living reward, Bolt never delivers anything. The objective was satisfied and the designer's intent was not. This is called reward hacking, and it is one of the central problems in AI safety.
- Define an MDP formally: the 5 components and the Markov property.
- Write the Bellman equation and explain each term.
- Compute a discounted return: rewards \(1, 1, 1, \dots\) forever with \(\gamma=0.9\) gives \(1/(1-0.9)=10\).
- Explain why a policy, and not a plan, is needed in stochastic environments.
- Given rewards, predict qualitatively what the optimal policy does.
Value Iteration and Policy Iteration
The Bellman equations are \(n\) non-linear equations in \(n\) unknowns. There are two classic ways to solve them. Both are dynamic programming, and both need the full model (\(P\) and \(R\)).
Value iteration
The idea: start with arbitrary utilities (say all zeros), then repeatedly apply the Bellman equation as an update, using the current estimates on the right-hand side:
$$ U_{k+1}(s) \;\leftarrow\; R(s) + \gamma \max_a \sum_{s'} P(s'\mid s,a)\, U_k(s'). $$function VALUE-ITERATION(mdp, ε):
U ← 0 for every state
repeat:
δ ← 0
for each state s:
U'[s] ← R(s) + γ · max_a Σ_s' P(s'|s,a) · U[s']
δ ← max(δ, |U'[s] − U[s]|)
U ← U'
until δ < ε(1−γ)/γ # (if γ = 1, just use δ < ε)
return U
\(U_k(s)\) is the optimal expected reward if Bolt has only \(k\) steps left. After 1 iteration only the terminals "know" their value. After 2, their neighbours know the goal is one step away. After \(k\), states up to \(k\) steps from the goal have meaningful values. The value floods backward from the rewards through the grid, like ink spreading in water. Watch it happen in the widget below.
Worked by hand: the first sweeps
Take the 4×3 world with \(R = -0.04\), \(\gamma=1\), and \(U_0 = 0\) everywhere. Coordinates are (column, row) with (0,0) at the bottom-left.
Iteration 1. Every non-terminal gets \(-0.04 + \max_a(\text{weighted sum of zeros}) = -0.04\). Terminals are fixed at ±1.
Iteration 2, for cell (2,2), just left of +1. Try action E:
$$ 0.8\,U_1(3,2) + 0.1\,U_1(2,2)_{\text{N bumps, stays}} + 0.1\,U_1(2,1)_{\text{S}} = 0.8(1) + 0.1(-0.04) + 0.1(-0.04) = 0.792 $$Every other action is worse (the others mostly reach −0.04 states), so \(U_2(2,2) = -0.04 + 0.792 = 0.752\). All other non-terminals are still far from +1 and get \(-0.08\).
Iteration 3, for (2,2) again with action E: \(0.8(1) + 0.1(0.752) + 0.1(-0.08) = 0.8672\), so \(U_3(2,2) = 0.8272\). The value now reaches (1,2): action E gives \(0.8(0.752) + 0.1(-0.08) + 0.1(-0.08) = 0.5856\), so \(U_3(1,2) = 0.5456\).
| Cell | \(U_1\) | \(U_2\) | \(U_3\) | \(U_4\) | … \(U_{30}\) (converged) |
|---|---|---|---|---|---|
| (2,2) | −0.040 | 0.752 | 0.827 | 0.888 | 0.918 |
| (1,2) | −0.040 | −0.080 | 0.546 | 0.731 | 0.868 |
| (0,2) | −0.040 | −0.080 | −0.120 | 0.372 | 0.812 |
| (2,1) | −0.040 | −0.080 | 0.454 | 0.567 | 0.660 |
| (0,0) start | −0.040 | −0.080 | −0.120 | −0.160 | 0.705 |
Things to try:
- Press Sweep repeatedly from Reset. The arrows near the goal settle first, and the far corner settles last.
- Notice the policy often becomes optimal long before the values converge. Policy iteration exploits this.
- Set the living reward to −2 (rush to any exit), −0.2 (shortcut), −0.01 (super-cautious wall-hugging) and run to convergence each time.
- Now try +0.1 with γ = 1. The values grow by 0.1 every sweep and never converge, because staying forever is worth infinite reward. Lower γ to 0.9 and it converges: every cell is then worth 0.1/(1 − 0.9) = 1, exactly as much as the +1 exit, so Bolt has no reason to deliver at all. Reward design matters!
- Set slip noise to 0. The world becomes deterministic, and the policy is just the shortest path.
- Set γ to 0.6. Bolt becomes short-sighted: distant cells barely feel the +1.
Why does it converge? (The contraction argument)
Let \(B\) be the Bellman update operator, \(U_{k+1} = B U_k\). For any two utility vectors,
$$ \lVert BU - BU' \rVert_\infty \le \gamma\, \lVert U - U' \rVert_\infty. $$Each update shrinks the distance between any two estimates by a factor \(\gamma\). So \(B\) is a contraction, it has a unique fixed point (the true \(U\)), and the error shrinks geometrically: \(\lVert U_k - U\rVert \le \gamma^k \lVert U_0 - U\rVert\). In practice, a stopping rule follows: if \(\lVert U_{k+1} - U_k\rVert < \varepsilon(1-\gamma)/\gamma\), then \(\lVert U_{k+1} - U\rVert < \varepsilon\).
The number of iterations needed to reach error \(\varepsilon\) is about \(\log(R_{\max}/(\varepsilon(1-\gamma))) / \log(1/\gamma)\), so it grows quickly as \(\gamma \to 1\). Far-sighted agents are expensive.
Value iteration in code
import numpy as np
# ---- Bolt's 4x3 world (AIMA Fig 17.1). (col, row) with (0,0) bottom-left; (1,1) is a wall ----
COLS, ROWS, WALL = 4, 3, (1, 1)
TERMINAL = {(3, 2): +1.0, (3, 1): -1.0}
STATES = [(c, r) for c in range(COLS) for r in range(ROWS) if (c, r) != WALL]
ACTIONS = {"N": (0, 1), "S": (0, -1), "E": (1, 0), "W": (-1, 0)}
SIDEWAYS = {"N": "EW", "S": "EW", "E": "NS", "W": "NS"}
def step(s, a):
"""Where Bolt ends up if it actually moves in direction a (bumping into walls = stay put)."""
nxt = (s[0] + ACTIONS[a][0], s[1] + ACTIONS[a][1])
return nxt if nxt in STATES else s
def transitions(s, a):
"""P(s' | s, a): 0.8 intended direction, 0.1 each perpendicular direction."""
out = {}
for prob, direction in [(0.8, a), (0.1, SIDEWAYS[a][0]), (0.1, SIDEWAYS[a][1])]:
s2 = step(s, direction)
out[s2] = out.get(s2, 0) + prob
return out
def R(s):
return TERMINAL.get(s, -0.04) # small "living cost" for every non-terminal step
def expected_utility(s, a, U):
return sum(p * U[s2] for s2, p in transitions(s, a).items())
def value_iteration(gamma=1.0, eps=1e-6):
U = {s: 0.0 for s in STATES}
k = 0
while True:
U_new, delta = {}, 0.0
for s in STATES:
if s in TERMINAL:
U_new[s] = R(s)
else: # Bellman update
U_new[s] = R(s) + gamma * max(expected_utility(s, a, U) for a in ACTIONS)
delta = max(delta, abs(U_new[s] - U[s]))
U, k = U_new, k + 1
if delta < eps:
return U, k
def greedy_policy(U, gamma=1.0):
return {s: max(ACTIONS, key=lambda a: expected_utility(s, a, U)) for s in STATES if s not in TERMINAL}
def show(U, pi=None):
for r in reversed(range(ROWS)):
row = []
for c in range(COLS):
s = (c, r)
if s == WALL: row.append(" #### ")
elif pi and s in pi: row.append(f"{U[s]:6.3f} {pi[s]}")
else: row.append(f"{U[s]:6.3f} ")
print(" ".join(row))
U, iters = value_iteration(gamma=1.0)
print(f"converged after {iters} iterations")
show(U, greedy_policy(U))converged after 30 iterations
0.812 E 0.868 E 0.918 E 1.000
0.762 N #### 0.660 N -1.000
0.705 N 0.655 W 0.611 W 0.388 W
These are exactly the utilities in AIMA Fig. 17.3. Look at cell (3,0), bottom-right, with value 0.388 and action W. The cell directly North of it is the −1 pit, so going North would mean falling in with probability 0.8. The optimal policy goes away from the goal and takes the long way round. Also (2,0) chooses W, not N: it prefers the long, safe route through the left column.
Policy iteration
Value iteration polishes the utilities to many decimal places even though only the policy matters, and the policy usually stabilizes much earlier. Policy iteration works with policies directly by alternating two steps:
- Policy evaluation: given policy \(\pi_i\), compute \(U^{\pi_i}\). The policy is fixed, so there is no max and the Bellman equations are linear: $$ U^{\pi_i}(s) = R(s) + \gamma \sum_{s'} P(s' \mid s, \pi_i(s))\, U^{\pi_i}(s'). $$ That's \(n\) linear equations in \(n\) unknowns, solvable exactly in \(O(n^3)\) with Gaussian elimination.
- Policy improvement: make the policy greedy with respect to those utilities: $$ \pi_{i+1}(s) = \arg\max_a \sum_{s'} P(s' \mid s, a)\, U^{\pi_i}(s'). $$
Repeat until the policy stops changing. At that point the policy satisfies the Bellman equation, so it is optimal.
def policy_evaluation(pi, gamma=1.0):
"""Solve the LINEAR system U(s) = R(s) + gamma * sum_s' P(s'|s,pi(s)) U(s') exactly."""
idx = {s: i for i, s in enumerate(STATES)}
A, b = np.eye(len(STATES)), np.array([R(s) for s in STATES])
for s in STATES:
if s not in TERMINAL:
for s2, p in transitions(s, pi[s]).items():
A[idx[s], idx[s2]] -= gamma * p
u = np.linalg.solve(A, b)
return {s: u[idx[s]] for s in STATES}
def policy_iteration(gamma=1.0):
pi = {s: "N" for s in STATES if s not in TERMINAL} # start: always go North
rounds = 0
while True:
U = policy_evaluation(pi, gamma)
rounds += 1
changed = 0
for s in pi: # policy improvement
best = max(ACTIONS, key=lambda a: expected_utility(s, a, U))
if expected_utility(s, best, U) > expected_utility(s, pi[s], U) + 1e-12:
pi[s], changed = best, changed + 1
print(f"round {rounds}: {changed} states changed their action")
if changed == 0:
return pi, U
pi, U = policy_iteration()
show(U, pi)round 1: 6 states changed their action
round 2: 1 states changed their action
round 3: 1 states changed their action
round 4: 1 states changed their action
round 5: 0 states changed their action
0.812 E 0.868 E 0.918 E 1.000
0.762 N #### 0.660 N -1.000
0.705 N 0.655 W 0.611 W 0.388 W
Five rounds instead of 30 sweeps, and the identical answer. Switch the widget to Policy iteration to watch the rounds.
Comparison
| Value iteration | Policy iteration | |
|---|---|---|
| Works on | Utilities | Policies |
| Cost per iteration | \(O(|S|^2|A|)\), cheap | \(O(|S|^3)\) to solve the linear system, plus improvement |
| Number of iterations | Many (depends on \(\gamma\), \(\varepsilon\)) | Few. Finite, since there are only finitely many policies, and each round strictly improves the policy until it is optimal |
| Exact answer? | Approximate (stops at \(\varepsilon\)) | Exact optimal policy |
| Best when | Many states, cheap sweeps | Fewer states, or a good initial policy is known |
Modified policy iteration sits in between: evaluate the policy approximately with \(k\) simplified Bellman sweeps (no max) instead of an exact solve. With \(k=1\) it is value iteration. The widget's PI uses this approach. Asynchronous versions update states in any order, prioritizing those whose values are changing most.
The MDL MDP assignment typically gives you a story-based world: a character with a few health levels, arrows or stamina, and a monster or a goal, with stochastic action outcomes. You're asked to:
- Enumerate the state space carefully: the Cartesian product of all components, e.g. (position, health, materials, monster state). Write a function from state tuple to index and back. Most bugs live here.
- Encode
P(s'|s,a)for every action from every state. Check that each row sums to 1 with an assert. - Run value iteration with the given γ and ε, and log the utility and action of every state at every iteration in the required trace format.
- Simulate a few episodes from given start states following the final policy.
- Change one parameter (γ, step cost, a probability) and explain the behavioural change, as in the "how reward shapes behaviour" table in §5.2.
Note which convention the assignment uses: reward on states \(R(s)\), on transitions \(R(s,a,s')\), or a step cost per action. The Bellman update changes slightly: \(U(s) = \max_a \sum_{s'} P(s'|s,a)[R(s,a,s') + \gamma U(s')]\).
Solving MDPs with Linear Programming
Value iteration and policy iteration are iterative. There's a third way that solves the MDP in one shot with an off-the-shelf solver: write it as a linear program (LP). This matters for three reasons. It gives polynomial-time guarantees, it makes adding constraints easy (for example "keep the expected battery use below X"), and its dual has a beautiful interpretation. It is also a standard MDL assignment topic.
A 60-second LP refresher
A linear program optimizes a linear objective subject to linear constraints:
$$ \min_{x}\ c^\top x \quad \text{s.t.}\quad A_{ub}\,x \le b_{ub},\quad A_{eq}\,x = b_{eq},\quad \text{bounds on } x. $$Every LP (the primal) has a dual LP. At the optimum both have the same objective value (strong duality). Solvers like scipy.optimize.linprog, PuLP and CVXPY handle thousands of variables easily.
The primal LP: utilities as variables
The Bellman equation says \(V(s) = \max_a [\,r(s,a) + \gamma\sum_{s'} P(s'|s,a)V(s')\,]\). A max is not linear, but "\(V(s)\) is at least each option" is:
$$ V(s) \;\ge\; r(s,a) + \gamma \sum_{s'} P(s' \mid s,a)\, V(s') \qquad \text{for every } s \text{ and every } a. $$Many vectors \(V\) satisfy these constraints. Any upper bound on the true values does. The smallest one is exactly the optimal value function, so:
Primal LP
$$ \min_{V}\ \sum_s \alpha(s)\, V(s) \quad \text{s.t.}\quad V(s) - \gamma \sum_{s'} P(s'\mid s,a)\, V(s') \;\ge\; r(s,a)\quad \forall s, a $$with any positive weights \(\alpha(s)\) (often all 1, or a start-state distribution). There are \(|S|\) variables and \(|S|\cdot|A|\) constraints.
Each constraint pushes \(V(s)\) up to at least the value of every action. Minimizing pushes it down as far as possible. The two meet exactly at \(V(s) = \max_a(\dots)\), the Bellman equation. For every state, the constraint of the best action is tight (holds with equality), and that tight constraint identifies the optimal action.
The dual LP: flows of probability
The dual has one variable \(x(s,a) \ge 0\) per state–action pair, and an elegant meaning: \(x(s,a)\) is the expected (discounted) number of times the agent is in state \(s\) and takes action \(a\). It's often called the occupancy measure.
Dual LP
$$ \max_{x \ge 0}\ \sum_{s,a} x(s,a)\, r(s,a) \quad\text{s.t.}\quad \sum_{a} x(s',a) - \gamma \sum_{s,a} P(s' \mid s,a)\, x(s,a) = \alpha(s') \quad \forall s'. $$Read the constraint as flow conservation, like water in pipes. The flow out of \(s'\) (the total times you act there) equals the flow that starts at \(s'\) (\(\alpha\)) plus the discounted flow that arrives from other states. The objective adds up the reward collected by all that flow. The optimal policy is recovered as
$$ \pi^*(s) = \arg\max_a x(s,a), $$since at the optimum, essentially all the flow through a state goes through its best action.
In matrix form, which is how assignments usually phrase it, the constraint is \(A x = \alpha\), where \(A\) has one row per state and one column per (state, action) pair:
$$ A[s', (s,a)] = \mathbb{1}[s = s'] - \gamma\, P(s' \mid s,a). $$A column of \(A\) holds "+1 for the state you leave, minus the (discounted) probability mass for each state you might land in." With \(\gamma = 1\) and terminal states that exit the system, each non-terminal column sums to 0 (probability is conserved), and terminal columns have just the +1.
Both LPs in code
The same 4×3 world, now with \(\gamma = 0.9\). Each terminal state has a single EXIT action that collects its reward and leaves the world.
import numpy as np
from scipy.optimize import linprog
# ---- the same 4x3 world as §5.3, written as matrices ----
COLS, ROWS, WALL = 4, 3, (1, 1)
TERMINAL = {(3, 2): +1.0, (3, 1): -1.0}
STATES = [(c, r) for c in range(COLS) for r in range(ROWS) if (c, r) != WALL]
MOVES = {"N": (0, 1), "S": (0, -1), "E": (1, 0), "W": (-1, 0)}
SIDE = {"N": "EW", "S": "EW", "E": "NS", "W": "NS"}
GAMMA = 0.9
n = len(STATES)
idx = {s: i for i, s in enumerate(STATES)}
def step(s, a):
nxt = (s[0] + MOVES[a][0], s[1] + MOVES[a][1])
return nxt if nxt in idx else s
# list every (state, action) pair; terminals get a single EXIT action that leaves the world
pairs, P, r = [], [], []
for s in STATES:
acts = ["EXIT"] if s in TERMINAL else list(MOVES)
for a in acts:
row = np.zeros(n)
if a != "EXIT":
for prob, d in [(0.8, a), (0.1, SIDE[a][0]), (0.1, SIDE[a][1])]:
row[idx[step(s, d)]] += prob
pairs.append((s, a)); P.append(row); r.append(TERMINAL.get(s, -0.04))
P, r = np.array(P), np.array(r) # P: (pairs x states), r: reward of each pair
# ---------- PRIMAL: min sum_s V(s) s.t. V(s) >= r(s,a) + gamma * sum_s' P(s'|s,a) V(s') ----------
E = np.array([[1.0 if s == t else 0.0 for t in STATES] for s, a in pairs]) # picks V(s) for each pair
primal = linprog(c=np.ones(n), A_ub=-(E - GAMMA * P), b_ub=-r, bounds=[(None, None)] * n)
V = primal.x
# ---------- DUAL: max sum x(s,a) r(s,a) s.t. flow conservation, x >= 0 ----------
alpha = np.ones(n) / n # start-state distribution (any positive vector works)
A_eq = (E - GAMMA * P).T # one row per state s': out-flow - discounted in-flow
dual = linprog(c=-r, A_eq=A_eq, b_eq=alpha, bounds=[(0, None)] * len(pairs))
x = dual.x
policy = {}
for s in STATES:
if s not in TERMINAL:
cands = [(x[i], a) for i, (t, a) in enumerate(pairs) if t == s]
policy[s] = max(cands)[1] # the action carrying the most "flow"
for row_ in reversed(range(ROWS)):
cells = []
for c in range(COLS):
s = (c, row_)
cells.append(" #### " if s == WALL else f"{V[idx[s]]:6.3f} {policy.get(s, ' ')}")
print(" ".join(cells))
print("primal objective sum V =", round(primal.fun, 4))
print("dual objective =", round(-dual.fun, 4), " = alpha . V =", round(alpha @ V, 4)) 0.509 E 0.650 E 0.795 E 1.000
0.399 N #### 0.486 N -1.000
0.296 N 0.254 E 0.345 N 0.130 W
primal objective sum V = 3.8645
dual objective = 0.3513 = alpha . V = 0.3513
Three things to notice:
- Strong duality. The dual objective equals \(\sum_s \alpha(s) V(s)\). It's the same optimization seen from the other side. (The primal objective printed uses weights of 1 instead of \(\alpha = 1/n\), hence the factor of 11.)
- The policy changed with γ! At \(\gamma = 0.9\), cells (1,0) and (2,0) now choose E and N, risking the route past the pit, where at \(\gamma=1\) they chose W and took the long safe route. With discounting, a long detour costs more, because the +1 at the end is worth less the later it arrives. Running value iteration with \(\gamma = 0.9\) gives exactly these numbers.
- Using a solver lets you add constraints. For example, "probability of ever entering the pit ≤ 5%" is a linear constraint on \(x\). This is a constrained MDP, which value iteration can't handle directly.
LP-for-MDP assignments typically ask you to output the A matrix, the R vector (reward per state–action pair), the α vector (initial state distribution, e.g. 1 at the start state and 0 elsewhere), the optimal x, the derived deterministic policy and the objective value. Tips:
- Fix an ordering of (state, action) pairs once, and use it everywhere: columns of A, entries of R and of x.
- Include only valid actions per state (for example, no "shoot" action without arrows). Each terminal state gets one NOOP/exit action.
- Sanity check: with \(\gamma=1\), every non-terminal column of A should sum to 0, because probability is conserved. Assert this.
- Many states have \(x(s,\cdot) = 0\) because they're never visited from the start distribution. Their "policy" is arbitrary. Say so in your report.
- The dual is a maximization.
linprogminimizes, so passc = -Rand negate the result.
Modelling Observation Errors: POMDPs
Everything in §5.2–5.4 assumed that Bolt knows which state it is in. The policy \(\pi(s)\) needs \(s\) as input. But Bolt's GPS is useless indoors, its camera is fooled by glass doors, and its wheel encoders drift. Real agents get observations that are noisy, partial clues about the state. This section models those observation errors.
From MDP to POMDP
A partially observable MDP adds two things to an MDP \((S, A, P, R, \gamma)\):
- A set of observations \(O\) (e.g. {sees door, sees wall}).
- A sensor model \(P(o \mid s)\): the probability of perceiving \(o\) in state \(s\). (Sometimes \(P(o \mid s, a)\), if the observation depends on the action.)
The agent never sees \(s\). It sees only \(o\).
The sensor model is the model of observation error. "The door detector is right 90% of the time" means \(P(\text{door} \mid \text{door cell}) = 0.9\) and \(P(\text{door} \mid \text{wall cell}) = 0.1\). A perfect sensor has \(P(o\mid s) \in \{0,1\}\), and the POMDP becomes an MDP again.
Belief states
If Bolt can't know its state, what should its policy depend on? The answer: on everything it believes about the state, a probability distribution over states called the belief state:
$$ b(s) = P(S_t = s \mid o_1, a_1, o_2, a_2, \dots, o_t). $$The belief summarizes the entire history of actions and observations, and it is all the agent needs. (It is a sufficient statistic.) The optimal action depends only on \(b\), not on the raw history.
You wake up in a dark hotel corridor. You don't know which room you're outside. You feel a door handle on your left: that rules out the stretches with no doors. You walk three steps and feel nothing: that rules out more. Your "map of where I might be" sharpens with each observation and blurs slightly each time you move, because your steps aren't perfectly measured. That map is the belief state, and the rule for updating it is Bayes' rule.
The belief update (filtering)
After doing action \(a\) in belief \(b\) and then observing \(o\), the new belief is:
$$ \boxed{\; b'(s') = \alpha\; P(o \mid s') \sum_{s} P(s' \mid s, a)\, b(s) \;} $$Read it right to left, as two steps:
- Predict (motion): \(\bar b(s') = \sum_s P(s' \mid s, a)\, b(s)\). Push the belief through the transition model. Uncertainty grows, because motion is noisy.
- Correct (sensing): \(b'(s') = \alpha\, P(o \mid s')\, \bar b(s')\). Weight each state by how well it explains the observation, then normalize. This is exactly Bayes' rule from §4.2, with \(\bar b\) as the prior and \(P(o|s')\) as the likelihood. Uncertainty shrinks.
This predict–correct loop is the Bayes filter. With Gaussian beliefs it becomes the Kalman filter, used in every GPS, phone and spacecraft. With samples it becomes the particle filter, used in robot localization.
Try this: press Sense once, and the belief splits into a few bumps, one at each door. Then Move right: the bumps shift and spread. Then Sense again. Repeat a few times and one peak wins. Lower the sensor accuracy to 0.6 and see how much longer it takes. Tick "peek" to check whether Bolt is right.
Worked example in code
A corridor of 10 cells with doors at 1, 3 and 7. The door sensor is 90% accurate. Bolt senses, then moves right, then repeats.
import numpy as np
# Bolt in a corridor of 10 cells. Doors at cells 1, 3 and 7. Bolt doesn't know where it is.
N = 10
door = np.zeros(N, dtype=bool); door[[1, 3, 7]] = True
# Transition model for "move right": 0.8 moves one cell, 0.1 stays, 0.1 moves two (wheel slip)
T = np.zeros((N, N)) # T[s, s'] = P(s' | s, right)
for s in range(N):
for ds, p in [(1, 0.8), (0, 0.1), (2, 0.1)]:
T[s, min(N - 1, s + ds)] += p
# Sensor model: says "door" correctly 90% of the time
def obs_likelihood(saw_door):
return np.where(door == saw_door, 0.9, 0.1) # P(o | s) for every s
def predict(b): # b'(s') = sum_s P(s'|s,a) b(s)
return b @ T
def update(b, saw_door): # b'(s) = alpha * P(o|s) * b(s)
b = obs_likelihood(saw_door) * b
return b / b.sum()
b = np.full(N, 1 / N) # uniform: "I could be anywhere"
for t, saw in enumerate([True, False, True, False]):
b = update(b, saw)
print(f"t={t} sensed {'DOOR' if saw else 'wall'}: ", np.round(b, 2))
b = predict(b)
print("most likely cell:", b.argmax(), "with belief %.2f" % b.max())t=0 sensed DOOR: [0.03 0.26 0.03 0.26 0.03 0.03 0.03 0.26 0.03 0.03]
t=1 sensed wall: [0. 0.01 0.26 0.01 0.26 0.06 0.03 0.01 0.26 0.1 ]
t=2 sensed DOOR: [0. 0.01 0.01 0.63 0.02 0.07 0.03 0.11 0.01 0.11]
t=3 sensed wall: [0. 0. 0.01 0.01 0.56 0.1 0.07 0. 0.1 0.15]
most likely cell: 5 with belief 0.46
Follow the story. At t=0, "door" means Bolt is at one of the three doors, about 26% each. After moving right and sensing a wall, all three hypotheses survive (each door has a wall to its right). At t=2, "door" again: only the hypothesis "I started at door 1" predicts a door two cells later (cell 3), so its probability jumps to 0.63. The pattern of observations over time pins down the location, even though no single observation could.
Two states \(\{A, B\}\), belief \(b = (0.5, 0.5)\). An action keeps the state with probability 0.7 and switches with probability 0.3. The sensor reports the true state with probability 0.8. After the action, you observe "A".
- Predict: \(\bar b(A) = 0.7(0.5) + 0.3(0.5) = 0.5\), and \(\bar b(B) = 0.5\).
- Correct: unnormalized \((0.8 \times 0.5,\ 0.2\times 0.5) = (0.4, 0.1)\).
- Normalize: \(b' = (0.8, 0.2)\).
Observe "A" again after another action. Predict: \(\bar b(A) = 0.7(0.8)+0.3(0.2) = 0.62\) and \(\bar b(B) = 0.38\). Correct: \((0.8 \times 0.62,\ 0.2 \times 0.38) = (0.496, 0.076)\), so \(b' \approx (0.867, 0.133)\).
Decisions in a POMDP: the belief-state MDP
The key theoretical move: treat the belief as the state. Then
- the "state" \(b\) is fully observable, since the agent always knows its own belief;
- the transitions are probabilistic: from \(b\) and action \(a\), the next belief depends on which observation arrives, which happens with probability \(P(o \mid b, a) = \sum_{s'} P(o|s') \sum_s P(s'|s,a)b(s)\);
- the reward is the expected reward, \(\rho(b) = \sum_s b(s) R(s)\).
So a POMDP is an MDP over beliefs, and the optimal policy is \(\pi^*(b)\). The catch is that the belief space is continuous: with \(n\) states, beliefs live in an \((n-1)\)-dimensional simplex. Value iteration over a continuous space is a different game.
Why POMDPs are hard, and how they're solved
- For a finite horizon, the optimal value function over beliefs is piecewise linear and convex. It is the max of a set of linear functions ("α-vectors"), each corresponding to a conditional plan. Exact POMDP value iteration manipulates these α-vectors, but their number can grow exponentially with the horizon. Solving POMDPs exactly is PSPACE-hard.
- Approximations are used in practice: point-based value iteration (only update at sampled beliefs), online lookahead search from the current belief, and the QMDP heuristic: solve the underlying MDP to get \(Q(s,a)\), then act by \(\arg\max_a \sum_s b(s) Q(s,a)\).
QMDP assumes all uncertainty will vanish after one step, so it never takes an action purely to gather information, like "stop and look around." A true POMDP solution values information automatically. Actions that reduce uncertainty raise the expected value of future decisions. This is the value of information (§5.1) appearing again, now inside sequential decisions.
POMDP assignments usually ask you to (1) specify a POMDP: list states, actions, observations, the transition table, the observation table and rewards, often in the .pomdp file format used by solvers like pomdp-solve or SARSOP, with a given initial belief; (2) compute belief updates by hand or in code for a given action–observation sequence; and (3) interpret a solver's policy graph. Common mistakes: an observation table indexed by (start state) instead of (end state), and probabilities that don't sum to 1 across observations for each state.
Chapter summary
- MEU: choose \(\arg\max_a \sum_{s'} P(s'|a)U(s')\). The value of information = best EU with info − best EU without.
- MDP = \((S, A, P, R, \gamma)\) + Markov property. The solution is a policy.
- Bellman: \(U(s) = R(s) + \gamma \max_a \sum_{s'} P(s'|s,a)U(s')\).
- Value iteration repeats Bellman updates (a contraction). Policy iteration alternates exact evaluation (linear) and greedy improvement. LP: primal over \(V\), dual over flows \(x(s,a)\).
- POMDP adds a sensor model \(P(o|s)\). Act on the belief \(b\), updated by \(b'(s') = \alpha P(o|s')\sum_s P(s'|s,a)b(s)\).
All of this assumed someone handed Bolt the model: transition probabilities, sensor accuracies, rewards. Where do such models come from? From data. Next, Bolt learns interpretable rules from examples with decision trees, and then learns whole probabilistic models with Bayesian networks.
Decision Tree Learning
Decision trees are probably the most human of all learned models. A doctor's triage flowchart, a bank's loan checklist and a 20-questions game are all decision trees. This chapter shows how to learn one automatically from examples, using an idea from information theory: ask the question that tells you the most.
Decision trees also tie together everything so far:
- Building a tree is a greedy search through the space of trees: hill climbing (Ch 3) with no backtracking.
- The search is guided by entropy, a measure of uncertainty built from probability (Ch 4).
- Choosing the most informative attribute mirrors the value of information (Ch 5).
- Trees overfit spectacularly if left unchecked, and we fix that with the validation and pruning ideas of Ch 2.
- §6.1 What is a decision tree?: representation, expressiveness, and why we can't just try them all.
- §6.2 Entropy and information gain: measuring uncertainty in bits, and how much a question reduces it.
- §6.3 Building a tree: ID3: the full algorithm, worked by hand on the classic PlayTennis data, plus code and an interactive builder.
- §6.4 Overfitting, pruning and real-world trees: depth vs. accuracy, pruning, continuous attributes, missing values and random forests.
The canteen manager asks: "Can you tell me in advance which orders will be late, and why?" A neural network might predict well, but it can't explain itself. A decision tree can: "If the distance is over 3.2 km, it'll be late. Otherwise, if it's between 9 and 11 pm (rush hour) and over 1.5 km, it'll be late. Otherwise it's on time." That's a model the manager can read, check and act on.
What Is a Decision Tree?
A decision tree classifies an example by asking a sequence of questions about its attributes:
- Each internal node tests one attribute ("Outlook?").
- Each branch corresponds to one value (or range) of that attribute ("Sunny").
- Each leaf gives a prediction ("Play = No").
To classify, start at the root and follow the branches matching the example until you reach a leaf.
Trees are logic
Every root-to-leaf path is a conjunction (AND) of tests. The whole tree is a disjunction (OR) of the paths ending in "Yes":
$$ \text{Play} \iff (\text{Sunny} \wedge \text{Normal}) \;\vee\; (\text{Overcast}) \;\vee\; (\text{Rain} \wedge \text{Weak}). $$This is disjunctive normal form. So trees can be converted directly into human-readable if-then rules, and that is a huge practical advantage. Medicine, finance and law often require explainable models.
How expressive are trees?
For Boolean attributes, any Boolean function can be written as a decision tree: in the worst case, give each row of the truth table its own path. But some functions need huge trees:
- Majority ("Yes if more than half the attributes are true") and parity (XOR, "Yes if an odd number are true") need exponentially many nodes. No single attribute is informative on its own. Only the combination is.
- For continuous attributes, trees make axis-parallel splits ("distance ≤ 3.2"). A diagonal boundary like "late if distance + hour/2 > 14" can only be approximated by a staircase.
Why not just try every tree?
How many distinct Boolean functions are there on \(n\) Boolean attributes? A truth table has \(2^n\) rows, and each row can be Yes or No, so there are
$$ 2^{2^n} \text{ functions.} $$For \(n = 6\) that's \(2^{64} \approx 1.8\times 10^{19}\). For \(n = 10\) it's about \(10^{308}\). The space is far too big to search exhaustively. Even finding the smallest consistent tree is NP-hard. So we use a greedy heuristic: build the tree top-down and pick the "most important" attribute at each node. Defining "most important" is the job of §6.2.
A tree that memorizes the training set always exists (one leaf per example), and it generalizes terribly, like the degree-14 polynomial in §2.2. We want a small tree consistent with the data. This preference for simplicity is Occam's razor: among hypotheses that fit the data, prefer the simplest. Why does it work? There are far fewer small trees than big ones, so a small tree that fits the data is unlikely to fit by coincidence. That's the same intuition as "low-variance models generalize."
When are trees a good choice?
- Instances are attribute–value pairs (tabular data).
- The target is discrete (classification). Regression trees exist too: their leaves hold numbers.
- An explanation is needed (disjunctive rules).
- The data may contain noise or missing values (§6.4).
- Features have different scales and types. Trees don't care about scaling, and they mix categorical and numeric features freely.
Entropy and Information Gain
Think of the game "20 questions." A good first question is "Is it alive?", not "Is it a left-handed penguin?". The good question splits the possibilities roughly in half, whatever the answer. The bad one almost always gets "no" and teaches you almost nothing. To build good trees we need to measure, in numbers, how much a question tells us. Claude Shannon worked out how in 1948.
Surprise and information
How much information do you gain when an event with probability \(p\) happens? Shannon wanted a measure \(I(p)\) with three properties:
- Certain events carry no information: \(I(1) = 0\).
- Rarer events carry more: \(I\) decreases in \(p\).
- Information from independent events adds: \(I(p_1 p_2) = I(p_1) + I(p_2)\).
The only function with these properties is the logarithm:
$$ I(p) = -\log_2 p \quad \text{bits.} $$A fair coin flip gives \(-\log_2 \tfrac12 = 1\) bit. Learning which of 8 equally likely hostels an order came from gives \(-\log_2 \tfrac18 = 3\) bits, which is exactly three yes/no questions.
Entropy: expected surprise
The entropy of a random variable is its average information content. It measures how uncertain we are before seeing the outcome:
$$ \boxed{\,H(X) = -\sum_{k} P(x_k) \log_2 P(x_k)\,} \qquad (\text{with } 0 \log 0 = 0). $$For a Boolean variable that is true with probability \(p\), write \(B(p)\):
$$ B(p) = -p\log_2 p - (1-p)\log_2(1-p). $$| Distribution | Entropy | Meaning |
|---|---|---|
| \(p = 0\) or \(1\) | 0 bits | No uncertainty: you already know |
| \(p = 0.5\) (fair coin) | 1 bit | Maximum uncertainty for 2 outcomes |
| \(p = 0.99\) | 0.08 bits | Almost certain |
| Uniform over \(k\) outcomes | \(\log_2 k\) bits | Maximum for \(k\) outcomes |
For a set \(S\) of training examples with \(p\) positive and \(n\) negative ones, the entropy of the labels is \(H(S) = B\!\left(\frac{p}{p+n}\right)\). A pure set (all one class) has entropy 0. A 50/50 set has entropy 1. That's exactly what we need: a measure of how "mixed" a node is.
14 examples, 9 Yes and 5 No:
$$ H(S) = -\tfrac{9}{14}\log_2\tfrac{9}{14} - \tfrac{5}{14}\log_2\tfrac{5}{14} = 0.643(0.637) + 0.357(1.485) = 0.410 + 0.530 = 0.940 \text{ bits}. $$Log tricks for exams without a calculator: \(\log_2 x = \ln x / \ln 2 = \log_{10} x / 0.301\). Memorize \(B(1/4) = B(3/4) = 0.811\), \(B(1/3) = B(2/3) = 0.918\), \(B(2/5) = B(3/5) = 0.971\) and \(B(1/2) = 1\).
Information gain
Now ask a question: split \(S\) on attribute \(A\). Each value \(v\) of \(A\) gets a subset \(S_v\). After the split, the expected remaining entropy is the weighted average of the children's entropies, called the remainder:
$$ \text{Remainder}(A) = \sum_{v \in \text{Values}(A)} \frac{|S_v|}{|S|}\, H(S_v). $$The information gain is how much the split reduces entropy:
$$ \boxed{\,\text{Gain}(S, A) = H(S) - \sum_{v} \frac{|S_v|}{|S|} H(S_v)\,} $$ID3 splits on the attribute with the highest gain: the question whose answer, on average, leaves the least uncertainty.
| Outlook | Examples | [+, −] | \(H(S_v)\) |
|---|---|---|---|
| Sunny | 5 | [2+, 3−] | \(B(2/5) = 0.971\) |
| Overcast | 4 | [4+, 0−] | 0 (pure!) |
| Rain | 5 | [3+, 2−] | \(B(3/5) = 0.971\) |
Similarly: Humidity: High [3+,4−] (\(H=0.985\)), Normal [6+,1−] (\(H=0.592\)), so Gain = \(0.940 - \tfrac{7}{14}0.985 - \tfrac{7}{14}0.592 = 0.152\). Wind: Weak [6+,2−] (\(H=0.811\)), Strong [3+,3−] (\(H=1\)), so Gain = \(0.940 - \tfrac{8}{14}0.811 - \tfrac{6}{14}1 = 0.048\). Temperature: Gain = 0.029. Outlook wins.
Check every number above with the calculator. Choose a preset or type your own counts:
In code
import math
from collections import Counter
ATTRS = ["Outlook", "Temp", "Humidity", "Wind"]
DATA = [("Sunny","Hot","High","Weak","No"), ("Sunny","Hot","High","Strong","No"),
("Overcast","Hot","High","Weak","Yes"), ("Rain","Mild","High","Weak","Yes"),
("Rain","Cool","Normal","Weak","Yes"), ("Rain","Cool","Normal","Strong","No"),
("Overcast","Cool","Normal","Strong","Yes"), ("Sunny","Mild","High","Weak","No"),
("Sunny","Cool","Normal","Weak","Yes"), ("Rain","Mild","Normal","Weak","Yes"),
("Sunny","Mild","Normal","Strong","Yes"), ("Overcast","Mild","High","Strong","Yes"),
("Overcast","Hot","Normal","Weak","Yes"), ("Rain","Mild","High","Strong","No")]
def entropy(rows):
counts = Counter(r[-1] for r in rows)
n = len(rows)
return -sum(c / n * math.log2(c / n) for c in counts.values())
def info_gain(rows, attr):
i = ATTRS.index(attr)
remainder = 0.0
for value in set(r[i] for r in rows):
subset = [r for r in rows if r[i] == value]
remainder += len(subset) / len(rows) * entropy(subset)
return entropy(rows) - remainder
print("H(S) = %.3f" % entropy(DATA))
for a in ATTRS:
print(f"Gain(S, {a:8s}) = {info_gain(DATA, a):.3f}")
sunny = [r for r in DATA if r[0] == "Sunny"]
print("\nInside the Sunny branch, H = %.3f" % entropy(sunny))
for a in ["Temp", "Humidity", "Wind"]:
print(f"Gain(Sunny, {a:8s}) = {info_gain(sunny, a):.3f}")H(S) = 0.940
Gain(S, Outlook ) = 0.247
Gain(S, Temp ) = 0.029
Gain(S, Humidity) = 0.152
Gain(S, Wind ) = 0.048
Inside the Sunny branch, H = 0.971
Gain(Sunny, Temp ) = 0.571
Gain(Sunny, Humidity) = 0.971
Gain(Sunny, Wind ) = 0.020
Inside the Sunny branch, Humidity has gain 0.971, equal to the branch's entire entropy. That means Humidity splits the Sunny days perfectly: High → all No, Normal → all Yes.
A flaw of information gain, and the fix
Suppose we add an attribute "Date" with a unique value for every day. Splitting on Date gives 14 pure children with one example each, so Remainder = 0 and the gain is the maximum possible, 0.940. ID3 would happily put Date at the root. It's a perfect fit to the training data and useless for prediction, which is overfitting again. Information gain is biased toward attributes with many values.
C4.5's fix is the gain ratio. Divide by the "split information," the entropy of the split itself:
$$ \text{SplitInfo}(S, A) = -\sum_v \frac{|S_v|}{|S|}\log_2\frac{|S_v|}{|S|}, \qquad \text{GainRatio} = \frac{\text{Gain}(S,A)}{\text{SplitInfo}(S,A)}. $$Date has SplitInfo = \(\log_2 14 = 3.81\), which heavily penalizes its gain ratio. Outlook splits the 14 days into groups of 5, 4 and 5, so its SplitInfo is the entropy of those proportions: 1.577. Its gain ratio is therefore \(0.247/1.577 = 0.157\).
Gini impurity: the other popular measure
CART (and scikit-learn's default) uses Gini impurity instead of entropy:
$$ \text{Gini}(S) = 1 - \sum_k p_k^2. $$It is the probability of mislabelling a random example if you label it randomly according to the node's class distribution. It's 0 for a pure node and 0.5 for a 50/50 binary node. Gini and entropy have similar shapes and usually choose the same splits. Gini is slightly cheaper to compute (no logarithms).
- Entropy is expected surprise, an expectation over a probability distribution (Ch 4).
- Information gain = how much observing \(A\) is expected to reduce uncertainty about the class. That is the mutual information \(I(A; \text{Class})\). The value of information (§5.1) is the same idea measured in utility instead of bits.
- Cross-entropy, the standard loss for neural-network classifiers, is a close relative of entropy.
Building a Tree from Examples: ID3
We now have all the pieces. ID3 (Iterative Dichotomiser 3, Ross Quinlan, 1986) builds a tree top-down by repeatedly asking the most informative question. Its descendants C4.5 and CART still power real systems, including random forests and gradient boosting.
The algorithm
function ID3(examples, attributes, parent_examples):
if examples is empty: return PLURALITY(parent_examples)
else if all examples have the same class: return that class
else if attributes is empty: return PLURALITY(examples)
else:
A ← the attribute in attributes with the highest Gain(examples, A)
tree ← a new node testing A
for each value v of A:
exs ← { e in examples : e.A = v }
subtree ← ID3(exs, attributes − {A}, examples)
add a branch to tree labelled (A = v) leading to subtree
return tree
Each of the three base cases has a reason:
- No examples left for some value: we've never seen this combination, so guess the parent's majority class.
- All examples agree: the node is pure, so make a leaf.
- No attributes left but the examples still disagree: identical inputs with different labels. That's noise (or a missing feature), so take a majority vote. Remember \(y = f(x) + \varepsilon\) from Chapter 2.
Worked example: the whole PlayTennis tree by hand
| Day | Outlook | Temp | Humidity | Wind | Play |
|---|---|---|---|---|---|
| D1 | Sunny | Hot | High | Weak | No |
| D2 | Sunny | Hot | High | Strong | No |
| D3 | Overcast | Hot | High | Weak | Yes |
| D4 | Rain | Mild | High | Weak | Yes |
| D5 | Rain | Cool | Normal | Weak | Yes |
| D6 | Rain | Cool | Normal | Strong | No |
| D7 | Overcast | Cool | Normal | Strong | Yes |
| D8 | Sunny | Mild | High | Weak | No |
| D9 | Sunny | Cool | Normal | Weak | Yes |
| D10 | Rain | Mild | Normal | Weak | Yes |
| D11 | Sunny | Mild | Normal | Strong | Yes |
| D12 | Overcast | Mild | High | Strong | Yes |
| D13 | Overcast | Hot | Normal | Weak | Yes |
| D14 | Rain | Mild | High | Strong | No |
Step 1: the root. From §6.2: Gain(Outlook) = 0.247, Gain(Humidity) = 0.152, Gain(Wind) = 0.048, Gain(Temp) = 0.029. Split on Outlook.
Step 2: Overcast branch {D3, D7, D12, D13}: all Yes, so it's a leaf: Yes.
Step 3: Sunny branch {D1, D2, D8, D9, D11} = [2+, 3−], H = 0.971.
| Attribute | Split | Remainder | Gain |
|---|---|---|---|
| Humidity | High [0+,3−], Normal [2+,0−] | 0 | 0.971 |
| Temp | Hot [0+,2−], Mild [1+,1−], Cool [1+,0−] | \(\tfrac25 \cdot 1 = 0.400\) | 0.571 |
| Wind | Weak [1+,2−], Strong [1+,1−] | \(\tfrac35(0.918) + \tfrac25(1) = 0.951\) | 0.020 |
Split on Humidity: High → No, Normal → Yes. Both children are pure.
Step 4: Rain branch {D4, D5, D6, D10, D14} = [3+, 2−], H = 0.971.
| Attribute | Split | Remainder | Gain |
|---|---|---|---|
| Wind | Weak [3+,0−], Strong [0+,2−] | 0 | 0.971 |
| Humidity | High [1+,1−], Normal [2+,1−] | \(\tfrac25(1) + \tfrac35(0.918) = 0.951\) | 0.020 |
| Temp | Mild [2+,1−], Cool [1+,1−] | 0.951 | 0.020 |
Split on Wind: Weak → Yes, Strong → No.
Done. The tree in §6.1 uses only 3 of the 4 attributes. Temperature was never needed. The algorithm discovered that it's irrelevant given the others, which is automatic feature selection.
Play with it
The builder below runs ID3 live. Untick a few rows to remove those examples and watch the tree change. Remove D6 and D14 (the only "Rain, No" days), and the whole Rain branch collapses into a single "Yes" leaf. Now restore them and remove only D3, a single Overcast day. The root itself flips from Outlook to Humidity (gain 0.219 vs 0.214), and the whole tree reorganizes. Removing D13, another Overcast day, changes nothing. One example out of fourteen can rewrite the whole model: decision trees are high-variance models (§2.3). That's the reason random forests exist (§6.4).
In code
import math
from collections import Counter
ATTRS = ["Outlook", "Temp", "Humidity", "Wind"]
DATA = [("Sunny","Hot","High","Weak","No"), ("Sunny","Hot","High","Strong","No"),
("Overcast","Hot","High","Weak","Yes"), ("Rain","Mild","High","Weak","Yes"),
("Rain","Cool","Normal","Weak","Yes"), ("Rain","Cool","Normal","Strong","No"),
("Overcast","Cool","Normal","Strong","Yes"), ("Sunny","Mild","High","Weak","No"),
("Sunny","Cool","Normal","Weak","Yes"), ("Rain","Mild","Normal","Weak","Yes"),
("Sunny","Mild","Normal","Strong","Yes"), ("Overcast","Mild","High","Strong","Yes"),
("Overcast","Hot","Normal","Weak","Yes"), ("Rain","Mild","High","Strong","No")]
def entropy(rows):
n = len(rows)
return -sum(c / n * math.log2(c / n) for c in Counter(r[-1] for r in rows).values())
def info_gain(rows, i):
rem = 0.0
for v in set(r[i] for r in rows):
sub = [r for r in rows if r[i] == v]
rem += len(sub) / len(rows) * entropy(sub)
return entropy(rows) - rem
def plurality(rows):
return Counter(r[-1] for r in rows).most_common(1)[0][0]
def id3(rows, attrs, parent_rows=None):
if not rows: # no examples: use the parent's majority
return plurality(parent_rows)
labels = set(r[-1] for r in rows)
if len(labels) == 1: # pure node: a leaf
return labels.pop()
if not attrs: # no attributes left: majority vote
return plurality(rows)
best = max(attrs, key=lambda i: info_gain(rows, i))
tree = {"attr": ATTRS[best], "branches": {}}
for v in sorted(set(r[best] for r in DATA)): # every value of the attribute, seen or not
subset = [r for r in rows if r[best] == v]
tree["branches"][v] = id3(subset, [a for a in attrs if a != best], rows)
return tree
def show(tree, indent=""):
if isinstance(tree, str):
print(indent + "-> " + tree); return
for v, sub in tree["branches"].items():
print(f"{indent}{tree['attr']} = {v}")
show(sub, indent + " ")
def classify(tree, x):
while isinstance(tree, dict):
tree = tree["branches"][x[ATTRS.index(tree["attr"])]]
return tree
tree = id3(DATA, list(range(len(ATTRS))))
show(tree)
print("training accuracy:", sum(classify(tree, r) == r[-1] for r in DATA), "/", len(DATA))
print("new day (Sunny, Cool, High, Strong) ->", classify(tree, ("Sunny", "Cool", "High", "Strong")))Outlook = Overcast
-> Yes
Outlook = Rain
Wind = Strong
-> No
Wind = Weak
-> Yes
Outlook = Sunny
Humidity = High
-> No
Humidity = Normal
-> Yes
training accuracy: 14 / 14
new day (Sunny, Cool, High, Strong) -> No
The tree says No for (Sunny, Cool, High, Strong), the same answer naive Bayes gave in §4.2 with 79.5% confidence. Two very different models with different inductive biases agree here. When they disagree, it's worth asking why.
ID3 as search
Viewed through Chapter 3, ID3 is a greedy hill-climbing search through the space of trees:
- State: a partial tree. Move: replace a leaf with a test. Heuristic: information gain.
- No backtracking: once it chooses Outlook at the root, it never reconsiders. Like any hill climber it can reach a local optimum: a tree that's consistent but bigger than necessary. Parity functions fool it completely, because every single attribute has zero gain on its own.
- Uses all examples at every step (statistics, not individual examples), so it is fairly robust to individual noisy examples.
ID3's inductive bias: it prefers shorter trees, and trees that put high-information-gain attributes near the root. This is a preference (search) bias, not a restriction bias: the hypothesis space contains every possible tree, and the algorithm simply tries the simple-looking ones first.
- "Construct the decision tree for this dataset using ID3. Show all information-gain computations." Lay it out exactly like Steps 1–4: a table per node with splits, remainders and gains.
- Remember to remove the used attribute when you recurse, and handle empty branches with the parent's majority.
- Ties: state your tie-breaking rule (e.g. alphabetical, or first in the list).
- "What is ID3's inductive bias?" Shorter trees; high-gain attributes near the root; Occam's razor.
Overfitting, Pruning and Real-World Trees
ID3 keeps splitting until every leaf is pure. On clean data that's fine. On real data with noise, "pure leaves" means memorizing the noise: one leaf for every weird delivery that happened to be late because the security guard was chatty. You've seen this disease before, in §2.2 with polynomials.
Watching a tree overfit
Bolt's late-delivery data has two numeric features, distance (km) and hour (18:00 to 02:00, written 18–26). The true rule is "late if distance > 3.2, or if it's 21:00–23:00 and distance > 1.5." On top of that, 15% of labels are flipped at random: unexplained lateness. So even a perfect model can reach only about 85% accuracy. We grow trees of increasing maximum depth:
import numpy as np
rng = np.random.default_rng(1)
def make_orders(n):
dist = rng.uniform(0, 5, n) # km
hour = rng.uniform(18, 26, n) # 18:00 .. 02:00
late = (dist > 3.2) | ((hour > 21) & (hour < 23) & (dist > 1.5)) # the true rule
flip = rng.random(n) < 0.15 # 15% label noise: unexplained lateness
return np.column_stack([dist, hour]), (late ^ flip).astype(int)
X_tr, y_tr = make_orders(200)
X_te, y_te = make_orders(5000)
def entropy(y):
p = np.bincount(y, minlength=2) / len(y)
p = p[p > 0]
return -(p * np.log2(p)).sum()
def best_split(X, y):
best = (0.0, None, None) # (gain, feature, threshold)
H = entropy(y)
for f in range(X.shape[1]):
values = np.unique(X[:, f])
for t in (values[:-1] + values[1:]) / 2: # candidate thresholds: midpoints
left = X[:, f] <= t
g = H - (left.mean() * entropy(y[left]) + (~left).mean() * entropy(y[~left]))
if g > best[0]:
best = (g, f, t)
return best
def grow(X, y, depth, max_depth):
if depth == max_depth or entropy(y) == 0:
return int(np.bincount(y, minlength=2).argmax())
g, f, t = best_split(X, y)
if f is None:
return int(np.bincount(y, minlength=2).argmax())
left = X[:, f] <= t
return (f, t, grow(X[left], y[left], depth + 1, max_depth), grow(X[~left], y[~left], depth + 1, max_depth))
def predict(node, x):
while isinstance(node, tuple):
f, t, l, r = node
node = l if x[f] <= t else r
return node
def accuracy(tree, X, y):
return np.mean([predict(tree, x) == t for x, t in zip(X, y)])
print("depth | train acc | test acc")
for d in [1, 2, 3, 4, 6, 8, 12, 20]:
tree = grow(X_tr, y_tr, 0, d)
print(f"{d:5d} | {accuracy(tree, X_tr, y_tr):9.3f} | {accuracy(tree, X_te, y_te):8.3f}")depth | train acc | test acc
1 | 0.815 | 0.778
2 | 0.815 | 0.778
3 | 0.840 | 0.776
4 | 0.915 | 0.823
6 | 0.950 | 0.787
8 | 0.980 | 0.772
12 | 1.000 | 0.758
20 | 1.000 | 0.758
It's the U-shape again, now in accuracy (so it's upside down). Training accuracy climbs to a perfect 1.000. Test accuracy peaks at depth 4 (0.823, close to the ~0.85 ceiling) and then declines as the tree carves out tiny regions around noisy points. Depth is the tree's complexity knob, just like polynomial degree.
Two ways to stop overfitting
1. Pre-pruning (early stopping)
Stop growing a branch when:
- a maximum depth is reached;
- a node has fewer than
min_samplesexamples; - the best gain is below a threshold;
- the split is not statistically significant, which is the χ² test.
χ² pruning (AIMA §19.3) asks: is this split's apparent gain real, or could it come from random noise? Suppose a node has \(p\) positives and \(n\) negatives, and a split sends \(p_k, n_k\) to child \(k\). If the attribute were irrelevant, we'd expect \(\hat p_k = p \cdot \frac{p_k+n_k}{p+n}\) positives in child \(k\) (and similarly \(\hat n_k\)). The deviation
$$ \Delta = \sum_k \frac{(p_k - \hat p_k)^2}{\hat p_k} + \frac{(n_k - \hat n_k)^2}{\hat n_k} $$follows a χ² distribution with \(v-1\) degrees of freedom under the "irrelevant" hypothesis. If \(\Delta\) is below the 5% critical value, the split is not significant, so don't make it.
The danger of pre-pruning is the horizon effect. A split might look useless on its own but enable great splits below it. XOR is the extreme case: neither attribute alone has any gain.
2. Post-pruning (grow, then cut)
Grow the full tree, then remove parts that don't help. This is usually better, because it sees the whole tree before deciding.
Reduced-error pruning (simple and effective):
- Split the data into training and validation sets (§2.4).
- Grow the full tree on the training set.
- For each internal node (bottom-up), try replacing its subtree with a leaf predicting the majority class. If validation accuracy doesn't decrease, keep the change.
- Repeat until any further pruning would hurt validation accuracy.
Rule post-pruning (C4.5): convert the tree into one rule per path, remove any precondition whose removal doesn't hurt the estimated accuracy, then sort the rules by accuracy. Rules are pruned independently, which is more flexible than cutting whole subtrees.
Cost-complexity pruning (CART, and scikit-learn's ccp_alpha): minimize \(\text{Error}(T) + \alpha \cdot |\text{leaves}(T)|\). This is regularization exactly as in §2.4: a penalty on complexity, with \(\alpha\) tuned by cross-validation.
Max depth is polynomial degree. Cost-complexity \(\alpha\) is ridge's \(\lambda\). Reduced-error pruning is validation-based model selection. χ² pruning is a statistical test of "signal vs noise." Every model family has a complexity knob, and the bias–variance tradeoff always applies.
Real-world extensions
Continuous attributes
For a numeric attribute like distance, test a threshold "distance ≤ t". Which values of t should you try? Sort the examples by the attribute. The only thresholds that can be optimal are midpoints between adjacent examples with different labels. For \(n\) examples there are at most \(n-1\) candidates, so evaluate the gain of each and keep the best. (The code above tries all midpoints, which is simpler and slightly slower.) A numeric attribute can be reused deeper in the tree with a different threshold, unlike a categorical attribute in ID3.
Temperature: 40, 48, 60, 72, 80, 90 with labels No, No, Yes, Yes, Yes, No. The label changes between 48→60 and between 80→90, so the candidates are \(t = 54\) and \(t = 85\).
- \(t=54\): ≤54 gives [0+, 2−] (H = 0), >54 gives [3+, 1−] (H = 0.811). Remainder = \(\frac46(0.811) = 0.541\). H(parent) = B(3/6) = 1, so the gain is 0.459.
- \(t=85\): ≤85 gives [3+, 2−] (H = 0.971), >85 gives [0+, 1−] (H = 0). Remainder = \(\frac56(0.971) = 0.809\), so the gain is 0.191.
Choose \(t = 54\).
Missing values
- Fill in the most common value at that node (among examples with the same class, if known).
- C4.5 sends a fraction of the example down each branch, proportional to how many training examples went each way, and combines the predictions with those weights.
Attributes with costs
If measuring an attribute is expensive (a blood test vs. asking a question), use \(\text{Gain}^2/\text{Cost}\) or similar, which trades informativeness against cost. This is value of information versus price, as in §5.1.
Regression trees
To predict a number, each leaf stores the mean of its examples, and splits are chosen to reduce variance (equivalently, squared error) instead of entropy. It's the same algorithm with a different impurity measure.
Ensembles: making high variance an asset
Single trees are unstable, as you saw when deleting D3 in §6.3 flipped the root. §2.3 told us that averaging models trained on different data reduces variance. Two hugely successful methods build on this:
- Random forests (bagging): train hundreds of deep trees, each on a bootstrap resample of the data, and each choosing from a random subset of features at every split. Average their votes. The individual trees overfit in different ways, and averaging cancels the noise. This is often the best "out-of-the-box" model for tabular data.
- Gradient boosting (XGBoost, LightGBM): train shallow trees sequentially, each one fitting the errors of the ensemble so far. Boosting reduces bias. It wins a large share of tabular ML competitions.
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import cross_val_score
for depth in [2, 4, 6, None]:
clf = DecisionTreeClassifier(criterion="entropy", max_depth=depth, random_state=0)
print(depth, cross_val_score(clf, X_tr, y_tr, cv=5).mean())
clf = DecisionTreeClassifier(criterion="entropy", max_depth=4).fit(X_tr, y_tr)
print(export_text(clf, feature_names=["distance", "hour"])) # human-readable rulescriterion="entropy" gives information gain, and the default is Gini. Tune max_depth, min_samples_leaf or ccp_alpha by cross-validation, never on the test set.
Chapter summary
- Trees = readable disjunctions of conjunctions. They can represent any Boolean function, but some only with huge trees.
- Entropy \(H = -\sum p \log_2 p\) measures impurity. Gain = H(parent) − weighted H(children).
- ID3 is greedy hill climbing on gain, with inductive bias toward short trees and high-gain attributes near the root.
- Information gain favours many-valued attributes, so use gain ratio. Gini is a common alternative.
- Trees overfit as depth grows. Control them with pre-pruning (depth, χ²) or post-pruning (reduced-error, cost-complexity).
- Trees have high variance, and random forests average it away.
Bayesian Networks
In §4.1 we found that a full joint distribution answers any probabilistic question, but needs \(2^n\) numbers. That's fine for 3 variables and hopeless for 30. Bayesian networks fix this. They use the fact that most variables only directly depend on a few others, and they draw those dependencies as a graph. The result is compact, readable and efficient to reason with. Judea Pearl received the Turing Award largely for this idea.
- §7.1 Representing uncertain knowledge: nodes, arrows, CPTs, the factorization of the joint, and how to build a network.
- §7.2 Conditional independence and d-separation: reading independencies straight off the graph, including the strange phenomenon of "explaining away."
- §7.3 Exact inference: enumeration and variable elimination, worked by hand, with an interactive network.
- §7.4 Approximate inference and learning: rejection sampling, likelihood weighting, Gibbs sampling, and learning CPTs from data.
Bolt has an anti-theft alarm. It is triggered by attempted thefts, and sometimes by small earthquakes that shake the campus. Two hostel residents, John and Mary, call security when they hear it. John sometimes confuses Bolt's alarm with a phone ringtone. Mary often has headphones on. Tonight both called. How worried should security be that someone is stealing Bolt? And if the news reports a small earthquake, how much should that calm everyone down?
This chapter combines nearly everything: probability and Bayes' rule (Ch 4) are its language, conditional independence (§4.2) is its foundation, decision networks (§5.1) are Bayes nets plus decisions and utilities, naive Bayes (§4.2) is its simplest special case, POMDP belief updates (§5.5) are inference in a dynamic Bayes net, and learning CPTs from data is ML with the overfitting issues of Ch 2.
Representing Uncertain Knowledge
The definition
A Bayesian network is a directed acyclic graph (DAG) where
- each node is a random variable;
- each arrow \(X \to Y\) means "X directly influences Y" (X is a parent of Y);
- each node \(X_i\) has a conditional probability table (CPT) \(\mathbf{P}(X_i \mid \text{Parents}(X_i))\).
Look at what the network says, and at what it doesn't say:
- Burglary and Earthquake both directly influence the Alarm.
- John and Mary only react to the Alarm. They don't see burglars or feel earthquakes directly. If John notices the burglar himself, the model is wrong, and we'd need an arrow B → J.
- All the messy details (Mary's headphones, John's ringtone confusion) are summarized in the CPT numbers: 0.70 rather than 1.0, and 0.05 rather than 0.
The semantics: the joint factorizes
Here is the key equation. A Bayes net represents the joint distribution as the product of the local CPTs:
$$ \boxed{\; P(x_1, \dots, x_n) = \prod_{i=1}^{n} P\big(x_i \mid \text{parents}(X_i)\big) \;} $$Compare this with the always-true chain rule from §4.1: \(P(x_1,\dots,x_n) = \prod_i P(x_i \mid x_1, \dots, x_{i-1})\). The Bayes net replaces "all previous variables" with "just my parents." That replacement is valid exactly when each variable is conditionally independent of its other predecessors given its parents. That's the assumption a Bayes net makes, and the arrows are where you write it down.
The alarm sounds, both John and Mary call, and there is neither a burglary nor an earthquake:
$$ P(j, m, a, \neg b, \neg e) = P(j\mid a)\,P(m\mid a)\,P(a \mid \neg b, \neg e)\,P(\neg b)\,P(\neg e) $$ $$ = 0.90 \times 0.70 \times 0.001 \times 0.999 \times 0.998 \approx 0.000628. $$Every full assignment's probability is a product of exactly one entry from each CPT.
import itertools
# The burglar-alarm network (AIMA Fig 14.2). Each node: (parents, P(node=True | parent values))
NET = {
"Burglary": ((), {(): 0.001}),
"Earthquake": ((), {(): 0.002}),
"Alarm": (("Burglary", "Earthquake"),
{(True, True): 0.95, (True, False): 0.94, (False, True): 0.29, (False, False): 0.001}),
"JohnCalls": (("Alarm",), {(True,): 0.90, (False,): 0.05}),
"MaryCalls": (("Alarm",), {(True,): 0.70, (False,): 0.01}),
}
ORDER = ["Burglary", "Earthquake", "Alarm", "JohnCalls", "MaryCalls"] # parents before children
def p(var, value, assignment):
parents, cpt = NET[var]
pt = cpt[tuple(assignment[q] for q in parents)]
return pt if value else 1 - pt
def joint(assignment):
"""Chain rule for Bayes nets: product of each node's CPT entry given its parents."""
result = 1.0
for var in ORDER:
result *= p(var, assignment[var], assignment)
return result
# P(j, m, a, not b, not e): the alarm went off with no burglar and no earthquake, both call
x = dict(Burglary=False, Earthquake=False, Alarm=True, JohnCalls=True, MaryCalls=True)
print("P(j, m, a, ~b, ~e) = %.6f" % joint(x))
total = sum(joint(dict(zip(ORDER, vals))) for vals in itertools.product([True, False], repeat=5))
print("sum over all 32 worlds =", round(total, 10))
print("numbers needed: full joint =", 2**5 - 1, " Bayes net =", sum(2 ** len(NET[v][0]) for v in ORDER))P(j, m, a, ~b, ~e) = 0.000628
sum over all 32 worlds = 1.0
numbers needed: full joint = 31 Bayes net = 10
Compactness: why this is a big deal
A Boolean node with \(k\) parents needs \(2^k\) numbers, one P(true) per combination of parent values. With \(n\) nodes and at most \(k\) parents each, the network needs at most \(n \cdot 2^k\) numbers instead of \(2^n - 1\).
| \(n\) variables, ≤ \(k=5\) parents | Full joint \(2^n - 1\) | Bayes net ≤ \(n \cdot 2^k\) |
|---|---|---|
| 5 (burglary) | 31 | 10 (actual) |
| 30 | ~1.07 billion | 960 |
| 100 | ~\(10^{30}\) | 3,200 |
Fewer numbers also means less data needed to learn them and less overfitting. That's the bias–variance tradeoff again (§2.3). A sparse network makes strong independence assumptions (some bias) but has far fewer parameters to estimate (much less variance).
Building a network: order matters
The recipe (AIMA §14.2):
- Choose an ordering of the variables, \(X_1, \dots, X_n\).
- For each \(X_i\) in turn, choose as parents a minimal set of earlier variables such that \(P(X_i \mid X_1,\dots,X_{i-1}) = P(X_i \mid \text{Parents}(X_i))\).
- Write the CPT.
Any ordering gives a correct network, but not an equally compact one. Use the causal order (causes before effects: B, E, A, J, M) and you get 10 numbers, all easy to estimate. Use the diagnostic order M, J, A, B, E and you need extra arrows. J depends on M (if Mary called, the alarm probably went off). A depends on both J and M. B depends on A. And E depends on A and B, because once you know the alarm rang, a burglary "explains" it and makes an earthquake less likely. That gives 13 numbers, and they are strange ones like P(e | a, b), which no expert can estimate intuitively. Ordering M, J, E, B, A is even worse: 31 numbers, no savings at all.
Draw arrows from causes to effects. Causal models are usually the sparsest, their CPTs are the most natural to estimate ("how often does an earthquake trigger the alarm?"), and they stay valid when the situation changes. A new alarm model only changes one CPT.
Compact CPTs: noisy-OR
A node with many parents still needs \(2^k\) numbers. When the parents are independent possible causes, the noisy-OR model needs only \(k\). Each cause \(i\) alone fails to trigger the effect with probability \(q_i\), and the failures are independent:
$$ P(\neg \text{effect} \mid \text{causes that are true}) = \prod_{i\, \text{true}} q_i. $$Example: Bolt is late (effect) if it rains (\(q = 0.6\)), if its battery is low (\(q = 0.2\)), or both. Then P(late | rain, low battery) = \(1 - 0.6 \times 0.2 = 0.88\).
Conditional Independence and d-Separation
A Bayes net's arrows encode a lot of independence assumptions. Being able to read independencies off the graph without computing anything is a core exam skill. It is also how you check whether a model makes sense.
Two basic independence properties
- Local Markov property: each node is conditionally independent of its non-descendants, given its parents. (JohnCalls is independent of Burglary and Earthquake given Alarm.)
- Markov blanket: each node is conditionally independent of every other node given its Markov blanket: its parents, its children and its children's other parents.
Why are the children's other parents included? Because of explaining away, the phenomenon described just below.
The three building blocks
Every path through a Bayes net is built from three kinds of three-node connections. Understand these three and you understand d-separation.
| Structure | Picture | A and C independent? | Given B? |
|---|---|---|---|
| Causal chain | A → B → C | No (rain makes slipping likely, slipping makes lateness likely) | Yes: once you know Bolt slipped, rain adds nothing about lateness |
| Common cause (fork) | A ← B → C | No (John's call is evidence for Mary's call) | Yes: given the alarm, John and Mary are independent |
| Common effect (collider / v-structure) | A → B ← C | Yes: burglaries and earthquakes are unrelated | No! Given the alarm, they become dependent |
Chains and forks behave the way you'd expect: observing the middle node blocks the flow of information. Colliders are the opposite: the path is blocked until you observe the middle node (or any of its descendants). Then it opens.
Explaining away
Burglaries and earthquakes are independent: knowing there was an earthquake tells you nothing about burglars. But suppose the alarm went off. Now if you learn there was an earthquake, the earthquake explains the alarm, and a burglary becomes much less likely. The two causes compete to explain the shared effect. The numbers (computed in §7.3):
| Evidence | P(Burglary | evidence) |
|---|---|
| none | 0.001 |
| John and Mary both call | 0.284 |
| John and Mary call and there was an earthquake | 0.003 |
Learning about the earthquake drops the burglary probability by a factor of almost 100. Bolt's own version: Bolt is late (effect). If you learn its battery was low (one cause), the probability that the path was wet (another cause) drops. This is everyday reasoning, and Bayes nets get it automatically.
d-separation: the general rule
A path between X and Y is blocked by evidence set Z if it contains a node N such that either
- N is a chain or fork node (→N→, ←N←, or ←N→) and N is in Z, or
- N is a collider (→N←) and neither N nor any descendant of N is in Z.
X and Y are d-separated given Z if every path between them is blocked. Then \(X \perp Y \mid Z\) is guaranteed for any CPT values.
Here is an algorithm that is easier to apply by hand than checking every path, the ancestral moral graph method:
- Keep only X, Y, Z and their ancestors.
- Moralize: connect ("marry") every pair of parents that share a child, then drop the arrow directions.
- Delete the nodes in Z.
- If X and Y are disconnected, they are d-separated given Z.
Here it is on a bigger Bolt network: Rain and Sprinkler both cause a WetPath, a wet path causes Slips, slips and a low Battery cause Lateness, and lateness causes a Complaint.
# d-separation via the "ancestral moral graph" method
PARENTS = { # a bigger campus network for Bolt
"Rain": [], "Sprinkler": [], "Battery": [],
"WetPath": ["Rain", "Sprinkler"],
"Slip": ["WetPath"],
"Late": ["Slip", "Battery"],
"Complaint": ["Late"],
}
def ancestors(nodes):
result, stack = set(nodes), list(nodes)
while stack:
for par in PARENTS[stack.pop()]:
if par not in result:
result.add(par); stack.append(par)
return result
def d_separated(X, Y, Z):
"""True if every path between X and Y is blocked given evidence Z."""
keep = ancestors(set(X) | set(Y) | set(Z)) # 1. keep only ancestors
edges = {n: set() for n in keep}
for child in keep: # 2. moralize: link each node to its parents
ps = PARENTS[child] # and "marry" co-parents
for a in ps:
edges[a].add(child); edges[child].add(a)
for b in ps:
if a != b: edges[a].add(b)
seen, stack = set(X), list(X) # 3. delete Z, check if X still reaches Y
while stack:
for nb in edges[stack.pop()]:
if nb not in seen and nb not in Z:
if nb in Y: return False
seen.add(nb); stack.append(nb)
return True
tests = [
(["Rain"], ["Sprinkler"], []), # common effect, nothing observed
(["Rain"], ["Sprinkler"], ["WetPath"]), # observe the common effect
(["Rain"], ["Sprinkler"], ["Complaint"]), # observe a DESCENDANT of the common effect
(["Rain"], ["Late"], []), # causal chain
(["Rain"], ["Late"], ["Slip"]), # chain, middle observed
(["Battery"], ["Rain"], []),
(["Battery"], ["Rain"], ["Late"]), # explaining away
]
for X, Y, Z in tests:
verdict = "independent" if d_separated(X, Y, Z) else "DEPENDENT"
print(f"{X[0]:9s} vs {Y[0]:9s} given {str(Z):15s}: {verdict}")Rain vs Sprinkler given [] : independent
Rain vs Sprinkler given ['WetPath'] : DEPENDENT
Rain vs Sprinkler given ['Complaint'] : DEPENDENT
Rain vs Late given [] : DEPENDENT
Rain vs Late given ['Slip'] : independent
Battery vs Rain given [] : independent
Battery vs Rain given ['Late'] : DEPENDENT
Line 3 is the subtle one. Observing a complaint (a descendant of the WetPath collider) opens the path between Rain and Sprinkler: a complaint is evidence that the path was wet, and the two possible causes start competing again. The last line is explaining away across a longer distance. If Bolt is late, learning that it rained makes "low battery" a less necessary explanation.
- List every undirected path between X and Y.
- For each path, label every intermediate node as chain, fork or collider for that path.
- A path is blocked if any chain/fork node is observed, or any collider is unobserved with no observed descendants.
- Independent only if all paths are blocked.
The usual mistake is forgetting that observing a collider's descendant also opens it.
Exact Inference
Inference means computing the posterior distribution of query variables given evidence, \(\mathbf{P}(X \mid \mathbf{e})\). "Given that John and Mary both called, what's the probability of a burglary?" The general recipe from §4.1 still applies: sum the joint over the hidden variables, then normalize. The Bayes net gives us the joint as a product of CPTs, and the cleverness is in how we organize the sums.
Inference by enumeration
Query \(B\), evidence \(j, m\), hidden variables \(E, A\):
$$ \mathbf{P}(B \mid j, m) = \alpha \sum_{e}\sum_{a} \mathbf{P}(B)\, P(e)\, P(a \mid B, e)\, P(j \mid a)\, P(m \mid a). $$Move each factor as far left as it can go, so it sits outside the sums that don't involve it:
$$ \mathbf{P}(B \mid j, m) = \alpha\, \mathbf{P}(B) \sum_{e} P(e) \sum_{a} P(a \mid B, e)\, P(j\mid a)\, P(m\mid a). $$First, \(f(a) = P(j|a)P(m|a)\): for \(a\), \(0.90 \times 0.70 = 0.63\). For \(\neg a\), \(0.05 \times 0.01 = 0.0005\).
For \(B = b\):
- \(e\): \(\sum_a P(a|b,e) f(a) = 0.95(0.63) + 0.05(0.0005) = 0.598525\)
- \(\neg e\): \(0.94(0.63) + 0.06(0.0005) = 0.59223\)
- \(\sum_e P(e)(\cdot) = 0.002(0.598525) + 0.998(0.59223) = 0.592243\)
- Times \(P(b) = 0.001\): 0.000592
For \(B = \neg b\):
- \(e\): \(0.29(0.63) + 0.71(0.0005) = 0.183055\)
- \(\neg e\): \(0.001(0.63) + 0.999(0.0005) = 0.0011295\)
- \(\sum_e\): \(0.002(0.183055) + 0.998(0.0011295) = 0.0014934\)
- Times \(P(\neg b) = 0.999\): 0.001492
Normalize: \(\alpha \langle 0.000592, 0.001492 \rangle = \langle 0.284, 0.716 \rangle\).
So even with both neighbours calling, a burglary is only 28% likely. False alarms (rate 0.001) are far more common than burglaries, and the false-alarm rate is multiplied by 999 non-burglary cases. It's the base-rate effect from §4.2 inside a network.
NET = {
"Burglary": ((), {(): 0.001}),
"Earthquake": ((), {(): 0.002}),
"Alarm": (("Burglary", "Earthquake"),
{(True, True): 0.95, (True, False): 0.94, (False, True): 0.29, (False, False): 0.001}),
"JohnCalls": (("Alarm",), {(True,): 0.90, (False,): 0.05}),
"MaryCalls": (("Alarm",), {(True,): 0.70, (False,): 0.01}),
}
ORDER = ["Burglary", "Earthquake", "Alarm", "JohnCalls", "MaryCalls"]
def p(var, value, e):
parents, cpt = NET[var]
pt = cpt[tuple(e[q] for q in parents)]
return pt if value else 1 - pt
def enumerate_all(variables, e):
"""Sum of products over the remaining variables (AIMA's ENUMERATE-ALL)."""
if not variables:
return 1.0
Y, rest = variables[0], variables[1:]
if Y in e: # evidence or already-fixed variable
return p(Y, e[Y], e) * enumerate_all(rest, e)
return sum(p(Y, y, e) * enumerate_all(rest, {**e, Y: y}) for y in (True, False))
def enumeration_ask(X, e):
dist = {x: enumerate_all(ORDER, {**e, X: x}) for x in (True, False)}
z = sum(dist.values()) # normalize (the alpha)
return {x: v / z for x, v in dist.items()}
print("P(Burglary | j, m) =", {k: round(v, 3) for k, v in enumeration_ask("Burglary", {"JohnCalls": True, "MaryCalls": True}).items()})
print("P(Burglary | j) =", round(enumeration_ask("Burglary", {"JohnCalls": True})[True], 4))
print("P(Burglary | j, m, e) =", round(enumeration_ask("Burglary", {"JohnCalls": True, "MaryCalls": True, "Earthquake": True})[True], 4))
print("P(Earthquake | j, m) =", round(enumeration_ask("Earthquake", {"JohnCalls": True, "MaryCalls": True})[True], 4))
print("P(Alarm) =", round(enumeration_ask("Alarm", {})[True], 5))P(Burglary | j, m) = {True: 0.284, False: 0.716}
P(Burglary | j) = 0.0163
P(Burglary | j, m, e) = 0.0033
P(Earthquake | j, m) = 0.1761
P(Alarm) = 0.00252
Now explore it interactively. Every number is computed exactly by enumerating the 32 worlds.
Things to try:
- Set only JohnCalls = true: P(Burglary) is just 1.6%. John is unreliable, and one call is weak evidence.
- Set Alarm = true and see JohnCalls and MaryCalls update. Then also set JohnCalls = false. MaryCalls doesn't change at all, because J and M are independent given A.
- Set Burglary = true and Earthquake = true and look at Alarm (0.95). Causal reasoning, from causes down to effects, works just like diagnostic reasoning, from effects up to causes.
Complexity of enumeration
Enumeration evaluates a tree of sums of depth \(n\), so it costs \(O(2^n)\) time (but only linear space). It also recomputes the same things repeatedly: the product \(P(j|a)P(m|a)\) was computed separately for every value of \(e\) and \(b\). The fix is the same as in Chapter 5: dynamic programming.
Variable elimination
Variable elimination (VE) evaluates the sum-of-products expression right to left and stores intermediate results as factors: tables indexed by the variables they depend on.
- Make a factor for each CPT, with the evidence variables already fixed: \(f_J(A) = P(j|A)\), \(f_M(A) = P(m|A)\), \(f_A(A,B,E)\), \(f_E(E)\), \(f_B(B)\).
- Eliminate A: multiply all factors mentioning A, then sum A out: $$ f_1(B,E) = \sum_a f_A(a,B,E)\, f_J(a)\, f_M(a). $$ That's a 2×2 table. Its entries are exactly the four sums 0.598525, 0.59223, 0.183055 and 0.0011295 from the hand calculation above.
- Eliminate E: \(f_2(B) = \sum_e f_E(e)\, f_1(B, e)\), giving \(\langle 0.592243, 0.0014934\rangle\).
- Multiply in the remaining factors and normalize: \(\alpha\, f_B(B)\, f_2(B) = \langle 0.284, 0.716\rangle\).
The two operations are the pointwise product of factors (multiply entries that agree on shared variables) and summing out a variable. VE also skips irrelevant work: every variable that is not an ancestor of a query or evidence variable is irrelevant and can be removed. For example, to compute P(J | b), MaryCalls is irrelevant, because \(\sum_m P(m|a) = 1\).
Complexity: it depends on the graph's shape
- Polytrees (singly connected: at most one undirected path between any two nodes, like the burglary net) allow exact inference in time linear in the size of the network.
- Multiply connected networks: exact inference is NP-hard in general (#P-hard, in fact). The cost of VE is exponential in the size of the largest factor created, which depends on the elimination order. Finding the best order is itself NP-hard, so heuristics are used, such as eliminating the variable that creates the smallest factor first.
- Clustering / junction tree algorithms merge nodes into a polytree of "mega-nodes" so that all posteriors can be computed at once.
When exact inference is too expensive, we approximate by sampling. That's the next section.
Approximate Inference by Sampling
When exact inference is too expensive, we can simulate the network many times and count. This is the Monte Carlo idea: if you can generate random worlds from a distribution, frequencies converge to probabilities by the law of large numbers. All the methods here are consistent: the estimates converge to the right answer as the number of samples grows.
We'll use the sprinkler network (AIMA Fig. 14.12): Cloudy influences both Sprinkler (the gardener runs it less on cloudy days) and Rain, and Sprinkler and Rain both make the grass wet.
1. Prior (direct) sampling
Sample each variable in topological order (parents first) from its CPT, using the values already sampled for its parents. Each run produces one complete world, drawn exactly from the joint distribution. Example run: Cloudy ~ P(0.5) gives true. Then Sprinkler ~ P(0.1) gives false, Rain ~ P(0.8) gives true, and WetGrass ~ P(0.90) gives true. One sample: [true, false, true, true].
2. Rejection sampling
To estimate \(P(X \mid e)\): generate prior samples, throw away any that disagree with the evidence, and count among the rest. It's simple and correct, but wasteful. The fraction kept is \(P(e)\), which drops exponentially as evidence accumulates. With evidence probability 0.001, you throw away 99.9% of your work.
3. Likelihood weighting
Don't sample the evidence variables. Fix them to their observed values, and multiply a weight by the likelihood of each fixed value given its parents. Every sample is used, but weighted by how well it explains the evidence:
$$ w = \prod_{E_i \in \text{evidence}} P(e_i \mid \text{parents}(E_i)). $$Estimate: \(P(x \mid e) \approx \frac{\sum_{\text{samples with } x} w}{\sum_{\text{all samples}} w}\).
The weakness: evidence only affects the sampling of its descendants. If the evidence is downstream (an effect) and very unlikely, most samples get tiny weights, and a few dominate the estimate.
4. Gibbs sampling (MCMC)
A completely different idea. Start from any world consistent with the evidence. Then repeatedly pick a non-evidence variable and resample it given all the others. Thanks to the Markov blanket property (§7.2), that only depends on its Markov blanket:
$$ P(x_i \mid \text{everything else}) \;\propto\; P(x_i \mid \text{parents}(X_i)) \prod_{Y_j \in \text{children}(X_i)} P(y_j \mid \text{parents}(Y_j)). $$This is a random walk through the space of worlds, a Markov chain. After a "burn-in" period, the fraction of time it spends in each world equals that world's posterior probability.
Gibbs sampling is a local search (Ch 3) through the space of complete assignments, where moves are random and the walk is designed to visit states in proportion to their probability rather than to maximize anything. Simulated annealing (§3.2) is a close relative. It uses the same "random neighbour + probabilistic acceptance" machinery, plus a temperature that gradually forces the walk toward the maximum.
Compare them
Query: P(Rain | Sprinkler = true, WetGrass = true). The exact answer by enumeration is 0.3204.
import random
# Sprinkler network (AIMA Fig 14.12): Cloudy -> Sprinkler, Cloudy -> Rain, (Sprinkler, Rain) -> WetGrass
ORDER = ["Cloudy", "Sprinkler", "Rain", "WetGrass"]
def p_true(var, s):
if var == "Cloudy": return 0.5
if var == "Sprinkler": return 0.1 if s["Cloudy"] else 0.5
if var == "Rain": return 0.8 if s["Cloudy"] else 0.2
return {(True, True): 0.99, (True, False): 0.90, (False, True): 0.90, (False, False): 0.0}[(s["Sprinkler"], s["Rain"])]
rng = random.Random(0)
def prior_sample():
s = {}
for var in ORDER: # topological order: parents are sampled first
s[var] = rng.random() < p_true(var, s)
return s
def rejection_sampling(query, evidence, n):
kept = [s for s in (prior_sample() for _ in range(n)) if all(s[k] == v for k, v in evidence.items())]
return sum(s[query] for s in kept) / len(kept), len(kept)
def likelihood_weighting(query, evidence, n):
num = den = 0.0
for _ in range(n):
s, w = {}, 1.0
for var in ORDER:
pt = p_true(var, s)
if var in evidence: # don't sample evidence: fix it and weight by its likelihood
s[var] = evidence[var]
w *= pt if evidence[var] else 1 - pt
else:
s[var] = rng.random() < pt
num += w * s[query]; den += w
return num / den
def gibbs(query, evidence, n, burn_in=500):
s = {v: evidence.get(v, rng.random() < 0.5) for v in ORDER}
free = [v for v in ORDER if v not in evidence]
def joint(st):
prob = 1.0
for v in ORDER:
pt = p_true(v, st); prob *= pt if st[v] else 1 - pt
return prob
count = 0
for t in range(n + burn_in):
v = rng.choice(free) # resample one variable given all the others
s[v] = True; p1 = joint(s)
s[v] = False; p0 = joint(s)
s[v] = rng.random() < p1 / (p1 + p0)
if t >= burn_in:
count += s[query]
return count / n
ev = {"Sprinkler": True, "WetGrass": True}
print("exact answer: P(Rain | sprinkler, wetgrass) = 0.3204")
est, kept = rejection_sampling("Rain", ev, 10000)
print("rejection sampling : %.4f (kept %d of 10000 samples)" % (est, kept))
print("likelihood weighting : %.4f" % likelihood_weighting("Rain", ev, 10000))
print("Gibbs sampling : %.4f" % gibbs("Rain", ev, 10000))exact answer: P(Rain | sprinkler, wetgrass) = 0.3204
rejection sampling : 0.3194 (kept 2830 of 10000 samples)
likelihood weighting : 0.3291
Gibbs sampling : 0.3187
All three land within about 0.01 of the truth. Rejection sampling threw away 72% of its samples. (For simplicity, the gibbs function above recomputes the full joint rather than just the Markov blanket. The ratio is the same, because the factors outside the blanket cancel.)
Choose "Cloudy = false, WetGrass = true" with rejection sampling, and watch what fraction of samples survive. Then switch to likelihood weighting and compare how quickly each estimate settles near the green line.
Where do the CPTs come from? Learning from data
So far, the network's numbers have come from an expert. With data, we can learn them. If every variable is observed in every example, the maximum-likelihood estimate of each CPT entry is just a count ratio:
$$ \hat P(X = x \mid \text{parents} = u) = \frac{\#(X = x,\ \text{parents} = u)}{\#(\text{parents} = u)}. $$Each CPT is learned separately: the factorization splits the learning problem into small independent counting problems. With little data, add Laplace smoothing (pseudo-counts) to avoid zero probabilities. That's a prior, i.e. regularization, as in §2.4 and §4.2.
import random
ORDER = ["Cloudy", "Sprinkler", "Rain", "WetGrass"]
def p_true(var, s):
if var == "Cloudy": return 0.5
if var == "Sprinkler": return 0.1 if s["Cloudy"] else 0.5
if var == "Rain": return 0.8 if s["Cloudy"] else 0.2
return {(True, True): 0.99, (True, False): 0.90, (False, True): 0.90, (False, False): 0.0}[(s["Sprinkler"], s["Rain"])]
rng = random.Random(1)
def prior_sample():
s = {}
for var in ORDER:
s[var] = rng.random() < p_true(var, s)
return s
data = [prior_sample() for _ in range(2000)] # pretend this is a log of 2000 observed days
def estimate(var, parent, parent_value, k=1):
"""Maximum-likelihood estimate with add-k (Laplace) smoothing: (count + k) / (total + 2k)."""
rows = [d for d in data if d[parent] == parent_value]
return (sum(d[var] for d in rows) + k) / (len(rows) + 2 * k)
print("P(Rain | Cloudy) true 0.80 learned %.3f" % estimate("Rain", "Cloudy", True))
print("P(Rain | ~Cloudy) true 0.20 learned %.3f" % estimate("Rain", "Cloudy", False))
print("P(Sprinkler | Cloudy) true 0.10 learned %.3f" % estimate("Sprinkler", "Cloudy", True))
print("P(Sprinkler | ~Cloudy) true 0.50 learned %.3f" % estimate("Sprinkler", "Cloudy", False))P(Rain | Cloudy) true 0.80 learned 0.803
P(Rain | ~Cloudy) true 0.20 learned 0.192
P(Sprinkler | Cloudy) true 0.10 learned 0.103
P(Sprinkler | ~Cloudy) true 0.50 learned 0.514
Harder versions of the problem:
- Hidden variables (never observed): use the EM algorithm. Guess the CPTs, infer the hidden variables (E-step), re-estimate by expected counts (M-step), and repeat. It's a local-search method and can get stuck in local optima, just like hill climbing.
- Unknown structure (which arrows?): search over DAGs (hill climbing over add/remove/reverse-edge moves) and score each structure by fit minus a complexity penalty (e.g. BIC). More edges always fit the training data better, so without the penalty you get a fully connected, overfit network. This is the bias–variance tradeoff one final time.
Chapter summary
- A Bayes net = DAG + CPTs. Joint = \(\prod_i P(x_i \mid \text{parents}(X_i))\). This is exponentially more compact than the full joint.
- Build it in causal order for sparse, natural CPTs.
- Chains and forks block when the middle is observed. Colliders block unless the middle or a descendant is observed (explaining away). d-separation generalizes this.
- Exact inference: enumeration (\(O(2^n)\)) and variable elimination (factors, dynamic programming). Linear for polytrees, NP-hard in general.
- Approximate inference: rejection sampling (wasteful), likelihood weighting (weights), Gibbs (MCMC over the Markov blanket).
- Learning CPTs = counting (plus smoothing). Structure learning = search with a complexity penalty.
Look at what Bolt can do now. It learns delivery-time models that generalize (Ch 2). It tunes them by search when gradients aren't available (Ch 3). It reasons about uncertain sensors with Bayes' rule (Ch 4) and Bayes nets (Ch 7). It chooses actions that maximize expected utility (Ch 4–5), plans routes in a slippery world (MDPs), tracks its own location from noisy readings (POMDPs) and explains lateness with readable rules (Ch 6). That is the whole course, and it's also a fair description of a modern autonomous robot. Head to the cheat sheet and study plan to consolidate.
A — Formula Cheat Sheet
Every formula in the book on one page, grouped by chapter. Print it (print icon) and use it for revision. Make sure you can explain each line, not just recite it.
Ch 2 — Generalization
| Data model | \(y = f(x) + \varepsilon,\ \ \mathbb{E}[\varepsilon]=0,\ \operatorname{Var}(\varepsilon)=\sigma^2\) |
| MSE | \(\frac1n\sum_i (h(x_i) - y_i)^2\) |
| Normal equations | \(X^\top X w = X^\top y\) |
| Line fit | \(w_1 = \frac{\sum(x_i-\bar x)(y_i-\bar y)}{\sum (x_i-\bar x)^2},\ \ w_0 = \bar y - w_1\bar x\) |
| Bias–variance | \(\mathbb{E}[(y-\hat g)^2] = (\bar g - f)^2 + \mathbb{E}[(\hat g - \bar g)^2] + \sigma^2\), with \(\bar g = \mathbb{E}_{\mathcal D}[\hat g_{\mathcal D}]\) |
| Ridge | \(\min \lVert Xw-y\rVert^2 + \lambda\lVert w\rVert^2 \Rightarrow (X^\top X + \lambda I)w = X^\top y\) |
| Lasso | \(\min \lVert Xw-y\rVert^2 + \lambda\sum|w_j|\) (sparse) |
| k-fold CV | \(\text{CV} = \frac1k\sum_{i=1}^k \text{Err}_{\text{fold } i}\) |
Complexity ↑ ⇒ bias ↓, variance ↑. More data ⇒ variance ↓. Underfit: both errors high and close. Overfit: low train, high test.
Ch 3 — Local search
| Restarts needed | \(\mathbb{E}[\text{runs}] = 1/p\) |
| SA acceptance (maximize) | \(P(\text{accept}) = e^{\Delta E/T}\) for \(\Delta E < 0\). (Minimizing cost: \(e^{-\Delta C/T}\).) |
| Geometric cooling | \(T_{t+1} = \alpha T_t\) |
| Roulette selection | \(p_i = f_i/\sum_j f_j\), expected copies \(N p_i\) |
| Bit mutation rate | \(p_m \approx 1/L\) |
| 8-queens | \(h\) = attacking pairs. GA fitness = non-attacking pairs, max \(\binom82 = 28\) |
Failure modes: local maxima, plateaus/shoulders, ridges. Mutation explores (restores lost alleles). Crossover exploits (combines building blocks). Too much selection pressure ⇒ premature convergence.
Ch 4 — Probability and utility
| Conditional | \(P(a|b) = P(a,b)/P(b)\) |
| Product / chain rule | \(P(a,b)=P(a|b)P(b)\), \(P(x_1..x_n) = \prod_i P(x_i|x_1..x_{i-1})\) |
| Marginalization | \(P(Y) = \sum_z P(Y, z)\) |
| Inference recipe | \(\mathbf P(X|e) = \alpha\sum_y \mathbf P(X,e,y)\) |
| Bayes' rule | \(P(h|e) = \dfrac{P(e|h)P(h)}{\sum_{h'}P(e|h')P(h')}\) |
| Odds form | posterior odds = \(\frac{P(e|h)}{P(e|\neg h)}\) × prior odds |
| Independence | \(P(a,b)=P(a)P(b)\). Conditional: \(P(a,b|c) = P(a|c)P(b|c)\) |
| Naive Bayes | \(P(C|x) = \alpha P(C)\prod_i P(x_i|C)\). Laplace: \(\frac{n_{v}+1}{n + |V|}\) |
| Expectation | \(\mathbb E[X]=\sum x P(x)\), \(\operatorname{Var}X = \mathbb E[X^2]-\mathbb E[X]^2\) |
| Lottery EU | \(U([p_1,S_1;\dots]) = \sum_i p_i U(S_i)\) |
| MEU | \(a^* = \arg\max_a \sum_{s'}P(s'|a)U(s')\) |
| Certainty equivalent | \(U(CE) = \mathbb{EU}(L)\), risk premium = EMV − CE |
| Affine invariance | \(U' = aU + b,\ a>0\) gives the same decisions |
Axioms: orderability, transitivity, continuity, substitutability, monotonicity, decomposability. Concave U = risk-averse, linear = neutral, convex = seeking.
Ch 5 — Decision theory and MDPs
| VPI | \(\text{VPI}(E) = \sum_e P(e)\max_a \mathbb{EU}(a|e) - \max_a \mathbb{EU}(a)\ \ (\ge 0)\) |
| Discounted return | \(\sum_t \gamma^t R(s_t) \le R_{\max}/(1-\gamma)\) |
| Bellman (optimality) | \(U(s) = R(s) + \gamma\max_a\sum_{s'}P(s'|s,a)U(s')\) |
| Bellman (transition reward) | \(U(s) = \max_a\sum_{s'}P(s'|s,a)[R(s,a,s')+\gamma U(s')]\) |
| Q-value | \(Q(s,a) = R(s)+\gamma\sum_{s'}P(s'|s,a)U(s')\), \(\pi^*(s) = \arg\max_a Q(s,a)\) |
| Policy evaluation | \(U^\pi = R + \gamma P^\pi U^\pi \Rightarrow (I-\gamma P^\pi)U^\pi = R\) |
| Contraction | \(\lVert BU - BU'\rVert_\infty \le \gamma\lVert U-U'\rVert_\infty\). Stop when \(\delta < \varepsilon(1-\gamma)/\gamma\) |
| Primal LP | \(\min \sum_s \alpha_s V(s)\) s.t. \(V(s) \ge r(s,a) + \gamma\sum_{s'}P(s'|s,a)V(s')\) |
| Dual LP | \(\max \sum x(s,a)r(s,a)\) s.t. \(\sum_a x(s',a) - \gamma\sum_{s,a}P(s'|s,a)x(s,a) = \alpha(s')\), \(x\ge0\) |
| Belief update | \(b'(s') = \alpha\, P(o|s')\sum_s P(s'|s,a)b(s)\) |
Ch 6 — Decision trees
| Entropy | \(H(S) = -\sum_k p_k\log_2 p_k\). Binary: \(B(p) = -p\log_2p-(1-p)\log_2(1-p)\) |
| Information gain | \(\text{Gain}(S,A) = H(S) - \sum_v \frac{|S_v|}{|S|}H(S_v)\) |
| Split info / gain ratio | \(\text{SI} = -\sum_v\frac{|S_v|}{|S|}\log_2\frac{|S_v|}{|S|}\), GR = Gain/SI |
| Gini | \(1 - \sum_k p_k^2\) |
| χ² pruning | \(\Delta = \sum_k \frac{(p_k-\hat p_k)^2}{\hat p_k} + \frac{(n_k-\hat n_k)^2}{\hat n_k}\), \(\hat p_k = p\frac{p_k+n_k}{p+n}\) |
| Hypothesis count | \(2^{2^n}\) Boolean functions of \(n\) attributes |
Handy values: B(1/2)=1, B(1/3)=0.918, B(1/4)=0.811, B(2/5)=0.971, B(1/5)=0.722, B(1/7)=0.592, B(3/7)=0.985, B(5/14)=0.940.
Ch 7 — Bayesian networks
| Factorization | \(P(x_1..x_n) = \prod_i P(x_i|\text{parents}(X_i))\) |
| CPT size | Boolean node with \(k\) Boolean parents needs \(2^k\) numbers |
| Noisy-OR | \(P(\neg e|\text{causes}) = \prod_{i\ \text{true}} q_i\) |
| Markov blanket | parents + children + children's other parents |
| Enumeration | \(\mathbf P(X|e) = \alpha\sum_{y}\prod_i P(x_i|\text{pa}_i)\) |
| Likelihood weight | \(w = \prod_{E_i} P(e_i|\text{parents}(E_i))\) |
| Gibbs step | \(P(x_i|\text{mb}) \propto P(x_i|\text{pa}_i)\prod_{\text{children } Y}P(y|\text{pa}_Y)\) |
| CPT learning (MLE) | \(\hat P(x|u) = \#(x,u)/\#(u)\) |
Chain A→B→C and fork A←B→C: blocked if B observed. Collider A→B←C: blocked unless B or a descendant is observed (explaining away).
Classic numbers to recognize
- PlayTennis: H(S) = 0.940. Gains: Outlook 0.247, Humidity 0.152, Wind 0.048, Temp 0.029.
- 4×3 world (\(R=-0.04, \gamma=1\)): start cell \(U = 0.705\). Next to +1: 0.918.
- Burglary: P(B | j, m) = 0.284. P(B | j, m, e) = 0.003 (explaining away). P(j,m,a,¬b,¬e) = 0.000628.
- Disease test (1%, 90%, 9%): P(D|+) ≈ 0.092.
- Sprinkler: P(R | s, w) = 0.320.
B — Python Toolkit for MDL
The assignments are 35% of your grade. This appendix collects the practical knowledge that makes them go smoothly: environment setup, the numpy idioms used throughout this book, and habits that save you from losing a night's work.
Setup
# in a terminal (once):
# python3 -m venv ~/mdl-env && source ~/mdl-env/bin/activate
# pip install numpy scipy matplotlib scikit-learn pandas jupyter
import numpy as np, scipy, matplotlib.pyplot as plt
print(np.__version__, scipy.__version__)numpy idioms you'll use constantly
| Task | Idiom | Used in |
|---|---|---|
| Reproducible randomness | rng = np.random.default_rng(42) | everywhere |
| Polynomial design matrix | np.vander(x, d+1, increasing=True) | §2.1–2.4 |
| Least squares | w, *_ = np.linalg.lstsq(X, y, rcond=None) | §2.1 |
| Solve linear system | np.linalg.solve(A, b) (never inv) | ridge, policy evaluation |
| Mean / variance across datasets | preds.mean(axis=0), preds.var(axis=0) | §2.3 bias–variance |
| Sort by fitness | order = np.argsort(-fitness) | §3.4 GA |
| Random mask | mask = rng.random(n) < p | mutation |
| Normalize a distribution | b = b / b.sum() | Bayes, POMDP |
| Matrix–vector belief predict | b @ T | §5.5 |
| Linear program | scipy.optimize.linprog(c, A_ub, b_ub, A_eq, b_eq, bounds) | §5.4 |
A reusable experiment skeleton
Every assignment benefits from the same structure: config at the top, deterministic seeds, logs to disk, and plots generated from the logs. That way you can always regenerate a figure for your report without re-running a 2-hour experiment.
import json, time
import numpy as np
CONFIG = {"seed": 0, "pop_size": 20, "generations": 5}
rng = np.random.default_rng(CONFIG["seed"])
log = []
def evaluate(w): # stand-in for an expensive or remote evaluation
return float(np.sum((w - 1.0) ** 2))
cache = {}
def cached_evaluate(w):
key = tuple(np.round(w, 10)) # never pay twice for the same query
if key not in cache:
cache[key] = evaluate(w)
return cache[key]
pop = rng.normal(0, 1, (CONFIG["pop_size"], 3))
for gen in range(CONFIG["generations"]):
scores = np.array([cached_evaluate(w) for w in pop])
best = int(scores.argmin())
log.append({"gen": gen, "best": scores[best], "mean": scores.mean(), "best_w": pop[best].tolist()})
parents = pop[np.argsort(scores)[: len(pop) // 2]]
children = parents[rng.integers(0, len(parents), len(pop) - len(parents))] + rng.normal(0, 0.2, (len(pop) - len(parents), 3))
pop = np.vstack([parents, children])
with open("/tmp/run_log.json", "w") as f: # in your project: a results/ folder
json.dump({"config": CONFIG, "log": log}, f, indent=1)
print("gen 0 best %.3f -> gen %d best %.3f, %d unique evaluations"
% (log[0]["best"], len(log) - 1, log[-1]["best"], len(cache)))gen 0 best 0.708 -> gen 4 best 0.567, 60 unique evaluations
Plotting for reports
import json, matplotlib.pyplot as plt
run = json.load(open("/tmp/run_log.json"))
gens = [r["gen"] for r in run["log"]]
plt.plot(gens, [r["best"] for r in run["log"]], label="best")
plt.plot(gens, [r["mean"] for r in run["log"]], label="mean")
plt.xlabel("generation"); plt.ylabel("error"); plt.yscale("log"); plt.legend(); plt.grid(alpha=.3)
plt.title("GA progress") # every plot: title, axis labels with units, legend
plt.savefig("ga_progress.png", dpi=150, bbox_inches="tight")scikit-learn equivalents
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.naive_bayes import CategoricalNB
model = make_pipeline(PolynomialFeatures(5), Ridge(alpha=1e-2)) # §2.4 in one line
scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_squared_error")
tree = DecisionTreeClassifier(criterion="entropy", max_depth=4).fit(X, y) # §6
print(export_text(tree))- Seed everything and write the seed in your report, so your numbers are reproducible.
- Assert your invariants: probabilities sum to 1 (
assert abs(P.sum(axis=1) - 1).max() < 1e-9), shapes match, no NaNs. - Start tiny. Test value iteration on a 2-state MDP you can solve by hand before running the 600-state one.
- Vectorize after it works. Correct loops first, fast numpy second.
- Explain, don't just report. Every table or plot in your report should be followed by one paragraph saying what it shows and why, using this book's vocabulary (bias, variance, exploration, explaining away...).
- Follow the output format exactly if the assignment specifies one (JSON keys, trace files). Autograders are unforgiving.
C — Study Plan and Exam Strategy
You said you want to understand these ideas deeply, and not just pass. The plan below is built for that, and it happens to be the best way to score well too. It assumes a roughly 15-week semester and lines up with the usual order of the syllabus.
Before the semester (2–3 weeks, about 1 hour a day)
- Read Chapters 1–2 of this book fully and run every code block yourself. Change the seeds, degrees and noise levels and predict what will happen before you run.
- Revise probability basics (§4.1). If conditional probability or expectation feels shaky, fix that now, because Chapters 4, 5 and 7 build on it.
- Get comfortable with numpy (Appendix B). Most of the course's coding difficulty is numpy fluency.
During the semester
| Weeks | Lectures (likely) | Read here | Do |
|---|---|---|---|
| 1–2 | Overview of AI/ML, data and generalization | Ch 1, §2.1–2.2 | Fit polynomials by hand and in code. Play with the degree slider until the U-curve feels obvious. |
| 3–4 | Bias–variance, overfitting | §2.3–2.4 | Derive the decomposition from memory twice. Start Assignment 1 early. |
| 5–6 | Local search, GA | Ch 3 | Hand-simulate one GA generation (selection, crossover, mutation). Run the §3.4 lab and the exercises. |
| 7 | Probability, utility | Ch 4 | Ten Bayes'-rule problems. Five EU / CE / risk-premium problems. |
| 8 | Mid exam | Appendix A (Ch 1–4) | Past papers, timed. |
| 9–11 | Decision theory, MDPs, POMDPs | Ch 5 | Three value-iteration sweeps by hand. Implement VI, PI and the LP. Do belief updates by hand. |
| 12–13 | Decision trees | Ch 6 | Build the PlayTennis tree from scratch on paper, in under 25 minutes. |
| 14–15 | Bayesian networks | Ch 7 | d-separation drills. Enumeration by hand. Run the sampling widget. |
| Finals | Everything | Appendix A, all quizzes | Retake every quiz until you score 100%. Redo every "Exam corner" box. |
How to study each chapter (the 4-pass method)
- Skim: read the chapter intro and every "Key idea" and "Connections" box. 10 minutes.
- Read and play: read fully, and spend real time on every widget. Predict, then check.
- Reproduce: close the book and re-derive the main result (bias–variance, Bellman, information gain, belief update) on paper. Where you get stuck is where you don't understand yet.
- Test: take the quiz. A wrong answer means re-reading that section, not just memorizing the answer.
The hand-computation drills that come up most
| Skill | Where to practise | Target time |
|---|---|---|
| Bias², variance from a table of predictions | §2.3 quiz | 3 min |
| Diagnose under/overfitting from error numbers | §2.2 exam corner | 1 min |
| Hill-climbing step / SA acceptance probability | §3.1–3.2 | 3 min |
| Roulette probabilities + crossover + mutation | §3.3 \(x^2\) example | 5 min |
| Bayes' rule posterior (with the 1000-people picture) | §4.2 | 3 min |
| Marginal / conditional from a joint table | §4.1 | 3 min |
| EU, CE, risk premium | §4.3 | 3 min |
| Value of information | §5.1 worked example | 8 min |
| 2–3 value-iteration sweeps | §5.3 table | 10 min |
| One policy-iteration round on a tiny MDP | §5.3 | 8 min |
| Write the primal/dual LP for a small MDP | §5.4 | 8 min |
| POMDP belief update | §5.5 exam corner | 4 min |
| Entropy, information gain, full ID3 tree | §6.2–6.3 | 20 min |
| Threshold for a continuous attribute | §6.4 | 5 min |
| Joint probability of a full assignment in a Bayes net | §7.1 | 2 min |
| d-separation | §7.2 checklist | 3 min |
| Inference by enumeration | §7.3 worked example | 12 min |
Exam-day strategy
- Write the formula first, then substitute. Partial credit lives in the setup. "Gain = H(S) − Σ..." earns marks even if you slip on arithmetic.
- Keep 3–4 decimals in intermediate steps. Rounding early in value iteration or IG computations compounds.
- Sanity-check every answer. Probabilities are in [0, 1]. Entropy of a binary variable is in [0, 1]. Information gain ≤ parent entropy. A posterior should move toward what the evidence suggests. A VPI is ≥ 0.
- State your conventions when there's ambiguity: reward on states or transitions, tie-breaking in ID3, maximizing vs minimizing in SA.
- Explain in words for "why" questions, using the vocabulary: bias, variance, exploration, exploitation, Markov property, explaining away, inductive bias.
Going beyond the course
If this material excites you, here is where it leads:
- Reinforcement learning: MDPs without a known model. Sutton & Barto's Reinforcement Learning: An Introduction (free online) starts exactly where Chapter 5 ends. Q-learning is the next step.
- Probabilistic graphical models: Koller & Friedman. Chapter 7 is the first 10% of this field.
- Statistical learning theory: why generalization works (VC dimension, PAC learning). Understanding Machine Learning by Shalev-Shwartz & Ben-David.
- Practical ML: scikit-learn's user guide, and Kaggle tabular competitions, where the gradient-boosted trees of §6.4 rule.
- Evolutionary computation: CMA-ES (the state-of-the-art successor to the real-valued GA of §3.4) and neuroevolution.
Every chapter in this book answered the same question from a different angle: how do you act well when you can't be sure? You fit patterns without fitting noise. You search without getting stuck. You believe in proportion to evidence. You weigh outcomes by how much they matter. You plan for slips, and you keep track of what you don't know. Those are good habits for an AI system, and for an engineer. Good luck next semester.