RLS RL, Read as Statistics

ch02_bandits.py

Companion code for Bandits as sequential experiments. Needs only Python 3 and NumPy: python code/ch02_bandits.py.

NumPy
"""Chapter 2: bandits as sequential experiments.

Demonstrates, with Bernoulli arms:
  * regret of uniform allocation (a fixed-design A/B/n test that never stops),
    explore-then-commit, epsilon-greedy and UCB1, averaged over many runs
    with standard errors, next to the UCB1 and Lai-Robbins bounds;
  * the bias of the sample mean under adaptive sampling (exact enumeration
    for a 3-round toy, then simulation for greedy, epsilon-greedy and UCB1);
  * the UCB1 indices used in the hand-worked example of the chapter.

Run: python code/ch02_bandits.py   (NumPy only, about 20 seconds)
"""
import numpy as np
from itertools import product

rng = np.random.default_rng(2)


# ---- Policies --------------------------------------------------------------
# Every policy is vectorised over `runs` independent experiments. A policy is a
# function choose(t, n, s, rng) -> arm index per run, where t = 1, 2, ... is the
# current round, n[run, arm] are pull counts and s[run, arm] are reward sums.
def unif(t, n, s, rng):
    return (t - 1) % n.shape[1] * np.ones(n.shape[0], dtype=int)


def make_etc(m):
    """Explore-then-commit: m pulls of each arm (round robin), then the best mean."""
    def choose(t, n, s, rng):
        K = n.shape[1]
        if t <= m * K:
            return unif(t, n, s, rng)
        return np.argmax(s / np.maximum(n, 1), axis=1)
    return choose


def make_eps(eps):
    """Epsilon-greedy with constant epsilon (after one pull of each arm)."""
    def choose(t, n, s, rng):
        K = n.shape[1]
        if t <= K:
            return unif(t, n, s, rng)
        greedy = np.argmax(s / n, axis=1)
        explore = rng.random(n.shape[0]) < eps
        return np.where(explore, rng.integers(K, size=n.shape[0]), greedy)
    return choose


def make_eps_decay(c):
    """Epsilon-greedy with epsilon_t = min(1, c K / t)."""
    def choose(t, n, s, rng):
        K = n.shape[1]
        if t <= K:
            return unif(t, n, s, rng)
        greedy = np.argmax(s / n, axis=1)
        explore = rng.random(n.shape[0]) < min(1.0, c * K / t)
        return np.where(explore, rng.integers(K, size=n.shape[0]), greedy)
    return choose


def ucb1_index(t, n, s):
    return s / n + np.sqrt(2.0 * np.log(t) / n)


def ucb1(t, n, s, rng):
    K = n.shape[1]
    if t <= K:
        return unif(t, n, s, rng)
    return np.argmax(ucb1_index(t, n, s), axis=1)


def greedy(t, n, s, rng):
    K = n.shape[1]
    if t <= K:
        return unif(t, n, s, rng)
    return np.argmax(s / n, axis=1)   # ties go to the lowest index


def run(choose, mu, T, runs, rng, checkpoints=()):
    """Play T rounds in `runs` parallel experiments. Returns pseudo-regret at the
    checkpoints (array runs x len(checkpoints)) and final counts and sums."""
    mu = np.asarray(mu)
    K = len(mu)
    gap = mu.max() - mu
    n = np.zeros((runs, K))
    s = np.zeros((runs, K))
    reg = np.zeros(runs)
    out = {}
    rows = np.arange(runs)
    for t in range(1, T + 1):
        a = choose(t, n, s, rng)
        r = (rng.random(runs) < mu[a]).astype(float)
        n[rows, a] += 1
        s[rows, a] += r
        reg += gap[a]
        if t in checkpoints:
            out[t] = reg.copy()
    return out, n, s


def kl_bern(p, q):
    return p * np.log(p / q) + (1 - p) * np.log((1 - p) / (1 - q))


# ---- 1. UCB1 indices for the hand-worked example ---------------------------
print("1. UCB1 indices (value = mean + sqrt(2 ln t / N)) for the worked example")
for label, t, ns, ms in (("A", 11, (6, 4), (4 / 6, 1 / 4)), ("B", 22, (20, 2), (0.6, 0.5))):
    n = np.array(ns, float)
    idx = np.array(ms) + np.sqrt(2 * np.log(t) / n)
    print(f"  case {label}: t={t}  N={ns}  means={tuple(round(m, 3) for m in ms)}"
          f"  indices={tuple(round(float(i), 3) for i in idx)}  -> pull arm {int(np.argmax(idx)) + 1}")

# ---- 2. Regret experiment --------------------------------------------------
mu = np.array([0.60, 0.50, 0.45, 0.40, 0.30])
K, T, RUNS = len(mu), 5000, 2000
CP = (100, 500, 1000, 5000)
gap = mu.max() - mu
algos = [
    ("uniform (A/B/n, no stopping)", unif),
    ("ETC, m=25 per arm", make_etc(25)),
    ("ETC, m=100 per arm", make_etc(100)),
    ("eps-greedy, eps=0.1", make_eps(0.1)),
    ("eps-greedy, eps_t=min(1,5K/t)", make_eps_decay(5)),
    ("UCB1", ucb1),
]
print(f"\n2. Expected regret, K={K} Bernoulli arms mu={tuple(mu.tolist())}, T={T}, {RUNS} runs")
print("   entries: mean pseudo-regret (standard error)")
print(f"{'algorithm':<32}" + "".join(f"{'T=' + str(c):>16}" for c in CP))
for name, pol in algos:
    out, _, _ = run(pol, mu, T, RUNS, rng, CP)
    cells = "".join(f"{out[c].mean():9.1f} ({out[c].std(ddof=1) / np.sqrt(RUNS):4.1f})".rjust(16) for c in CP)
    print(f"{name:<32}{cells}")

sub = gap > 0
lr_coef = (gap[sub] / kl_bern(mu[sub], mu.max())).sum()
ucb_bd = lambda T: 8 * (np.log(T) / gap[sub]).sum() + (1 + np.pi ** 2 / 3) * gap[sub].sum()
print("\n   Reference curves (not simulated):")
print(f"{'Lai-Robbins slope: sum Delta/kl':<32}" + "".join(f"{lr_coef * np.log(c):16.1f}" for c in CP))
print(f"{'UCB1 bound (Auer et al. Thm 1)':<32}" + "".join(f"{ucb_bd(c):16.1f}" for c in CP))
print(f"   Lai-Robbins coefficient sum_a Delta_a / kl(mu_a, mu*) = {lr_coef:.2f}  (regret ~ coef * ln T)")
print(f"   UCB1 coefficient 8 * sum_a 1 / Delta_a = {8 * (1 / gap[sub]).sum():.1f}")

# ---- 3. Bias of the sample mean under adaptive sampling --------------------
print("\n3a. Exact toy: two Bernoulli(0.5) arms, pull each once, pull the arm with the")
print("    higher first reward a third time (tie: arm 1). Exact E[mean_a] after 3 rounds.")
e1 = e2 = 0.0
for x, y in product((0, 1), repeat=2):          # first rewards of arm 1 and arm 2
    for z in (0, 1):                              # reward of the third pull
        w = 0.25 * 0.5
        if x >= y:                                # arm 1 pulled again
            m1, m2 = (x + z) / 2, y
        else:
            m1, m2 = x, (y + z) / 2
        e1 += w * m1
        e2 += w * m2
print(f"    E[mean_1] = {e1:.4f}, E[mean_2] = {e2:.4f}, true mean 0.5, bias = {e1 - 0.5:+.4f} each")

T_B, RUNS_B = 200, 40000
print(f"\n3b. Bias of the final sample mean, T={T_B}, {RUNS_B} runs. bias = E[mean_a - mu_a] (se)")
print(f"{'arms mu':<12}{'policy':<22}{'bias arm 1':>18}{'bias arm 2':>18}{'E[N_1]':>9}")
for mus in ((0.5, 0.5), (0.6, 0.4)):
    for name, pol in (("uniform", unif), ("eps-greedy 0.1", make_eps(0.1)),
                      ("UCB1", ucb1), ("greedy", greedy)):
        _, n, s = run(pol, mus, T_B, RUNS_B, rng)
        cells = []
        for a in range(2):
            ok = n[:, a] > 0
            d = s[ok, a] / n[ok, a] - mus[a]
            cells.append(f"{d.mean():+.4f} ({d.std(ddof=1) / np.sqrt(ok.sum()):.4f})".rjust(18))
        print(f"{str(mus):<12}{name:<22}{cells[0]}{cells[1]}{n[:, 0].mean():9.1f}")