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))Habits that save marks
- 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.