Srishti280992's picture
Add incentivized exploration reproduction bundle
b381c58 verified
Raw
History Blame Contribute Delete
7.67 kB
"""Section 5.1 sensitivity: which reading of the paper's under-specified warfarin
setup reproduces Table 2 (score 0.291, error ~0.35, confusion [[50,48,2],[14,84,2],[2,93,5]])?
Three specifications are ambiguous or absent in the paper:
(R) reward. "Evaluation Criteria" states y_t = 1 if the recommended dosage matches
the patient's true optimal arm, 0 otherwise (BINARY). The "Ground Truth"
paragraph instead says the true mean reward is x'beta_i for the optimal arm and
0 for counterfactual arms (CONTINUOUS). These are different environments.
(E) E_{F,delta}(|T_{m-1}|) in Algorithm 2 line 10 (gamma_m = 4 sqrt(K / E_F)).
THEORY = Corollary 1's closed form c3 sigma^2 d / (phi0 n) with the paper's own
sigma_hat = 0.054; EMPIRICAL = the oracle's measured out-of-fold MSPE minus sigma^2.
(P) phi0 of Assumption 3 (lambda_min E[xx']). The IWPC dummy design is rank
deficient so the true value is 0; we compare phi0 = 1 (unit normalisation) with
the smallest strictly positive eigenvalue of the empirical design.
(N) the per-arm cold-start size. Theorem 1 at C = 1 demands N(0.025) ~ 3.6e4 per
arm, i.e. ~1.1e5 patients versus the T = 5528 actually available, so the paper's
experiment cannot have used its own Theorem 1 value. We sweep N.
Everything else follows Section 5.1 verbatim: T = 5528, sigma_hat = 0.054, tau_P0 = 0.005,
eps in [0.025, 0.035, 0.045], Sigma_0 in [0.4, 0.6, 0.8] I_d, beta_{2,0} = 0.05 x 1_d,
beta_{1,0} = beta_{3,0} = 0_d, averaged over random permutations of patient arrivals.
"""
import argparse, json, os, sys, time
import numpy as np
os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from rcb.core import N_eps
from rcb.env import build_warfarin
from scripts.run_warfarin import (ground_truth, weighted_risk_score, run_one,
effective_phi0)
PAPER_CONF = np.array([[.50, .48, .02], [.14, .84, .02], [.02, .93, .05]])
def summarise(rs, arm, prev):
"""Aggregate a list of run_one results into the Table-2 style metrics."""
rp = [r["rec_by_patient"] for r in rs]
conf = np.mean([[[float((p[arm == k] == j).mean()) for j in range(3)]
for k in range(3)] for p in rp], axis=0)
# error over ALL T rounds (the paper's stated R(T)/T) and over the exploitation
# stage only (the quantity Figure 2's curve shape implies)
err_all, err_post = [], []
for r in rs:
c = r["correct"]
err_all.append(1.0 - c.mean())
tc = int(r["Tcold"])
err_post.append(1.0 - c[tc:].mean() if tc < len(c) else float("nan"))
return dict(
error=float(np.mean(err_all)),
error_post_coldstart=float(np.nanmean(err_post)),
score=float(np.mean([weighted_risk_score(p == arm, arm, prev) for p in rp])),
score_sd=float(np.std([weighted_risk_score(p == arm, arm, prev) for p in rp])),
Tcold=float(np.mean([r["Tcold"] for r in rs])),
gain_min=float(np.mean([r["gain"].min() for r in rs])),
confusion=conf.tolist(),
conf_L1_vs_paper=float(np.abs(conf - PAPER_CONF).sum()),
)
def offline_ceiling(X, arm, mu_opt, prev, reward, lam=1e-2):
"""Per-arm ridge fit on ALL 5528 patients: the best any policy built on the
paper's own linear-regression oracle can do, with zero exploration cost."""
d = X.shape[1]
bh = []
for i in range(3):
y = (arm == i).astype(float) if reward == "binary" else np.where(arm == i, mu_opt, 0.0)
bh.append(np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y))
pred = (X @ np.array(bh).T).argmax(1)
conf = np.array([[float((pred[arm == k] == j).mean()) for j in range(3)] for k in range(3)])
return dict(reward=reward, error=float(1 - (pred == arm).mean()),
score=weighted_risk_score(pred == arm, arm, prev),
confusion=conf.tolist(),
conf_L1_vs_paper=float(np.abs(conf - PAPER_CONF).sum()))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", default="data/iwpc_warfarin_5528.csv")
ap.add_argument("--out", default="outputs/warfarin_ablation.json")
ap.add_argument("--perms", type=int, default=5)
args = ap.parse_args()
X, arm, dose, cols = build_warfarin(args.data)
_, mu_opt, _, sigma = ground_truth(X, arm, dose)
n, d = X.shape
prev = np.bincount(arm, minlength=3) / n
phi0_emp = effective_phi0(X)
res = dict(meta=dict(n=n, d=d, sigma_hat=sigma, prevalence=prev.tolist(),
phi0_empirical=phi0_emp,
physician_error=float(1 - (arm == 1).mean()),
physician_score=weighted_risk_score(arm == 1, arm, prev),
paper=dict(score=0.291, error=0.3545, physician_score=0.20,
confusion=PAPER_CONF.tolist())))
print(f"physician: err={res['meta']['physician_error']:.4f} "
f"score={res['meta']['physician_score']:+.4f} (paper 0.20)")
res["ceilings"] = [offline_ceiling(X, arm, mu_opt, prev, r) for r in ("binary", "continuous")]
for c in res["ceilings"]:
print(f"offline ceiling [{c['reward']:<10}] err={c['error']:.4f} "
f"score={c['score']:+.4f} confL1={c['conf_L1_vs_paper']:.3f}")
# Theorem 1's own N(eps) at C = 1, phi0 = 1 -- infeasibility check
res["meta"]["N_theorem1"] = {
str(e): dict(phi0_1=N_eps(3, d, sigma, e, 0.005, 1.0, C=1.0),
phi0_emp=N_eps(3, d, sigma, e, 0.005, phi0_emp, C=1.0))
for e in (0.025, 0.035, 0.045)}
print("Theorem 1 N(eps) @C=1,phi0=1: " +
" ".join(f"{k}:{v['phi0_1']:.3g}" for k, v in res["meta"]["N_theorem1"].items())
+ f" (T available = {n})")
t0 = time.time()
# ---- (R) x (E) x (P) at a fixed small cold start ------------------------
res["spec_grid"] = []
for reward in ("binary", "continuous"):
for EF in ("theory", "empirical"):
for pname, pv0 in (("1.0", 1.0), ("empirical", phi0_emp)):
rs = [run_one(X, arm, mu_opt, sigma, 0.025, 0.4, seed=1000 * p + 7,
C_N=1.0, reward=reward, use_empirical_EF=(EF == "empirical"),
phi0=pv0, N_override=5) for p in range(args.perms)]
e = dict(reward=reward, EF=EF, phi0=pname, **summarise(rs, arm, prev))
res["spec_grid"].append(e)
print(f"[{reward:<10} EF={EF:<9} phi0={pname:<9}] err={e['error']:.4f} "
f"score={e['score']:+.4f} confL1={e['conf_L1_vs_paper']:.3f} "
f"[{time.time()-t0:.0f}s]")
# ---- (N) sweep under the faithful reading -------------------------------
res["N_sweep"] = []
for N in (1, 2, 5, 10, 20, 30, 50, 100):
rs = [run_one(X, arm, mu_opt, sigma, 0.025, 0.4, seed=1000 * p + 7, C_N=1.0,
reward="binary", use_empirical_EF=False, phi0=1.0,
N_override=N) for p in range(args.perms)]
e = dict(N=N, **summarise(rs, arm, prev))
res["N_sweep"].append(e)
print(f"[N={N:<4}] Tcold={e['Tcold']:.0f} err={e['error']:.4f} "
f"err_post={e['error_post_coldstart']:.4f} score={e['score']:+.4f} "
f"confL1={e['conf_L1_vs_paper']:.3f} [{time.time()-t0:.0f}s]")
res["wall_clock_s"] = time.time() - t0
os.makedirs(os.path.dirname(args.out), exist_ok=True)
json.dump(res, open(args.out, "w"))
print(f"wrote {args.out} in {res['wall_clock_s']:.0f}s")
if __name__ == "__main__":
main()