ch04_monte_carlo.py
Companion code for Monte Carlo evaluation is a sample mean. Needs only Python 3 and NumPy: python code/ch04_monte_carlo.py.
"""Chapter 4 companion: Monte Carlo policy evaluation as a sample mean.
Demonstrates (see content/chapters/04-monte-carlo-evaluation.md):
0. A one-state toy where every-visit Monte Carlo has a bias you can compute
by hand (E = 1.5 against v = 2 with one episode).
1. On a small episodic Markov reward process with v solved exactly:
bias, standard deviation and RMSE of first-visit, every-visit and
constant-step-size estimators of v(0), by number of episodes n.
2. Empirical coverage of nominal 95% intervals: first-visit (CLT),
every-visit treating visits as iid (wrong), every-visit with an
episode-level (cluster) standard error.
3. The constant step size as an exponentially weighted average: effective
sample size (2 - alpha) / alpha, and tracking a target that jumps.
Discount is gamma = 1 (episodic task), which lets us compute every-visit
returns without storing trajectories. NumPy only.
Run: python code/ch04_monte_carlo.py
"""
import numpy as np
rng = np.random.default_rng(4)
# ----------------------------------------------------------- the toy (exp 0)
# One state; each step pays reward 1 and the episode ends w.p. 1/2.
# Length L ~ Geometric(1/2) on {1, 2, ...}, E[L] = 2 = v. Return from the
# k-th visit is L - k + 1.
print("Experiment 0: one-state toy, v = 2 (episode length L ~ Geometric(1/2))")
print(f"{'n':>5s} {'first-visit mean':>17s} {'every-visit mean':>17s}")
for n in (1, 2, 5, 20, 100):
L = rng.geometric(0.5, size=(200000, n)).astype(float)
fv = L.mean(axis=1) # mean of L_i
ev = (L * (L + 1) / 2).sum(axis=1) / L.sum(axis=1) # sum of returns / number of visits
print(f"{n:5d} {fv.mean():17.3f} {ev.mean():17.3f}")
# ----------------------------------------------- the MRP: two states + stop
# States 0 and 1, terminal state 2. P[s] = transition probs to (0, 1, stop).
# Reward on the transition s -> s' is N(RM[s, s'], 1).
P = np.array([[0.60, 0.30, 0.10],
[0.50, 0.30, 0.20]])
RM = np.array([[1.0, 0.0, 5.0],
[2.0, 0.5, -1.0]])
rbar = (P * RM).sum(axis=1) # expected one-step reward
v = np.linalg.solve(np.eye(2) - P[:, :2], rbar) # v = rbar + P v (exact)
V0 = v[0]
print()
print(f"MRP: P = {P.tolist()} mean rewards = {RM.tolist()}, reward sd = 1, gamma = 1")
print(f"Exact values from solving (I - P) v = rbar: v(0) = {v[0]:.4f}, v(1) = {v[1]:.4f}")
def simulate_episodes(E):
"""Simulate E episodes from state 0. Returns per-episode:
G0 (return from t=0, the first-visit return), cnt (visits to state 0),
ev (sum of returns over all visits to 0), ev2 (sum of squared returns).
With gamma = 1 the return from a visit = G_total - (reward before it)."""
s = np.zeros(E, dtype=int)
cum = np.zeros(E)
cnt = np.zeros(E)
sc = np.zeros(E)
sc2 = np.zeros(E)
active = np.arange(E)
while active.size:
st = s[active]
at0 = st == 0
a0 = active[at0]
cnt[a0] += 1
sc[a0] += cum[a0]
sc2[a0] += cum[a0] ** 2
u = rng.random(active.size)
nxt = (u[:, None] > np.cumsum(P[st], axis=1)).sum(axis=1) # 0, 1 or 2 (stop)
nxt = np.minimum(nxt, 2)
cum[active] += RM[st, nxt] + rng.standard_normal(active.size)
s[active] = nxt
active = active[nxt != 2]
G = cum
ev = cnt * G - sc
ev2 = cnt * G**2 - 2 * G * sc + sc2
return G, cnt, ev, ev2
REPS, NMAX = 3000, 200
G, cnt, ev, ev2 = (a.reshape(REPS, NMAX) for a in simulate_episodes(REPS * NMAX))
sigma2 = G.var() # variance of one first-visit return G_0
print(f"sd of one first-visit return G_0 = {np.sqrt(sigma2):.3f}; mean visits to state 0 per episode = {cnt.mean():.3f}")
NS = (1, 2, 5, 10, 20, 50, 100, 200)
ALPHAS = (0.1, 0.02)
def const_alpha_paths(alpha, V_init=0.0):
"""V <- V + alpha (G - V) over episodes, updating on the first-visit return."""
Vt = np.full(REPS, V_init)
out = {}
for k in range(NMAX):
Vt = Vt + alpha * (G[:, k] - Vt)
if (k + 1) in NS:
out[k + 1] = Vt.copy()
return out
est = {"first-visit": {}, "every-visit": {}}
for a in ALPHAS:
est[f"alpha={a}"] = const_alpha_paths(a)
for n in NS:
est["first-visit"][n] = G[:, :n].mean(axis=1)
est["every-visit"][n] = ev[:, :n].sum(axis=1) / cnt[:, :n].sum(axis=1)
names = list(est)
def table(title, fn):
print()
print(title)
print(f"{'n':>5s}" + "".join(f"{nm:>16s}" for nm in names))
for n in NS:
print(f"{n:5d}" + "".join(f"{fn(est[nm][n]):>16s}" for nm in names))
print()
print(f"Experiment 1: estimators of v(0) = {V0:.4f}, {REPS} replications per n (alpha methods start at V = 0)")
table("Bias, mean(estimate) - v(0) (Monte Carlo se in parentheses)",
lambda x: f"{x.mean() - V0:+.3f} ({x.std(ddof=1) / np.sqrt(REPS):.3f})")
table("Standard deviation of the estimate", lambda x: f"{x.std(ddof=1):.3f}")
table("RMSE = sqrt(bias^2 + variance)", lambda x: f"{np.sqrt(((x - V0) ** 2).mean()):.3f}")
# ---------------------------------------------------------- coverage (exp 2)
print()
print("Experiment 2: coverage of nominal 95% intervals (z = 1.96), 3000 replications per n")
print(f"{'n':>5s}{'first-visit CLT':>18s}{'every-visit iid':>18s}{'every-visit cluster':>21s}")
for n in NS:
if n == 1:
continue
g = G[:, :n]
fv = g.mean(axis=1)
se_fv = g.std(axis=1, ddof=1) / np.sqrt(n)
cov_fv = np.mean(np.abs(fv - V0) <= 1.96 * se_fv)
Y, M = ev[:, :n].sum(axis=1), cnt[:, :n].sum(axis=1)
Y2 = ev2[:, :n].sum(axis=1)
e_v = Y / M
# naive: treat the M visit-returns as iid draws
var_visit = (Y2 - M * e_v**2) / (M - 1)
cov_naive = np.mean(np.abs(e_v - V0) <= 1.96 * np.sqrt(var_visit / M))
# cluster: episodes are the iid units; ratio estimator Y / M, linearised
resid = ev[:, :n] - e_v[:, None] * cnt[:, :n]
se_cl = np.sqrt((resid**2).sum(axis=1) * n / (n - 1)) / M
cov_cl = np.mean(np.abs(e_v - V0) <= 1.96 * se_cl)
print(f"{n:5d}{cov_fv:18.3f}{cov_naive:18.3f}{cov_cl:21.3f}")
print("(Monte Carlo se of a coverage figure near 0.95 is about 0.004)")
# ------------------------------------- constant alpha as an EWMA (exp 3)
print()
print("Experiment 3a: effective sample size of constant alpha, started at V = v(0), n = 200")
print(f"{'alpha':>7s}{'(2-a)/a':>10s}{'sigma^2/Var(V)':>16s}")
for a in (0.2, 0.1, 0.05, 0.02):
Vt = np.full(REPS, V0)
for k in range(NMAX):
Vt = Vt + a * (G[:, k] - Vt)
print(f"{a:7.2f}{(2 - a) / a:10.1f}{sigma2 / Vt.var(ddof=1):16.1f}")
print()
print("Experiment 3b: tracking a target that jumps by +3 after episode 100")
print("returns ~ N(mu_k, sigma^2) with sigma = sd of G_0 above; mean squared error of each estimate")
sig = np.sqrt(sigma2)
R3 = 4000
mu_k = np.where(np.arange(300) < 100, 0.0, 3.0)
Z = mu_k + sig * rng.standard_normal((R3, 300))
checkpoints = (50, 100, 110, 130, 200, 300)
paths = {"sample mean": np.cumsum(Z, axis=1) / np.arange(1, 301)}
for a in (0.1, 0.02):
Vt = np.zeros((R3, 300))
cur = np.zeros(R3)
for k in range(300):
cur = cur + a * (Z[:, k] - cur) if k else Z[:, 0].copy()
Vt[:, k] = cur
paths[f"alpha={a}"] = Vt
print(f"{'episode':>8s}" + "".join(f"{nm:>14s}" for nm in paths))
for k in checkpoints:
print(f"{k:8d}" + "".join(f"{((p[:, k - 1] - mu_k[k - 1]) ** 2).mean():14.2f}" for p in paths.values()))