"""CSE 541 Autumn 2026, Homework 3: starter code. Problems 1(d) and 4 are empirical. Fill in every function marked TODO; everything else is provided so that your plots are comparable to ours. Put mnist_pca30.npz (course website) in the same folder and run python hw3_starter.py # everything (a minute or two) python hw3_starter.py 1 3b 3d # or only some parts Requires numpy, matplotlib and scikit-learn (only for fit_logistic). Tip: the matrices here are tiny, so multithreaded BLAS only slows things down; run with OMP_NUM_THREADS=1. """ import sys from statistics import NormalDist import numpy as np import matplotlib.pyplot as plt # ====================================================================== # Problem 1(d): peeking at an A/B test # ====================================================================== def z_boundary(t, alpha): """The fixed-sample two-sided z-test threshold on |S_t|, applied at time t: z_{alpha/2} * sqrt(t). t is an array of times 1..N; return an array of the same shape. (NormalDist().inv_cdf is the Gaussian quantile.)""" # TODO raise NotImplementedError def mixture_boundary(t, alpha, rho2): """Your boundary b_t from Problem 1(b): reject the first time |S_t| >= b_t. rho2 is the prior variance rho^2.""" # TODO raise NotImplementedError def first_crossings(mu, N, runs, rng, alpha=0.05, rho2=0.01, chunk=100): """Simulate `runs` independent paths S_t = X_1 + ... + X_t, X_s ~ N(mu, 1), t = 1..N. For each path return the first time |S_t| crosses the z boundary and the first time it crosses the mixture boundary (N + 1 if never).""" t = np.arange(1, N + 1) bz, bm = z_boundary(t, alpha), mixture_boundary(t, alpha, rho2) tz, tm = [], [] for _ in range(runs // chunk): S = np.abs(np.cumsum(mu + rng.standard_normal((chunk, N), dtype=np.float32), axis=1, dtype=np.float64)) for b, out in ((bz, tz), (bm, tm)): hit = S >= b out.append(np.where(hit.any(axis=1), hit.argmax(axis=1) + 1, N + 1)) return np.concatenate(tz), np.concatenate(tm) def problem1(N=100_000, runs=1000, alpha=0.05, rho2=0.01, mus=(0.05, 0.1, 0.3)): rng = np.random.default_rng(0) grid = np.unique(np.logspace(0, np.log10(N), 200).astype(int)) fig, axes = plt.subplots(1, 2, figsize=(12, 4.3)) tz, tm = first_crossings(0.0, N, runs, rng, alpha, rho2) # under H_0 axes[0].plot(grid, [(tz <= g).mean() for g in grid], label="z-test, checked after every sample") axes[0].plot(grid, [(tm <= g).mean() for g in grid], label="mixture boundary") axes[0].axhline(alpha, color="k", linestyle=":", label=f"alpha = {alpha}") axes[0].set_xscale("log"); axes[0].set_xlabel("t"); axes[0].set_ylabel("P_0(rejected by time t)") axes[0].set_title("Under H_0 (mu = 0): false positives"); axes[0].legend(fontsize=8) print(f" H0: z-test rejected by N on {np.mean(tz <= N):.3f} of runs, mixture on {np.mean(tm <= N):.3f}") z, zb = NormalDist().inv_cdf(1 - alpha / 2), NormalDist().inv_cdf(0.8) for k, mu in enumerate(mus): # under the alternative _, tm = first_crossings(mu, N, runs, rng, alpha, rho2) n_fixed = (z + zb) ** 2 / mu ** 2 # fixed-n z-test with 80% power at this mu axes[1].plot(grid, [(tm <= g).mean() for g in grid], color=f"C{k}", label=f"mu = {mu}: mixture test has stopped") axes[1].axvline(n_fixed, color=f"C{k}", linestyle="--") print(f" mu = {mu}: mixture stops at mean {tm.mean():.0f}, median {np.median(tm):.0f}; fixed-n for 80% power: {n_fixed:.0f};" f" 2 log(1/alpha)/mu^2 = {2 * np.log(1 / alpha) / mu ** 2:.0f}") axes[1].axhline(0.8, color="k", linestyle=":") axes[1].set_xscale("log"); axes[1].set_xlabel("t"); axes[1].set_ylabel("P_mu(rejected by time t)") axes[1].set_title("Under mu > 0 (dashed: fixed n with 80% power at that mu)"); axes[1].legend(fontsize=8) fig.tight_layout(); fig.savefig("problem1.pdf"); plt.close(fig) # ====================================================================== # Problem 3: contextual bandits on MNIST # ====================================================================== N_ACTIONS = 10 def load_data(path="mnist_pca30.npz"): """Contexts C (60000 x 31, each row has norm 1; the last coordinate is a constant feature) and labels y in {0..9}. The rows are already shuffled.""" D = np.load(path) return D["C"].astype(np.float64), D["y"].astype(int) class BlockRidge: """Ridge regression for the model v(c, a) = , i.e. theta = (theta_0, ..., theta_{n-1}) in R^{n d} with features phi(c, a) = vec(c e_a^T). Because V_t = gamma I + sum_s phi_s phi_s^T is block diagonal (Problem 3(a)), we store one d x d inverse per action and update it with Sherman-Morrison. predict(c) -> array of n values width(c) -> array of n values ||c||_{V_a^{-1}} = ||phi(c, a)||_{V^{-1}} update(c, a, r) add the observation (phi(c, a), r) logdet_ratio log( det V_t / det V_0 ) """ def __init__(self, n, d, gamma=1.0): self.n, self.d, self.gamma = n, d, gamma self.Vinv = np.stack([np.eye(d) / gamma] * n) self.S = np.zeros((n, d)) self.theta = np.zeros((n, d)) self.logdet_ratio = 0.0 def predict(self, c): return self.theta @ c def width(self, c): return np.sqrt(np.einsum("i,aij,j->a", c, self.Vinv, c)) def update(self, c, a, r): u = self.Vinv[a] @ c s = 1.0 + c @ u self.Vinv[a] -= np.outer(u, u) / s self.S[a] += r * c self.theta[a] = self.Vinv[a] @ self.S[a] self.logdet_ratio += np.log(s) def fit_logistic(Cs, As, Rs, Ps): """The cost-sensitive classification oracle, approximated as in lecture: weighted multi-class logistic regression on examples (c_s, a_s) with weights r_s / p_s. Returns a function mapping an (m x d) array of contexts to m actions.""" from sklearn.linear_model import LogisticRegression w = Rs / Ps keep = w > 0 clf = LogisticRegression(C=100.0, max_iter=5000).fit(Cs[keep], As[keep], sample_weight=w[keep] / w[keep].mean()) W, b, classes = clf.coef_, clf.intercept_, clf.classes_ return lambda Cq: classes[np.argmax(np.atleast_2d(Cq) @ W.T + b, axis=1)] def run(C, y, choose, rng, gamma=1.0): """Play one contextual bandit game. `choose(t, c, model, hist, rng)` returns the action for round t, where model is the BlockRidge fit on rounds 0..t-1 and hist = (contexts, actions, rewards) of rounds 0..t-1. The reward is r_t = 1{a_t = y_t}; only r_t is revealed. Returns the array of actions.""" T, d = C.shape model = BlockRidge(N_ACTIONS, d, gamma) A = np.empty(T, dtype=int); R = np.empty(T) for t in range(T): a = int(choose(t, C[t], model, (C[:t], A[:t], R[:t]), rng)) r = float(a == y[t]) model.update(C[t], a, r) A[t], R[t] = a, r return A # Each algorithm is a function that returns a `choose` function (a closure, so that it can keep its own state). def uniform(): """Example: the uniformly random policy.""" def choose(t, c, model, hist, rng): return rng.integers(model.n) return choose def etc_world(tau): """Explore-then-commit, model the world: uniform for t < tau; afterwards greedy with respect to the least-squares estimate frozen at round tau (copy model.theta the first time t >= tau).""" state = {} def choose(t, c, model, hist, rng): # TODO raise NotImplementedError return choose def etc_bias(tau): """Explore-then-commit, model the bias: uniform for t < tau; at round tau call fit_logistic once on the logged data (p_s = 1/n) and play the returned policy from then on.""" state = {} def choose(t, c, model, hist, rng): # TODO raise NotImplementedError return choose def greedy(): """Follow-the-leader: always play argmax_a for the current estimate.""" def choose(t, c, model, hist, rng): # TODO raise NotImplementedError return choose def eps_greedy(c0=1.0): """With probability eps_t = min(1, c0 (n / (t+1))^{1/3}) play uniformly at random, otherwise greedy.""" def choose(t, c, model, hist, rng): # TODO raise NotImplementedError return choose def linucb(T, beta=None, U=1.0): """argmax_a + beta_t ||c||_{V_a^{-1}}. If beta is None use the confidence radius from Homework 2, beta_t = sqrt(gamma) U + sqrt(2 log(1/delta) + log(det V_t / det V_0)) with delta = 1/T; otherwise the constant beta.""" def choose(t, c, model, hist, rng): # TODO raise NotImplementedError return choose def thompson(scale=1.0): """Linear Thompson sampling with theta_tilde ~ N(theta_hat, scale^2 V^{-1}); see Problem 3(a) for how to sample the n numbers without ever forming theta_tilde.""" def choose(t, c, model, hist, rng): # TODO raise NotImplementedError return choose def squarecb(gam): """Inverse gap weighting on f_hat(c, a) = : with a_hat the greedy action, p(a) = 1 / (n + gam_t (f_hat(c, a_hat) - f_hat(c, a))) for a != a_hat, and the remaining mass on a_hat. `gam` is either a number or a function of t.""" def choose(t, c, model, hist, rng): # TODO raise NotImplementedError return choose def problem3b(T=50_000, tau=5000): C, y = load_data(); C, y = C[:T], y[:T] algs = { f"ETC, model the world (tau={tau})": etc_world(tau), f"ETC, model the bias (tau={tau})": etc_bias(tau), "greedy": greedy(), "eps-greedy": eps_greedy(), "LinUCB, beta from theory": linucb(T), "LinUCB, beta = 0.3": linucb(T, beta=0.3), "Thompson, scale = 1": thompson(1.0), "Thompson, scale = 0.3": thompson(0.3), "SquareCB, gamma = 10": squarecb(10.0), "SquareCB, gamma = 1000": squarecb(1000.0), "SquareCB, gamma_t = 10 sqrt(t)": squarecb(lambda t: 10.0 * np.sqrt(t + 1)), } fig, ax = plt.subplots(figsize=(9, 5.5)) styles = ["-", "--", "-.", ":"] for k, (name, choose) in enumerate(algs.items()): A = run(C, y, choose, np.random.default_rng(0)) wrong = (A != y) ax.plot(np.cumsum(wrong), label=name, linestyle=styles[k % 4]) print(f" {name:34s} mistakes {wrong.sum():6d} accuracy over the last 5000 rounds {1 - wrong[-5000:].mean():.3f}") ax.set_xlabel("round t"); ax.set_ylabel("cumulative mistakes sum_{s<=t} 1{a_s != y_s}") ax.set_title("Contextual bandits on MNIST: regret against always guessing the correct label") ax.set_ylim(0, 16000); ax.legend(fontsize=7) fig.tight_layout(); fig.savefig("problem3b.pdf"); plt.close(fig) def ope_estimates(pi, A, R, P, F): """Off-policy estimates of V(pi) from m logged rounds. pi : (m,) the action pi(c_t) the target policy would take on each logged context A, R, P : (m,) logged actions, rewards, and propensities p_t = mu(a_t | c_t) F : (m, n) the model's predictions f_hat(c_t, a) for every action Return the triple (IPS, model-the-world, doubly robust).""" # TODO raise NotImplementedError def problem3d(m_train=5000, m_eval=2000, reps=1000, eps=0.2): """A model f_hat and three target policies are built from m_train uniformly logged rounds. Each is then evaluated on m_eval fresh contexts, with the logged actions redrawn `reps` times so that we can see the bias and the spread of every estimator. Because MNIST has all the labels, the true value of each policy on those contexts is known.""" C, y = load_data(); n = N_ACTIONS; rng = np.random.default_rng(0) Ctr, ytr = C[:m_train], y[:m_train] Cev, yev = C[m_train:m_train + m_eval], y[m_train:m_train + m_eval] Atr = rng.integers(n, size=m_train); Rtr = (Atr == ytr).astype(float) # uniformly logged training rounds model = BlockRidge(n, C.shape[1]) for c, a, r in zip(Ctr, Atr, Rtr): model.update(c, a, r) F = Cev @ model.theta.T # f_hat(c, a) on the evaluation contexts targets = { "pi_world (greedy for f_hat)": np.argmax(F, axis=1), "pi_bias (logistic)": fit_logistic(Ctr, Atr, Rtr, np.full(m_train, 1 / n))(Cev), "pi_second (f_hat's 2nd choice)": np.argsort(F, axis=1)[:, -2], } prod = targets["pi_world (greedy for f_hat)"] # the "production" policy for logging (ii) for logging in ("uniform", f"eps-greedy around pi_world, eps = {eps}"): print(f" logging policy: {logging}") print(f" {'target policy':32s} {'truth':>6s} | {'IPS mean':>9s} {'sd':>6s} | {'MW mean':>9s} {'sd':>6s} | {'DR mean':>9s} {'sd':>6s}") for name, pi in targets.items(): est = np.empty((reps, 3)) for k in range(reps): if logging == "uniform": A = rng.integers(n, size=m_eval); P = np.full(m_eval, 1 / n) else: A = np.where(rng.random(m_eval) < eps, rng.integers(n, size=m_eval), prod) P = np.where(A == prod, 1 - eps + eps / n, eps / n) R = (A == yev).astype(float) est[k] = ope_estimates(pi, A, R, P, F) mu, sd = est.mean(axis=0), est.std(axis=0) print(f" {name:32s} {np.mean(pi == yev):6.3f} | {mu[0]:9.3f} {sd[0]:6.3f} | {mu[1]:9.3f} {sd[1]:6.3f} | {mu[2]:9.3f} {sd[2]:6.3f}") if __name__ == "__main__": parts = {"1": problem1, "3b": problem3b, "3d": problem3d} for p in (sys.argv[1:] or list(parts)): print(f"=== Problem {p} ===") parts[p]()