RLS RL, Read as Statistics

ch11_evaluation.py

Companion code for Evaluating RL honestly. Needs only Python 3 and NumPy: python code/ch11_evaluation.py.

NumPy
"""Chapter 11 companion: evaluating RL honestly when the unit of replication is a run.

Simulates final scores of RL runs (one number per seed) from a skewed,
bimodal distribution: most runs succeed with a lognormal score, some "fail"
and land near zero. Four experiments:

  (a) how often n seeds rank two slightly different algorithms correctly,
      using the mean and using the interquartile mean (IQM);
  (b) false-positive rate and power of Welch's t-test as n grows;
  (c) coverage of a t-interval for the mean vs a percentile-bootstrap
      interval for the IQM (each against its own population target);
  (d) optimism of "best of 5 hyperparameter configs on the same seeds",
      measured against fresh seeds.

NumPy only. The Student-t CDF is computed from the regularised incomplete
beta function (continued fraction), so the Welch p-values are exact for the
t approximation (Welch-Satterthwaite degrees of freedom), not normal ones.
Run: python code/ch11_evaluation.py   (about 30-50 seconds)
"""
import math
import numpy as np

rng = np.random.default_rng(11)

# ---------------------------------------------------------------- run scores
def run_scores(p_fail, n, size=None):
    """n final scores. Fail (prob p_fail): Uniform(0, 30). Else 100*LogNormal(0, 0.3)."""
    shape = (n,) if size is None else (size, n)
    fail = rng.random(shape) < p_fail
    good = 100.0 * np.exp(0.3 * rng.standard_normal(shape))
    bad = 30.0 * rng.random(shape)
    return np.where(fail, bad, good)

def true_mean(p_fail):
    return (1 - p_fail) * 100.0 * math.exp(0.3 ** 2 / 2) + p_fail * 15.0

def iqm(x):
    """Interquartile mean: drop floor(n/4) lowest and highest, average the rest.
    Works on the last axis. For n < 4 nothing is dropped (it is the mean)."""
    x = np.sort(x, axis=-1)
    k = x.shape[-1] // 4
    return x[..., k:x.shape[-1] - k].mean(axis=-1)

# ------------------------------------------------------- Welch t, from scratch
def _betacf(a, b, x):
    tiny = 1e-30
    qab, qap, qam = a + b, a + 1, a - 1
    c, d = 1.0, 1.0 - qab * x / qap
    d = 1.0 / (d if abs(d) > tiny else tiny)
    h = d
    for m in range(1, 200):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d; d = 1.0 / (d if abs(d) > tiny else tiny)
        c = 1.0 + aa / c; c = c if abs(c) > tiny else tiny
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d; d = 1.0 / (d if abs(d) > tiny else tiny)
        c = 1.0 + aa / c; c = c if abs(c) > tiny else tiny
        delta = d * c
        h *= delta
        if abs(delta - 1.0) < 1e-12:
            break
    return h

def betainc(a, b, x):
    if x <= 0.0: return 0.0
    if x >= 1.0: return 1.0
    lbeta = math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
    front = math.exp(lbeta + a * math.log(x) + b * math.log(1 - x))
    if x < (a + 1) / (a + b + 2):
        return front * _betacf(a, b, x) / a
    return 1.0 - front * _betacf(b, a, 1 - x) / b

def t_cdf(t, df):
    p = 0.5 * betainc(df / 2, 0.5, df / (df + t * t))  # upper tail of |t|
    return 1 - p if t > 0 else p

def t_quantile(q, df):
    lo, hi = 0.0, 100.0
    for _ in range(80):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if t_cdf(mid, df) < q else (lo, mid)
    return (lo + hi) / 2

def welch_p(x, y):
    """Two-sided Welch p-value with Welch-Satterthwaite df and a t reference."""
    nx, ny = len(x), len(y)
    vx, vy = x.var(ddof=1) / nx, y.var(ddof=1) / ny
    se2 = vx + vy
    if se2 == 0: return 1.0
    t = (x.mean() - y.mean()) / math.sqrt(se2)
    df = se2 ** 2 / (vx ** 2 / (nx - 1) + vy ** 2 / (ny - 1))
    return 2 * (1 - t_cdf(abs(t), df))

# ------------------------------------------------------------------- set-up
P_A, P_B = 0.30, 0.20          # B fails less often, so B is truly better
MU_A, MU_B = true_mean(P_A), true_mean(P_B)
big = run_scores(P_A, 2_000_000)
IQM_A = float(iqm(big))
big = run_scores(P_B, 2_000_000)
IQM_B = float(iqm(big))
NS = [3, 5, 10, 30]

print("Population: run score = Uniform(0,30) w.p. p_fail, else 100*LogNormal(0,0.3)")
print(f"  A: p_fail={P_A:.2f}  mean={MU_A:6.2f}  IQM={IQM_A:6.2f}")
print(f"  B: p_fail={P_B:.2f}  mean={MU_B:6.2f}  IQM={IQM_B:6.2f}")
print(f"  gap in means = {MU_B - MU_A:.2f}")

# --------------------------------------------------------------------- (a)
print("\n(a) P(correct ranking: B ranked above A), 4000 replications")
print(f"{'n seeds':>8} {'mean':>8} {'IQM':>8}")
R = 4000
for n in NS:
    a, b = run_scores(P_A, n, R), run_scores(P_B, n, R)
    print(f"{n:>8d} {(b.mean(1) > a.mean(1)).mean():>8.3f} {(iqm(b) > iqm(a)).mean():>8.3f}")

# --------------------------------------------------------------------- (b)
print("\n(b) Welch t-test, alpha=0.05, 2000 replications")
print(f"{'n seeds':>8} {'false pos (A vs A)':>20} {'power (A vs B)':>16}")
R = 2000
for n in NS + [100]:
    fp = pw = 0
    for _ in range(R):
        x, y = run_scores(P_A, n), run_scores(P_A, n)
        fp += welch_p(x, y) < 0.05
        x, y = run_scores(P_A, n), run_scores(P_B, n)
        pw += welch_p(x, y) < 0.05
    print(f"{n:>8d} {fp / R:>20.3f} {pw / R:>16.3f}")

# --------------------------------------------------------------------- (c)
print("\n(c) 95% interval coverage for algorithm A, 1000 replications, 1000 bootstrap draws")
print(f"{'n seeds':>8} {'t-int mean':>11} {'width':>7} {'boot mean':>10} {'width':>7} {'boot IQM':>9} {'width':>7}")
R, B = 1000, 1000
for n in NS:
    hit = np.zeros(3); wid = np.zeros(3)
    tq = t_quantile(0.975, n - 1)
    for _ in range(R):
        x = run_scores(P_A, n)
        m, s = x.mean(), x.std(ddof=1)
        lo, hi = m - tq * s / math.sqrt(n), m + tq * s / math.sqrt(n)
        hit[0] += lo <= MU_A <= hi; wid[0] += hi - lo
        xb = x[rng.integers(0, n, (B, n))]
        for j, (stat, target) in enumerate([(xb.mean(1), MU_A), (iqm(xb), IQM_A)], 1):
            lo, hi = np.percentile(stat, [2.5, 97.5])
            hit[j] += lo <= target <= hi; wid[j] += hi - lo
    h, w = hit / R, wid / R
    print(f"{n:>8d} {h[0]:>11.3f} {w[0]:>7.1f} {h[1]:>10.3f} {w[1]:>7.1f} {h[2]:>9.3f} {w[2]:>7.1f}")

# --------------------------------------------------------------------- (d)
print("\n(d) Best of 5 configs picked on the same seeds, 4000 replications")
print("    configs differ in p_fail; reported = mean over the seeds used to choose,")
print("    fresh = mean over new seeds for the chosen config; truth = its population mean")
for label, ps in [("spread configs", [0.20, 0.225, 0.25, 0.275, 0.30]),
                  ("identical configs", [0.25] * 5)]:
    print(f"  {label}: p_fail = {ps}")
    print(f"{'n seeds':>10} {'reported':>9} {'fresh':>8} {'truth':>8} {'optimism':>9}")
    mus = np.array([true_mean(p) for p in ps])
    R = 4000
    for n in NS:
        rep = fresh = tru = 0.0
        for _ in range(R):
            tune = np.array([run_scores(p, n).mean() for p in ps])
            k = int(tune.argmax())
            rep += tune[k]; tru += mus[k]
            fresh += run_scores(ps[k], n).mean()
        print(f"{n:>10d} {rep / R:>9.2f} {fresh / R:>8.2f} {tru / R:>8.2f} {(rep - tru) / R:>9.2f}")