# -*- coding: utf-8 -*- """phase 2 補充實驗(由 phase_1/scripts_1/extra_experiments.py 改寫)。與 train_ablation.py 共用同一批窗、同一批 fold、同一套指標。 子命令: cross 跨組交叉:用第二組(A0)、第三組、第二+第三組(A1)訓練,測第二組(B0)、第三組(B1)、對照組 rule 單一特徵不訓練的 AUC,以及邏輯斯迴歸 fixed 固定門檻:訓練回合切 30% 當校準回合定門檻,再到測試回合量實際誤判率;另做留一位玩家、B 的 125↔1000 Hz oof 焦點設定(W = 50、300)的 out-of-fold 分數,給 ROC 圖與回合分數圖用 all 以上全部 範例: python scripts_2/extra_experiments.py all python scripts_2/extra_experiments.py cross --windows 300 """ import argparse import time import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from mtd_common import N_FOLDS, PERSON, PERSONS, RESULTS, utf8_stdout from mtd_windows import GroupRows, load_rounds, load_segments, make_windows, round_code, window_features from train_ablation import (assign_folds, balanced_weight, clopper_pearson, evaluate, fit_predict_gbdt, logit, upsert) GROUPS = ['0', '1', '2', '3', '3f'] FOCUS_W = [50, 300, 1000] CROSS_TRAIN = {'2': ['2'], '3': ['3'], '2+3': ['2', '3']} CROSS_TEST = ['2', '3', '3f'] TARGET_FPR = (0.01, 0.05) CALIB_FRAC = 0.30 def feat_cols(F, use_dt): return list(F.columns) if use_dt else [c for c in F.columns if not c.startswith('t_')] class Ctx: """載入一次:窗、fold、四組列。每個窗長的特徵快取起來。""" def __init__(self, args): self.args = args self.segs, self.rounds = load_segments(), load_rounds() self.fold_of = assign_folds(self.rounds, args.folds, args.seed) self.rows = {g: GroupRows(g, 'deg', self.rounds) for g in GROUPS} self._cache = {} def windows(self, W): if W not in self._cache: wins = make_windows(self.segs, W) F = {g: window_features(self.rows[g].slice(wins), True) for g in GROUPS} rc = round_code(wins.player, wins['round']) fold = np.array([self.fold_of[c] for c in rc.tolist()]) self._cache[W] = (wins, F, rc, fold) return self._cache[W] def summary_rows(base, res): return [{**base, 'eval': name, **s} for name, s, _ in res] def rec_splits(pl): """(名稱, 選取遮罩) :全部與各錄製。""" return [('all', np.ones(len(pl), bool))] + [(f'r{p}', pl == p) for p in sorted(set(pl.tolist()))] def eval_splits(meta, score, rounds, args, rng): out = [] for name, sel in rec_splits(meta.player.to_numpy()): ar = rounds if name == 'all' else rounds[rounds.player == int(name[1:])] s, p = evaluate(meta[sel], score[sel], ar, args.boot, rng) out.append(('cv_' + name, s, p)) return out def xfer_jobs(pl, rounds): """(名稱, 訓練遮罩, 測試遮罩, 測試回合表):留一位玩家,與 B 的 125 ↔ 1000 Hz。""" person = np.array([PERSON[p] for p in pl]) jobs = [(f'lopo_{q}', person != q, person == q, rounds[rounds.player.map(PERSON) == q]) for q in PERSONS] jobs += [('dev_r2to4', pl == 2, pl == 4, rounds[rounds.player == 4]), ('dev_r4to2', pl == 4, pl == 2, rounds[rounds.player == 2])] return jobs # ---------------------------------------------------------------- 1a 跨組交叉 def run_cross(ctx, rng): a = ctx.args out = [] for W in a.windows: wins, F, rc, fold = ctx.windows(W) y = wins.cheat.to_numpy() for use_dt in (1, 0): cols = feat_cols(F['2'], use_dt) X = {g: F[g][cols].to_numpy() for g in CROSS_TEST} for tname, tgroups in CROSS_TRAIN.items(): oof = {g: np.full(len(y), np.nan) for g in CROSS_TEST} for k in range(a.folds): tr, te = np.where(fold != k)[0], np.where(fold == k)[0] Xtr = np.vstack([X[g][tr] for g in tgroups]) ytr = np.concatenate([y[tr]] * len(tgroups)) clf = gbdt_fit(Xtr, ytr, a.seed + k) for g in CROSS_TEST: oof[g][te] = logit(clf.predict_proba(X[g][te])[:, 1]) for g in CROSS_TEST: res = eval_splits(wins, oof[g], ctx.rounds, a, rng) out += summary_rows(dict(train=tname, test=g, W_ms=W, dt=use_dt), res) s0 = res[0][1] print(f' cross W={W} dt={use_dt} train {tname:>3} -> test {g:>2}: ' f'AUC {s0["win_auc"]:.3f} TPR@1% {s0["win_tpr@0.01"]:.3f} ' f'round recall@1% {s0.get("round_recall@1%", np.nan):.3f}') upsert(RESULTS / 'cross_group.csv', out, ['train', 'test', 'W_ms', 'dt', 'eval']) out = [] def gbdt_fit(Xtr, ytr, seed): from sklearn.ensemble import HistGradientBoostingClassifier clf = HistGradientBoostingClassifier(max_iter=200, learning_rate=0.1, l2_regularization=1.0, early_stopping=True, n_iter_no_change=10, random_state=seed) clf.fit(Xtr, ytr, sample_weight=balanced_weight(ytr)) return clf # ---------------------------------------------------------------- 1b 單一規則 + 邏輯斯迴歸 def run_rule(ctx, rng): a = ctx.args for W in a.windows: wins, F, rc, fold = ctx.windows(W) y = wins.cheat.to_numpy() pl = wins.player.to_numpy() out = [] for g in GROUPS: Fg = F[g] for f in Fg.columns: v = Fg[f].to_numpy() for name, sel in rec_splits(pl): if np.unique(v[sel]).size < 2: auc = 0.5 else: auc = roc_auc_score(y[sel], v[sel]) out.append(dict(group=g, W_ms=W, dt=int(f.startswith('t_')), feature=f, eval=name, kind='single', auc_raw=auc, auc_oriented=max(auc, 1 - auc), direction='higher=cheat' if auc >= 0.5 else 'lower=cheat')) for use_dt in (1, 0): cols = feat_cols(Fg, use_dt) Xg = Fg[cols].to_numpy() oof = np.full(len(y), np.nan) for k in range(a.folds): tr, te = np.where(fold != k)[0], np.where(fold == k)[0] m = make_pipeline(StandardScaler(), LogisticRegression(class_weight='balanced', max_iter=2000)) m.fit(Xg[tr], y[tr]) oof[te] = m.decision_function(Xg[te]) res = eval_splits(wins, oof, ctx.rounds, a, rng) for name, s, _ in res: out.append(dict(group=g, W_ms=W, dt=use_dt, feature='logreg', eval=name.replace('cv_', ''), kind='logreg', auc_raw=s.get('win_auc'), auc_oriented=s.get('win_auc'), direction='', win_tpr_1=s.get('win_tpr@0.01'), round_auc=s.get('round_auc'), round_recall_1=s.get('round_recall@1%'))) print(f' rule W={W} group {g:>2} dt={use_dt}: logreg AUC {res[0][1]["win_auc"]:.3f}') top = sorted([r for r in out if r['group'] == g and r['eval'] == 'all' and r['kind'] == 'single'], key=lambda r: -r['auc_oriented'])[:3] print(f' rule W={W} group {g:>2}: top single ' + ', '.join(f'{r["feature"]} {r["auc_oriented"]:.3f}' for r in top)) upsert(RESULTS / 'single_rule.csv', out, ['group', 'W_ms', 'dt', 'feature', 'eval']) # ---------------------------------------------------------------- 1c 固定門檻 def split_calib(rounds_df, frac, seed): """依 player × cheat 分層,回傳校準回合的 round_code 集合。""" rng = np.random.default_rng(seed) cal = set() for _, s in rounds_df.groupby(['player', 'cheat']): codes = round_code(s.player, s['round']) n = max(1, int(round(frac * len(codes)))) cal |= set(rng.choice(codes, n, replace=False).tolist()) return cal def round_means(rc, y, s): d = pd.DataFrame(dict(rc=rc, y=y, s=s)).groupby('rc').agg(y=('y', 'first'), s=('s', 'mean')) return d.index.to_numpy(), d.y.to_numpy(), d.s.to_numpy() def thresholds(y_cal, s_cal, rc_cal): """校準資料上的窗門檻與回合門檻(目標 FPR → 無作弊分數的上分位點)。""" neg = s_cal[y_cal == 0] _, ry, rs = round_means(rc_cal, y_cal, s_cal) rneg = rs[ry == 0] return ({f: float(np.quantile(neg, 1 - f)) for f in TARGET_FPR}, {f: float(np.quantile(rneg, 1 - f)) for f in TARGET_FPR}, len(rneg)) def apply_thr(y, s, rc, wthr, rthr): """回傳每個目標 FPR 的 (窗 FP, 窗 N, 窗 TP, 窗 P, 回合 FP, 回合 N, 回合 TP, 回合 P)。""" _, ry, rs = round_means(rc, y, s) out = {} for f in TARGET_FPR: out[f] = np.array([((s > wthr[f]) & (y == 0)).sum(), (y == 0).sum(), ((s > wthr[f]) & (y == 1)).sum(), (y == 1).sum(), ((rs > rthr[f]) & (ry == 0)).sum(), (ry == 0).sum(), ((rs > rthr[f]) & (ry == 1)).sum(), (ry == 1).sum()], dtype=float) return out def fixed_record(base, f, acc, n_cal_neg_rounds, fold_wfpr): wfp, wn, wtp, wp, rfp, rn, rtp, rp = acc lo, hi = clopper_pearson(int(rfp), int(rn)) if rn else (np.nan, np.nan) d = dict(**base, target_fpr=f, win_fpr=wfp / max(wn, 1), win_recall=wtp / max(wp, 1), round_fp=int(rfp), round_n_neg=int(rn), round_fpr=rfp / max(rn, 1), round_fpr_lo=lo, round_fpr_hi=hi, round_recall=rtp / max(rp, 1), n_calib_neg_rounds=n_cal_neg_rounds) if fold_wfpr: d['win_fpr_fold_min'] = float(np.min(fold_wfpr)) d['win_fpr_fold_max'] = float(np.max(fold_wfpr)) return d def run_fixed(ctx, rng): a = ctx.args for W in a.windows: wins, F, rc, fold = ctx.windows(W) y = wins.cheat.to_numpy() pl = wins.player.to_numpy() out = [] for g in GROUPS: for use_dt in (1, 0): X = F[g][feat_cols(F[g], use_dt)].to_numpy() # 同玩家交叉驗證:每折都從訓練回合切出校準回合 evs = ['cv_' + n for n, _ in rec_splits(pl)] acc = {e: {f: np.zeros(8) for f in TARGET_FPR} for e in evs} fold_wfpr = {f: [] for f in TARGET_FPR} ncal = [] for k in range(a.folds): tr_rounds = ctx.rounds[[ctx.fold_of[c] != k for c in round_code(ctx.rounds.player, ctx.rounds['round']).tolist()]] cal = split_calib(tr_rounds, CALIB_FRAC, a.seed + k) is_cal = np.isin(rc, list(cal)) tr = np.where((fold != k) & ~is_cal)[0] ca = np.where((fold != k) & is_cal)[0] te = np.where(fold == k)[0] clf = gbdt_fit(X[tr], y[tr], a.seed + k) s_ca = logit(clf.predict_proba(X[ca])[:, 1]) s_te = logit(clf.predict_proba(X[te])[:, 1]) wthr, rthr, nn = thresholds(y[ca], s_ca, rc[ca]) ncal.append(nn) for e, sel in [('cv_' + n, m) for n, m in rec_splits(pl[te])]: r = apply_thr(y[te][sel], s_te[sel], rc[te][sel], wthr, rthr) for f in TARGET_FPR: acc.setdefault(e, {ff: np.zeros(8) for ff in TARGET_FPR})[f] += r[f] if e == 'cv_all': fold_wfpr[f].append(r[f][0] / max(r[f][1], 1)) for e in acc: for f in TARGET_FPR: out.append(fixed_record(dict(group=g, W_ms=W, dt=use_dt, eval=e), f, acc[e][f], int(np.mean(ncal)), fold_wfpr[f] if e == 'cv_all' else None)) # 跨玩家 / 跨裝置:門檻只由訓練方的校準回合決定,鎖定後套到測試方 for name, trm, tem, _ in xfer_jobs(pl, ctx.rounds): tr_codes = set(rc[trm].tolist()) ra = ctx.rounds[np.isin(round_code(ctx.rounds.player, ctx.rounds['round']), list(tr_codes))] cal = split_calib(ra, CALIB_FRAC, a.seed) is_cal = np.isin(rc, list(cal)) tr = np.where(trm & ~is_cal)[0] ca = np.where(trm & is_cal)[0] te = np.where(tem)[0] clf = gbdt_fit(X[tr], y[tr], a.seed) wthr, rthr, nn = thresholds(y[ca], logit(clf.predict_proba(X[ca])[:, 1]), rc[ca]) r = apply_thr(y[te], logit(clf.predict_proba(X[te])[:, 1]), rc[te], wthr, rthr) for f in TARGET_FPR: out.append(fixed_record(dict(group=g, W_ms=W, dt=use_dt, eval=name), f, r[f], nn, None)) cv1 = [o for o in out if o['group'] == g and o['dt'] == use_dt and o['eval'] == 'cv_all' and o['target_fpr'] == 0.01][-1] xs = [o for o in out if o['group'] == g and o['dt'] == use_dt and o['eval'].startswith('lopo') and o['target_fpr'] == 0.01] print(f' fixed W={W} group {g:>2} dt={use_dt}: target 1% -> CV win FPR {cv1["win_fpr"]:.4f} ' f'recall {cv1["win_recall"]:.3f}; LOPO win FPR ' + ', '.join(f'{o["eval"][-1]} {o["win_fpr"]:.3f}' for o in xs)) upsert(RESULTS / 'fixed_threshold.csv', out, ['group', 'W_ms', 'dt', 'target_fpr', 'eval']) # ---------------------------------------------------------------- 1d OOF 分數 def run_oof(ctx, rng): a = ctx.args parts = [] for W in [w for w in a.windows if w in (50, 300)] or [300]: wins, F, rc, fold = ctx.windows(W) y = wins.cheat.to_numpy() for g in GROUPS: for use_dt in (1, 0): X = F[g][feat_cols(F[g], use_dt)].to_numpy() oof = np.full(len(y), np.nan) for k in range(a.folds): tr, te = np.where(fold != k)[0], np.where(fold == k)[0] oof[te] = fit_predict_gbdt(X[tr], y[tr], X[te], a.seed + k) d = wins[['player', 'round', 'cheat', 'strength', 'w0']].copy() d.insert(0, 'dt', use_dt) d.insert(0, 'W_ms', W) d.insert(0, 'group', g) d['score'] = oof parts.append(d) print(f' oof W={W} group {g:>2} dt={use_dt}: AUC {roc_auc_score(y, oof):.3f}') pd.concat(parts, ignore_index=True).to_csv(RESULTS / 'oof_scores.csv', index=False, float_format='%.6f') def main(): utf8_stdout() ap = argparse.ArgumentParser() ap.add_argument('what', choices=['all', 'cross', 'rule', 'fixed', 'oof']) ap.add_argument('--windows', nargs='+', type=int, default=FOCUS_W) ap.add_argument('--folds', type=int, default=N_FOLDS) ap.add_argument('--seed', type=int, default=0) ap.add_argument('--boot', type=int, default=200) args = ap.parse_args() t0 = time.time() rng = np.random.default_rng(args.seed) ctx = Ctx(args) todo = ['cross', 'rule', 'fixed', 'oof'] if args.what == 'all' else [args.what] for w in todo: print(f'== {w} ==', flush=True) {'cross': run_cross, 'rule': run_rule, 'fixed': run_fixed, 'oof': run_oof}[w](ctx, rng) print(f'total {time.time() - t0:.0f}s') if __name__ == '__main__': main()