ch06_ope.py
Companion code for Off-policy evaluation as importance sampling. Needs only Python 3 and NumPy: python code/ch06_ope.py.
"""Chapter 6: off-policy evaluation (RL, Read as Statistics).
Estimate the value of a target policy pi from trajectories collected by a
behaviour policy b, on a small finite-horizon MDP, for horizons H = 1..20.
Estimators: ordinary importance sampling (IS), weighted IS (WIS),
per-decision IS (PDIS), a direct method (DM, the imperfect model alone) and
doubly robust (DR, Jiang & Li 2016) built on that same imperfect model.
Reports bias, standard deviation, RMSE and effective sample size over many
independent datasets, plus the hand example of the chapter.
gamma = 1; the return is the sum of the first H rewards. NumPy only.
Run: python code/ch06_ope.py
"""
import numpy as np
rng = np.random.default_rng(6)
NS, NA = 3, 2 # states {0,1,2}, actions {0,1}
HMAX = 20
B = np.full((NS, NA), 0.5) # behaviour policy b(a|s): uniform
PI = np.full((NS, NA), 0.0) # target policy pi(a|s): action 1 w.p. 0.8
PI[:, 1], PI[:, 0] = 0.8, 0.2
def make_env():
"""P[s, a, s'] and mean reward r[s, a] (rewards are Bernoulli)."""
P = np.zeros((NS, NA, NS))
for s in range(NS):
for a in range(NA):
up, down = (0.7, 0.3) if a == 1 else (0.3, 0.7)
P[s, a, min(s + 1, NS - 1)] += up
P[s, a, max(s - 1, 0)] += down
r = np.array([[0.2 + 0.2 * s + 0.2 * a for a in range(NA)] for s in range(NS)])
return P, r
P_TRUE, R_TRUE = make_env()
def q_tables(P, r, pi, H):
"""Finite-horizon DP. Q[h][s, a] = value with h steps left (h = 1..H),
V[h][s] = sum_a pi(a|s) Q[h][s, a], V[0] = 0."""
V = [np.zeros(NS)]
Q = [None]
for h in range(1, H + 1):
q = r + np.einsum("sat,t->sa", P, V[-1])
Q.append(q)
V.append((pi * q).sum(1))
return Q, V
# Ground truth, and an imperfect model: reward means shifted by a fixed
# amount, transitions blurred toward uniform. The model is fixed in advance
# (independent of the data), which is what keeps DR unbiased.
Q_T, V_T = q_tables(P_TRUE, R_TRUE, PI, HMAX)
TRUTH = np.array([V_T[H].mean() for H in range(HMAX + 1)]) # uniform start
R_HAT = R_TRUE + np.array([[0.15, -0.10], [-0.15, 0.10], [0.15, -0.10]])
P_HAT = 0.6 * P_TRUE + 0.4 / NS
Q_M, V_M = q_tables(P_HAT, R_HAT, PI, HMAX)
DM = np.array([V_M[H].mean() for H in range(HMAX + 1)])
def sample_datasets(D, n):
"""D datasets of n trajectories of length HMAX under b.
Returns states, actions, rewards, each of shape (D, n, HMAX)."""
S = np.zeros((D, n, HMAX), int)
A = np.zeros_like(S)
R = np.zeros((D, n, HMAX))
s = rng.integers(0, NS, (D, n))
cum_b = np.cumsum(B, axis=1)
for t in range(HMAX):
u = rng.random((D, n))
a = (u[..., None] > cum_b[s]).sum(-1)
r = (rng.random((D, n)) < R_TRUE[s, a]).astype(float)
S[:, :, t], A[:, :, t], R[:, :, t] = s, a, r
p = P_TRUE[s, a] # (D, n, NS)
s = (rng.random((D, n))[..., None] > np.cumsum(p, -1)).sum(-1)
return S, A, R
def estimate_all(S, A, R):
"""All estimators for every H = 1..HMAX. Returns dict name -> (D, HMAX)
and the effective sample size of the IS weights, shape (D, HMAX)."""
rho = PI[S, A] / B[S, A] # per-step ratios
w = np.cumprod(rho, axis=2) # w_{1:t}
w_prev = np.concatenate([np.ones_like(w[..., :1]), w[..., :-1]], axis=2)
cumR = np.cumsum(R, axis=2) # G^{(H)}
pd_terms = np.cumsum(w * R, axis=2) # sum_t w_{1:t} r_t
out = {k: [] for k in ("IS", "WIS", "PDIS", "DR")}
ess = []
for H in range(1, HMAX + 1):
wH, G = w[:, :, H - 1], cumR[:, :, H - 1]
out["IS"].append((wH * G).mean(1))
out["WIS"].append((wH * G).sum(1) / wH.sum(1))
out["PDIS"].append(pd_terms[:, :, H - 1].mean(1))
ess.append(wH.sum(1) ** 2 / (wH ** 2).sum(1))
# DR: sum_t [ w_{1:t} r_t - w_{1:t} Qhat_{H-t+1}(s_t,a_t)
# + w_{1:t-1} Vhat_{H-t+1}(s_t) ]
total = np.zeros(S.shape[:2])
for t in range(H):
h = H - t
qh, vh = Q_M[h][S[:, :, t], A[:, :, t]], V_M[h][S[:, :, t]]
total += w[:, :, t] * (R[:, :, t] - qh) + w_prev[:, :, t] * vh
out["DR"].append(total.mean(1))
return {k: np.stack(v, 1) for k, v in out.items()}, np.stack(ess, 1)
def hand_example():
"""One state, two actions, five logged samples (a, r)."""
b = np.array([0.5, 0.5])
pi = np.array([0.8, 0.2])
data = [(0, 1), (0, 1), (0, 0), (1, 1), (1, 0)]
a = np.array([d[0] for d in data])
r = np.array([d[1] for d in data], float)
rho = pi[a] / b[a]
qhat = np.array([0.5, 0.5])
vhat = pi @ qhat
print("Hand example: b = (0.5, 0.5), pi = (0.8, 0.2), 5 samples")
print(" ratios rho :", rho)
print(" IS : %.4f" % (rho * r).mean())
print(" WIS : %.4f" % ((rho * r).sum() / rho.sum()))
print(" DR (qhat=0.5,0.5): %.4f" % (vhat + (rho * (r - qhat[a])).mean()))
print(" ESS : %.4f" % (rho.sum() ** 2 / (rho ** 2).sum()))
print(" E_b[rho^2] : %.4f" % (b @ (pi / b) ** 2))
print()
if __name__ == "__main__":
hand_example()
D, n = 400, 500
S, A, R = sample_datasets(D, n)
est, ess = estimate_all(S, A, R)
est["DM"] = np.tile(DM[1:], (D, 1)) # no randomness
rho2 = (PI ** 2 / B).sum(1).mean() # E_b[rho^2], same for all s
print("Setup: 3-state MDP, 2 actions, b uniform, pi plays action 1 w.p. 0.8")
print(" %d datasets x %d trajectories; per-step E_b[rho^2] = %.3f" % (D, n, rho2))
print()
Hs = [1, 2, 3, 5, 8, 10, 15, 20]
names = ["IS", "WIS", "PDIS", "DM", "DR"]
for title, fn in [("Bias", lambda e, tr: e.mean(0) - tr),
("Std dev", lambda e, tr: e.std(0)),
("RMSE", lambda e, tr: np.sqrt(((e - tr) ** 2).mean(0)))]:
print(title)
print(" %-3s %9s" % ("H", "truth") + "".join("%9s" % k for k in names))
for H in Hs:
tr = TRUTH[H]
print(" %-3d %9.4f" % (H, tr) + "".join(
"%9.4f" % fn(est[k][:, H - 1], tr) for k in names))
print()
print("Monte Carlo standard error of each Bias entry = Std dev / sqrt(%d)" % D)
print()
print("Effective sample size of the IS weights (n = %d)" % n)
print(" %-3s %10s %10s %12s %12s" % (
"H", "mean ESS", "n/E[w^2]", "Var(w) thy", "Var(w) obs"))
rho = PI[S, A] / B[S, A]
w = np.cumprod(rho, axis=2)
for H in Hs:
print(" %-3d %10.1f %10.1f %12.2f %12.2f" % (
H, ess[:, H - 1].mean(), n / rho2 ** H, rho2 ** H - 1,
w[:, :, H - 1].var()))