ch01_returns.py
Companion code for Returns are random variables. Needs only Python 3 and NumPy: python code/ch01_returns.py.
"""Chapter 1: returns are random variables.
Demonstrates, on a small slippery corridor MDP:
* the return G_0 from a fixed state is a random variable with a skewed,
multi-modal distribution (text histogram);
* its mean is v_pi(s), which we also get exactly by solving the linear
Bellman system; its variance matches the variance Bellman equation (Sobel 1982);
* how gamma changes the distribution;
* the Bellman equation as the law of total expectation (v = sum_a pi q);
* a 95% t-interval built from n sampled returns covers v_pi at about 95%;
* the policy changes the data-generating distribution.
Run: python code/ch01_returns.py (NumPy only, a few seconds)
"""
import numpy as np
rng = np.random.default_rng(1)
# ---- The MDP ---------------------------------------------------------------
# States 0..5 on a line. 0 and 5 are terminal (absorbing, no further reward).
# Actions: 0 = "left", 1 = "right". The chosen move happens with prob 0.8;
# otherwise the agent slips and moves the opposite way.
# Reward for a transition into s': -1 per step, +10 for landing on 5,
# -5 extra for landing on 0 (a pit).
N_STATES, TERMINAL = 6, (0, 5)
SLIP = 0.2
START = 2
def reward(s_next):
return -1.0 + 10.0 * (s_next == 5) - 5.0 * (s_next == 0)
def policy_matrix(p_right):
"""pi[s, a]: probability of action a in state s (same in every state)."""
return np.tile([1.0 - p_right, p_right], (N_STATES, 1))
def dynamics(pi):
"""Return P[s, s'] under pi and the expected one-step reward rbar[s],
plus the action-level pieces needed for q: P_a[a][s, s'].
"""
P_a = np.zeros((2, N_STATES, N_STATES))
for s in range(1, N_STATES - 1):
P_a[1, s, s + 1] += 1 - SLIP
P_a[1, s, s - 1] += SLIP
P_a[0, s, s - 1] += 1 - SLIP
P_a[0, s, s + 1] += SLIP
# Terminal states: absorbing, and handled by zero value.
P = np.einsum("sa,ast->st", pi, P_a)
r = reward(np.arange(N_STATES)) # reward by landing state
for t in TERMINAL:
P[t, :] = 0.0 # no transitions out of terminals (value fixed at 0)
P_a[:, t, :] = 0.0
return P, P_a, r
def exact_values(pi, gamma):
"""Solve v = rbar + gamma P v, and the second moment for the variance."""
P, P_a, r = dynamics(pi)
rbar = P @ r # E[R_{t+1} | S_t = s]
I = np.eye(N_STATES)
v = np.linalg.solve(I - gamma * P, rbar) # Bellman expectation equation
# Variance Bellman equation: with m2(s) = E[G^2 | s],
# m2 = c + gamma^2 P m2, c(s) = sum_s' P[s,s'] (r(s')^2 + 2 gamma r(s') v(s'))
c = P @ (r ** 2) + 2 * gamma * (P * r[None, :]) @ v
m2 = np.linalg.solve(I - gamma ** 2 * P, c)
var = m2 - v ** 2
# q(s, a) = sum_s' P_a[a][s,s'] (r(s') + gamma v(s'))
q = np.stack([P_a[a] @ (r * 1.0) + gamma * P_a[a] @ v for a in range(2)], axis=1)
return v, var, q
# ---- Sampling returns ------------------------------------------------------
def sample_returns(pi, gamma, s0, n, rng):
"""Simulate n independent episodes from s0.
Returns the n discounted returns G_0 and the n terminal states reached."""
s = np.full(n, s0)
G = np.zeros(n)
disc = 1.0
alive = np.ones(n, dtype=bool)
p_right = pi[:, 1]
while alive.any():
right = rng.random(n) < p_right[s] # action ~ pi(. | s)
slip = rng.random(n) < SLIP # environment noise
move = np.where(right ^ slip, 1, -1) # right and no slip, or left and slip
s_next = np.where(alive, s + move, s)
G += np.where(alive, disc * reward(s_next), 0.0)
disc *= gamma
alive = alive & ~np.isin(s_next, TERMINAL)
s = s_next
return G, s
def skewness(x):
z = (x - x.mean()) / x.std()
return float((z ** 3).mean())
def text_hist(x, bins=14, width=46):
counts, edges = np.histogram(x, bins=bins)
top = counts.max()
for c, lo, hi in zip(counts, edges[:-1], edges[1:]):
print(f" [{lo:6.2f}, {hi:6.2f}) {c / len(x):6.3f} " + "#" * int(round(width * c / top)))
# ---- Experiments -----------------------------------------------------------
pi = policy_matrix(0.6)
N = 200_000
print("MDP: corridor of 6 states (0 and 5 terminal), start state 2, slip prob 0.2")
print("Policy pi: right with prob 0.6, left with prob 0.4, in every state\n")
print("1. Return from state 2: Monte Carlo vs exact (N = 200000 episodes)")
print(f"{'gamma':>6} {'v exact':>9} {'MC mean':>9} {'MC se':>7} {'sd exact':>9} {'MC sd':>7} {'skew':>7}")
for gamma in (0.99, 0.9, 0.5):
v, var, _ = exact_values(pi, gamma)
G, _ = sample_returns(pi, gamma, START, N, rng)
print(f"{gamma:6.2f} {v[START]:9.4f} {G.mean():9.4f} {G.std(ddof=1) / np.sqrt(N):7.4f} "
f"{np.sqrt(var[START]):9.4f} {G.std(ddof=1):7.4f} {skewness(G):7.3f}")
gamma = 0.9
v, var, q = exact_values(pi, gamma)
G, _ = sample_returns(pi, gamma, START, N, rng)
print(f"\n2. Empirical distribution of G_0 from state 2, gamma = {gamma} (proportion of episodes)")
text_hist(G)
print(f" mean {G.mean():.3f} (v_pi = {v[START]:.3f}), median {np.median(G):.3f}")
print("\n3. Exact v_pi and sd of the return by start state (gamma = 0.9)")
print(f"{'state':>6} {'v_pi':>8} {'sd(G)':>8}")
for s in range(1, 5):
print(f"{s:6d} {v[s]:8.4f} {np.sqrt(var[s]):8.4f}")
print("\n4. Bellman expectation equation as the law of total expectation, state 2")
print(f" q(2,left) = {q[2, 0]:.4f} q(2,right) = {q[2, 1]:.4f}")
print(f" sum_a pi(a|2) q(2,a) = {0.4 * q[2, 0] + 0.6 * q[2, 1]:.4f} v_pi(2) = {v[2]:.4f}")
P, _, r = dynamics(pi)
rbar = P @ r
print(f" rbar(2) + gamma * sum_s' P(s'|2) v(s') = {rbar[2] + gamma * P[2] @ v:.4f}")
# Law of total variance at the first step, using the sampled start state 2:
# Var(G) = E[Var(G | S_1)] + Var(E[G | S_1]) with G = R_1 + gamma G_1 .
Ev_cond = P[2] * (r + gamma * v) # contribution of each next state
mean_all = Ev_cond.sum()
within = (P[2] * gamma ** 2 * var).sum()
between = (P[2] * (r + gamma * v - mean_all) ** 2).sum()
print(f" Var(G_0) = within {within:.4f} + between {between:.4f} = {within + between:.4f}"
f" (exact {var[2]:.4f})")
print("\n5. Coverage of a 95% t-interval for v_pi(2) from n sampled returns (2000 repetitions)")
print(f"{'n':>6} {'coverage':>9} {'mean width':>11}")
for n in (10, 30, 200):
reps = 2000
Gs = sample_returns(pi, gamma, START, n * reps, rng)[0].reshape(reps, n)
m, sd = Gs.mean(1), Gs.std(1, ddof=1)
tcrit = {10: 2.262, 30: 2.045, 200: 1.972}[n] # t_{0.975, n-1}
half = tcrit * sd / np.sqrt(n)
cover = ((m - half <= v[START]) & (v[START] <= m + half)).mean()
print(f"{n:6d} {cover:9.3f} {2 * half.mean():11.3f}")
print("\n6. The data distribution depends on the policy (gamma = 0.9, start state 2)")
print(f"{'P(right)':>9} {'v_pi(2)':>9} {'sd(G)':>8} {'P(reach 5)':>11}")
for p in (0.1, 0.4, 0.6, 0.9):
pp = policy_matrix(p)
vv, vr, _ = exact_values(pp, gamma)
_, end = sample_returns(pp, gamma, START, 50_000, rng)
reach = (end == 5).mean()
print(f"{p:9.1f} {vv[START]:9.4f} {np.sqrt(vr[START]):8.4f} {reach:11.3f}")