File size: 4,798 Bytes
b381c58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""Is the paper's ~0.35 warfarin error rate attainable by RCB?

RCB's error decomposes as
    err = P(explore off-greedy) * err_explore + P(play b_t) * err(b_t),
so it is bounded below by the accuracy of the offline oracle b_t itself. We sweep a
multiplier on the spread parameter gamma_m (gamma -> 0 = uniform exploration,
gamma -> inf = pure greedy on the oracle) and report where the paper's 0.35 sits.
"""
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 RCB, N_eps, L_eps
from rcb.env import build_warfarin
from scripts.run_warfarin import ground_truth, weighted_risk_score, effective_phi0


def offline_ceiling(X, arm, mu_opt, sigma, seed=0, lam=1e-2):
    """Accuracy of the per-arm ridge oracle fit on the ENTIRE dataset -- the best any
    policy using this oracle class can do (the paper's Lasso-Bandit dotted line)."""
    rng = np.random.default_rng(seed)
    n, d = X.shape
    bh = []
    for i in range(3):
        y = np.where(arm == i, mu_opt, 0.0) + sigma * rng.standard_normal(n)
        bh.append(np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y))
    pred = (X @ np.array(bh).T).argmax(1)
    return float((pred == arm).mean()), pred


def run(X, arm, mu_opt, sigma, eps, pv, seed, gmul, N, phi0):
    rng = np.random.default_rng(seed)
    n, d = X.shape
    order = rng.permutation(n)
    beta0 = [np.zeros(d), 0.05 * np.ones(d), np.zeros(d)]
    S0 = [pv * np.eye(d) for _ in range(3)]
    a = RCB(3, d, sigma, beta0, S0, N=N, L=L_eps(eps, 0.005, 0.95), offset=0.0,
            phi0=phi0, trust_mode="linear", gamma_const=4.0 * gmul,
            use_empirical_EF=True, rng=rng)
    ok = np.zeros(n, bool); expl = []; bok = []; gains = []
    rec_by_patient = np.empty(n, int)
    for t, idx in enumerate(order):
        x = X[idx]
        rec, info = a.recommend(x)
        rec_by_patient[idx] = rec
        gains.append(a.dbic_gain_expected(x, a.rec_kernel(x, info)))
        ok[t] = rec == arm[idx]
        if info["phase"] == "IPGS":
            expl.append(rec != info["b"]); bok.append(info["b"] == arm[idx])
        y = (mu_opt[idx] if ok[t] else 0.0) + sigma * rng.standard_normal()
        a.update(x, rec, y, info)
    return dict(err=float(1 - ok.mean()), explore=float(np.mean(expl)),
                b_acc=float(np.mean(bok)), Tcold=a.Tcold,
                gain_min=float(np.min(gains)), gain_mean=float(np.mean(gains)),
                rec=rec_by_patient)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", default="data/iwpc_warfarin_5528.csv")
    ap.add_argument("--out", default="outputs/warfarin_gamma_sweep.json")
    ap.add_argument("--perms", type=int, default=5)
    ap.add_argument("--N", type=int, default=10)
    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 = effective_phi0(X)

    acc_ceiling, pred = offline_ceiling(X, arm, mu_opt, sigma)
    print(f"offline ridge-oracle ceiling: accuracy={acc_ceiling:.3f} error={1-acc_ceiling:.3f} "
          f"score={weighted_risk_score(pred == arm, arm, prev):.3f}")
    print(f"physician (always Medium):    error={1-(arm==1).mean():.3f} "
          f"score={weighted_risk_score(arm == 1, arm, prev):.3f}")

    res = {"ceiling_error": 1 - acc_ceiling,
           "ceiling_score": weighted_risk_score(pred == arm, arm, prev),
           "physician_error": float(1 - (arm == 1).mean()),
           "physician_score": weighted_risk_score(arm == 1, arm, prev),
           "prevalence": prev.tolist(), "sweep": []}

    t0 = time.time()
    for gmul in [0.25, 1.0, 4.0, 16.0, 64.0, 256.0, 1e4]:
        rs = [run(X, arm, mu_opt, sigma, 0.025, 0.4, 1000 * p + 7, gmul, args.N, phi0)
              for p in range(args.perms)]
        sc = float(np.mean([weighted_risk_score(r["rec"] == arm, arm, prev) for r in rs]))
        e = dict(gamma_mult=gmul, error=float(np.mean([r["err"] for r in rs])),
                 explore=float(np.mean([r["explore"] for r in rs])),
                 b_acc=float(np.mean([r["b_acc"] for r in rs])), score=sc,
                 gain_min=float(np.mean([r["gain_min"] for r in rs])))
        res["sweep"].append(e)
        print(f"gamma x{gmul:<8g} error={e['error']:.3f} explore={e['explore']:.3f} "
              f"b_acc={e['b_acc']:.3f} score={sc:+.3f} min-gain={e['gain_min']:+.4f}")
    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}  [{res['wall_clock_s']:.0f}s]")


if __name__ == "__main__":
    main()