File size: 10,859 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | """Appendix F Settings 1-4 plus the empirical regret-rate fits for Claim 1.
Setting 1 (Environment Effects), verbatim:
"We consider RCB's robustness in terms of different K = [2, 5, 10], d = [3, 5, 10].
For rest parameters, we set T = 10^5, sigma = 0.05, eps = 0.05, tau_P0 = 0.01, and
rho_P0 = 0.95. The prior are set to be beta_{i,0} = 0_d and Sigma_{i,0} = 1/5 Id."
(Figure 3 instead shows K = [3, 5, 10] and d = [2, 5, 10]; we run the union
K in {2,3,5,10} x d in {2,3,5,10}, the most demanding reading.)
Setting 2 (Ad-hoc Design): N fixed to {10, 100, 1000}, everything else as Setting 1.
Setting 3 (eps effects): T = 5e4, K = 5, d = 5, eps in {0.01,0.03,0.05},
Sigma_{i,0} = 1/lambda Id, lambda in {3,5,10}.
Setting 4 (Prior decay / Assumption 4 mis-specification): T = 5e4, K = 5, d = 5,
eps = 0.05, beta_{1,0} = 1_5, beta_{i,0} = 0_5; Sigma_{i,0} in {0.02,0.04,0.1} I;
decay modes linear / sqrt / log.
"""
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 SyntheticEnv
def simulate(T, K, d, sigma=0.05, eps=0.05, tau_P0=0.01, rho_P0=0.95,
prior_var=0.2, beta0_first=None, N=None, C_N=None, trust_mode="linear",
seed=0, gain_every=50, offset=0.5):
rng = np.random.default_rng(seed)
beta0 = [np.zeros(d) for _ in range(K)]
if beta0_first is not None:
beta0[0] = np.full(d, beta0_first)
Sigma0 = [prior_var * np.eye(d) for _ in range(K)]
env = SyntheticEnv(K, d, sigma, beta0, Sigma0, offset=offset,
rng=np.random.default_rng(seed + 99991))
phi0 = env.phi0
if N is None:
N = max(1, int(round(N_eps(K, d, sigma, eps, tau_P0, phi0, C=C_N))))
L = L_eps(eps, tau_P0, rho_P0)
algo = RCB(K, d, sigma, beta0, Sigma0, N=N, L=L, offset=offset, phi0=phi0,
trust_mode=trust_mode, gamma_const=4.0, use_empirical_EF=True, rng=rng)
regret = np.zeros(T)
gains, gain_t = [], []
cum = 0.0
for t in range(T):
x = env.context()
mu = env.mean_rewards(x)
rec, info = algo.recommend(x)
if t % gain_every == 0:
gains.append(algo.dbic_gain_expected(x, algo.rec_kernel(x, info)))
gain_t.append(t)
cum += float(mu.max() - mu[rec])
regret[t] = cum
y = env.pull(x, rec)
algo.update(x, rec, y, info)
Tcold = algo.Tcold if algo.Tcold else T
return dict(regret=regret, gains=np.array(gains), gain_t=np.array(gain_t),
Tcold=Tcold, N=N, L=L, phi0=phi0,
regret_total=float(regret[-1]),
regret_exploit=float(regret[-1] - regret[min(Tcold, T - 1)]))
def slope(xs, ys):
return float(np.polyfit(np.log(xs), np.log(ys), 1)[0])
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="outputs/synthetic.json")
ap.add_argument("--seeds", type=int, default=5)
ap.add_argument("--N", type=int, default=20, help="cold-start size for the rate fits")
ap.add_argument("--only", default="all")
ap.add_argument("--C_N3", type=float, default=1e-3)
args = ap.parse_args()
res, t0 = {}, time.time()
S = range(args.seeds)
# -------- Is Theorem 1's N(eps) even feasible at the paper's own horizons? --
if args.only in ("all", "feas"):
print("== Theorem 1 feasibility: cold-start length K*L*N(eps) vs the paper's T ==")
feas = []
for tag, T, K, d, sigma, eps, tau, phi0 in [
("Setting 1 K=2,d=2", 1e5, 2, 2, 0.05, 0.05, 0.01, 1 / 2),
("Setting 1 K=5,d=5", 1e5, 5, 5, 0.05, 0.05, 0.01, 1 / 5),
("Setting 1 K=10,d=10", 1e5, 10, 10, 0.05, 0.05, 0.01, 1 / 10),
("Setting 3 eps=0.01", 5e4, 5, 5, 0.05, 0.01, 0.01, 1 / 5),
("Setting 3 eps=0.05", 5e4, 5, 5, 0.05, 0.05, 0.01, 1 / 5),
("Warfarin eps=0.025", 5528, 3, 70, 0.054, 0.025, 0.005, 1.81e-4),
("Warfarin eps=0.045", 5528, 3, 70, 0.054, 0.045, 0.005, 1.81e-4)]:
N = N_eps(K, d, sigma, eps, tau, phi0)
L = L_eps(eps, tau, 0.95)
cold = K * L * N
feas.append(dict(tag=tag, T=T, N=N, L=L, cold=cold, ratio=cold / T))
print(f" {tag:22s} T={T:<8.0f} N(eps)={N:.3e} L={L:6.1f} "
f"K*L*N={cold:.3e} = {cold/T:.3e} x T")
res["thm1_feasibility"] = feas
# ---------------- Setting 1: full K x d grid at the paper's T = 1e5 ------
if args.only in ("all", "s1"):
print("== Setting 1 (T=1e5, K x d grid, eps=0.05) ==")
s1 = []
for K in [2, 3, 5, 10]:
for d in [2, 3, 5, 10]:
rs = [simulate(100_000, K, d, N=args.N, seed=s) for s in S]
e = dict(K=K, d=d, N=rs[0]["N"], L=rs[0]["L"],
Tcold=float(np.mean([r["Tcold"] for r in rs])),
regret=float(np.mean([r["regret_total"] for r in rs])),
regret_sd=float(np.std([r["regret_total"] for r in rs])),
gain_min=float(np.mean([r["gains"].min() for r in rs])),
gain_frac_ok=float(np.mean([(r["gains"] >= -0.05).mean() for r in rs])),
regret_curve=np.mean([r["regret"] for r in rs], 0)[::500].tolist())
s1.append(e)
print(f" K={K:2d} d={d:2d} Tcold={e['Tcold']:6.0f} R(T)={e['regret']:8.1f}"
f" min-gain={e['gain_min']:+.4f} frac(gain>=-eps)={e['gain_frac_ok']:.3f}")
res["setting1"] = s1
# rate fits over the grid
for name, key, fixed in [("K", "K", "d"), ("d", "d", "K")]:
fits = {}
for fv in [2, 3, 5, 10]:
sub = [e for e in s1 if e[fixed] == fv]
fits[fv] = slope([e[key] for e in sub], [e["regret"] for e in sub])
res[f"setting1_slope_{name}"] = fits
print(f" regret exponent in {name}: " +
", ".join(f"{fixed}={k}: {v:.3f}" for k, v in fits.items()))
# ---------------- regret rate in T (the core of Claim 1) ----------------
if args.only in ("all", "rate"):
print("== Regret rate fits: R_exploit(T) vs T, K, d ==")
rate = {}
Ts = [2 ** k for k in range(13, 18)]
for (K, d) in [(3, 5), (5, 5), (10, 5), (5, 10)]:
ys = []
for T in Ts:
rs = [simulate(T, K, d, N=args.N, seed=s) for s in S]
ys.append(float(np.mean([r["regret_exploit"] for r in rs])))
rate[f"K{K}_d{d}"] = dict(T=Ts, regret=ys, slope=slope(Ts, ys))
print(f" K={K} d={d}: exponent in T = {rate[f'K{K}_d{d}']['slope']:.3f} {ys}")
# K and d exponents at fixed large T
T = 2 ** 17
Ks = [2, 3, 5, 10, 20]
yK = [float(np.mean([simulate(T, K, 5, N=args.N, seed=s)["regret_exploit"]
for s in S])) for K in Ks]
ds = [2, 3, 5, 10, 20]
yd = [float(np.mean([simulate(T, 5, d, N=args.N, seed=s)["regret_exploit"]
for s in S])) for d in ds]
rate["K_sweep"] = dict(K=Ks, regret=yK, slope=slope(Ks, yK))
rate["d_sweep"] = dict(d=ds, regret=yd, slope=slope(ds, yd))
print(f" exponent in K = {rate['K_sweep']['slope']:.3f} (theory 0.5)")
print(f" exponent in d = {rate['d_sweep']['slope']:.3f} (theory 0.5)")
res["rate"] = rate
# ---------------- Setting 2: ad-hoc N ------------------------------------
if args.only in ("all", "s2"):
print("== Setting 2 (ad-hoc N in {10,100,1000}) ==")
s2 = []
for N in [10, 100, 1000]:
for K in [3, 5, 10]:
for d in [2, 5, 10]:
rs = [simulate(100_000, K, d, N=N, seed=s) for s in S]
g = np.concatenate([r["gains"] for r in rs])
e = dict(N=N, K=K, d=d,
regret=float(np.mean([r["regret_total"] for r in rs])),
gain_min=float(g.min()),
frac_violate=float((g < -0.05).mean()))
s2.append(e)
print(f" N={N:5d} K={K:2d} d={d:2d} R(T)={e['regret']:8.1f}"
f" min-gain={e['gain_min']:+.4f} frac(gain<-eps)={e['frac_violate']:.3f}")
res["setting2"] = s2
# ---------------- Setting 3: eps effects (Claim 2 tradeoff) --------------
if args.only in ("all", "s3"):
print("== Setting 3 (eps x prior variance) ==")
s3 = []
for eps in [0.01, 0.03, 0.05]:
for lam in [3, 5, 10]:
rs = [simulate(50_000, 5, 5, eps=eps, prior_var=1.0 / lam,
C_N=args.C_N3, seed=s) for s in S]
e = dict(eps=eps, lam=lam, N=rs[0]["N"], L=rs[0]["L"],
Tcold=float(np.mean([r["Tcold"] for r in rs])),
regret=float(np.mean([r["regret_total"] for r in rs])),
gain_min=float(np.mean([r["gains"].min() for r in rs])),
frac_ok=float(np.mean([(r["gains"] >= -eps).mean() for r in rs])))
s3.append(e)
print(f" eps={eps} 1/lam={1/lam:.3f} N={e['N']:5d} L={e['L']:6.1f}"
f" Tcold={e['Tcold']:7.0f} R(T)={e['regret']:8.1f}"
f" frac(gain>=-eps)={e['frac_ok']:.3f}")
res["setting3"] = s3
# ---------------- Setting 4: Assumption 4 mis-specification --------------
if args.only in ("all", "s4"):
print("== Setting 4 (prior decay mis-specification) ==")
s4 = []
for pv in [0.02, 0.04, 0.1]:
for mode in ["linear", "sqrt", "log", "none"]:
rs = [simulate(50_000, 5, 5, eps=0.05, prior_var=pv, beta0_first=1.0,
trust_mode=mode, N=args.N, seed=s) for s in S]
e = dict(prior_var=pv, mode=mode,
regret=float(np.mean([r["regret_total"] for r in rs])),
gain_min=float(np.mean([r["gains"].min() for r in rs])),
frac_ok=float(np.mean([(r["gains"] >= -0.05).mean() for r in rs])))
s4.append(e)
print(f" Sigma0={pv} decay={mode:7s} R(T)={e['regret']:8.1f}"
f" min-gain={e['gain_min']:+.4f} frac(gain>=-eps)={e['frac_ok']:.3f}")
res["setting4"] = s4
res["wall_clock_s"] = time.time() - t0
os.makedirs("outputs", 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()
|