312 lines
15 KiB
Python
312 lines
15 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""第四章補跑實驗(data_1)。與 train_ablation.py 共用同一批窗、同一批 fold、同一套指標。
|
||
|
||
子命令:
|
||
cross 跨組交叉:用第二組(A0)、第三組、第二+第三組(A1)訓練,測第二組(B0)、第三組(B1)、對照組
|
||
rule 單一特徵不訓練的 AUC,以及邏輯斯迴歸
|
||
fixed 固定門檻:訓練回合切 30% 當校準回合定門檻,再到測試回合量實際誤判率;另做跨玩家
|
||
oof 焦點設定(W = 50、300)的 out-of-fold 分數,給 ROC 圖與回合分數圖用
|
||
all 以上全部
|
||
|
||
範例:
|
||
python scripts_1/extra_experiments.py all
|
||
python scripts_1/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 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 = ['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 eval_splits(meta, score, rounds, args, rng):
|
||
out = []
|
||
for name, sel in (('cv_all', np.ones(len(meta), bool)), ('cv_p1', meta.player.to_numpy() == 1),
|
||
('cv_p2', meta.player.to_numpy() == 2)):
|
||
ar = rounds if name == 'cv_all' else rounds[rounds.player == int(name[-1])]
|
||
s, p = evaluate(meta[sel], score[sel], ar, args.boot, rng)
|
||
out.append((name, s, p))
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------- 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["[email protected]"]:.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 (('all', np.ones(len(y), bool)), ('p1', pl == 1), ('p2', pl == 2)):
|
||
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('[email protected]'),
|
||
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()
|
||
# 同玩家交叉驗證:每折都從訓練回合切出校準回合
|
||
acc = {e: {f: np.zeros(8) for f in TARGET_FPR} for e in ('cv_all', 'cv_p1', 'cv_p2')}
|
||
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_all', np.ones(len(te), bool)), ('cv_p1', pl[te] == 1),
|
||
('cv_p2', pl[te] == 2)):
|
||
r = apply_thr(y[te][sel], s_te[sel], rc[te][sel], wthr, rthr)
|
||
for f in TARGET_FPR:
|
||
acc[e][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 pa, pb in ((1, 2), (2, 1)):
|
||
ra = ctx.rounds[ctx.rounds.player == pa]
|
||
cal = split_calib(ra, CALIB_FRAC, a.seed)
|
||
is_cal = np.isin(rc, list(cal))
|
||
tr = np.where((pl == pa) & ~is_cal)[0]
|
||
ca = np.where((pl == pa) & is_cal)[0]
|
||
te = np.where(pl == pb)[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=f'xfer_p{pa}to{pb}'), 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]
|
||
x12 = [o for o in out if o['group'] == g and o['dt'] == use_dt and o['eval'] == 'xfer_p1to2'
|
||
and o['target_fpr'] == 0.01][-1]
|
||
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}; P1->P2 win FPR {x12["win_fpr"]:.3f} recall {x12["win_recall"]:.3f}')
|
||
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=5)
|
||
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()
|