494 lines
23 KiB
Python
494 lines
23 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""phase 2 時間窗消融:組別 × 窗長 × Δt 有無 × 模型(GBDT / 1D-CNN),由 phase_1/scripts_1/train_ablation.py 改寫。
|
||
|
||
與 phase 1 的差別:
|
||
- 交叉驗證以區塊切分(fold = blockIndex // 2,4 折),每折每份錄製各有無輔助 10、有輔助 10 回合。
|
||
- 評估:cv_all(4 份合併)、cv_r1–r4(各錄製)、lopo_A/B/C(留一位玩家:用其他人訓練)、
|
||
dev_r2to4 / dev_r4to2(同一人 B 的 125 Hz ↔ 1000 Hz)。
|
||
- 第零組(純手)是負對照。
|
||
- 干擾檢查:只用無輔助回合,分辨前 4 區塊與後 4 區塊。
|
||
|
||
範例:
|
||
python scripts_2/train_ablation.py --models gbdt --windows 8 300 # 冒煙測試
|
||
python scripts_2/train_ablation.py --models gbdt # GBDT 全網格
|
||
python scripts_2/train_ablation.py --models cnn # CNN(W ≥ 50 ms)
|
||
結果會累積寫進 phase_2/results/(同一設定重跑會覆蓋舊結果)。
|
||
"""
|
||
import argparse
|
||
import os
|
||
import time
|
||
from pathlib import Path
|
||
|
||
import numpy as np
|
||
import pandas as pd
|
||
from scipy.stats import beta
|
||
from sklearn.ensemble import HistGradientBoostingClassifier
|
||
from sklearn.metrics import balanced_accuracy_score, roc_auc_score
|
||
from sklearn.model_selection import StratifiedGroupKFold
|
||
|
||
from mtd_common import N_FOLDS, PERSON, PERSONS, PLAYERS, RESULTS, md_table, utf8_stdout
|
||
from mtd_windows import (WINDOWS_MS, CtxRows, GroupRows, context_features, load_rounds, load_segments,
|
||
make_windows, round_code, window_features, window_tensor)
|
||
|
||
GROUP_LABEL = {'0': '第零組 純手(負對照)', '1': '第一組 Unity', '2': '第二組 Raw+插入', '3': '第三組 Raw+平均', '3f': '第三組對照(幀時間插入)'}
|
||
FPRS = (0.001, 0.01, 0.05)
|
||
ROUND_FPR = 0.01
|
||
FIXED_SEG_MS = 2000
|
||
KEYS = ['group', 'W_ms', 'dt', 'model', 'segset', 'eval']
|
||
|
||
|
||
# ---------------------------------------------------------------- 指標
|
||
def logit(p):
|
||
p = np.clip(p, 1e-6, 1 - 1e-6)
|
||
return np.log(p / (1 - p))
|
||
|
||
|
||
def tpr_at_fpr(y, s, fpr):
|
||
neg = np.sort(s[y == 0])[::-1]
|
||
if len(neg) == 0 or (y == 1).sum() == 0:
|
||
return np.nan, np.nan
|
||
k = int(np.floor(fpr * len(neg)))
|
||
thr = neg[min(k, len(neg) - 1)]
|
||
return float(np.mean(s[y == 1] > thr)), thr
|
||
|
||
|
||
def weighted_auc_boot(y, s, grp, n_boot, rng):
|
||
"""以回合為單位、按類別分層的 bootstrap AUC(向量化:一次排序,每次只做 bincount)。"""
|
||
uniq, inv = np.unique(s, return_inverse=True)
|
||
U = len(uniq)
|
||
g_uniq, g_inv = np.unique(grp, return_inverse=True)
|
||
g_y = np.zeros(len(g_uniq))
|
||
g_y[g_inv] = y
|
||
pos_g, neg_g = np.where(g_y == 1)[0], np.where(g_y == 0)[0]
|
||
out = []
|
||
for _ in range(n_boot):
|
||
c = np.zeros(len(g_uniq))
|
||
np.add.at(c, rng.choice(pos_g, len(pos_g)), 1)
|
||
np.add.at(c, rng.choice(neg_g, len(neg_g)), 1)
|
||
w = c[g_inv]
|
||
ph = np.bincount(inv, w * y, minlength=U)
|
||
nh = np.bincount(inv, w * (1 - y), minlength=U)
|
||
below = np.cumsum(nh) - nh
|
||
P, N = ph.sum(), nh.sum()
|
||
if P > 0 and N > 0:
|
||
out.append(float((ph * (below + 0.5 * nh)).sum() / (P * N)))
|
||
return np.percentile(out, [2.5, 97.5]) if out else (np.nan, np.nan)
|
||
|
||
|
||
def clopper_pearson(k, n, a=0.05):
|
||
lo = 0.0 if k == 0 else beta.ppf(a / 2, k, n - k + 1)
|
||
hi = 1.0 if k == n else beta.ppf(1 - a / 2, k + 1, n - k)
|
||
return lo, hi
|
||
|
||
|
||
def evaluate(meta, score, all_rounds, n_boot, rng):
|
||
"""meta:每窗的 player/round/cheat/strength;score:logit。回傳 (摘要 dict, 各強度 list)。"""
|
||
y = meta.cheat.to_numpy()
|
||
rc = round_code(meta.player, meta['round'])
|
||
res = dict(n_win_pos=int((y == 1).sum()), n_win_neg=int((y == 0).sum()))
|
||
if res['n_win_pos'] == 0 or res['n_win_neg'] == 0:
|
||
return res, []
|
||
res['win_auc'] = roc_auc_score(y, score)
|
||
res['win_auc_lo'], res['win_auc_hi'] = weighted_auc_boot(y, score, rc, n_boot, rng)
|
||
res['win_bacc'] = balanced_accuracy_score(y, score > 0)
|
||
thr = {}
|
||
for f in FPRS:
|
||
res[f'win_tpr@{f:g}'], thr[f] = tpr_at_fpr(y, score, f)
|
||
# 回合層級:窗 logit 平均
|
||
rd = pd.DataFrame(dict(rc=rc, y=y, s=score, strength=meta.strength.to_numpy())).groupby('rc').agg(
|
||
y=('y', 'first'), s=('s', 'mean'), strength=('strength', 'first'), n=('s', 'size'))
|
||
ry, rs = rd.y.to_numpy(), rd.s.to_numpy()
|
||
res['n_round_pos'], res['n_round_neg'] = int((ry == 1).sum()), int((ry == 0).sum())
|
||
ar = all_rounds
|
||
res['coverage_pos'] = res['n_round_pos'] / max(int((ar.cheat == 1).sum()), 1)
|
||
res['coverage_neg'] = res['n_round_neg'] / max(int((ar.cheat == 0).sum()), 1)
|
||
if res['n_round_pos'] and res['n_round_neg']:
|
||
res['round_auc'] = roc_auc_score(ry, rs)
|
||
boots = []
|
||
pos_i, neg_i = np.where(ry == 1)[0], np.where(ry == 0)[0]
|
||
for _ in range(1000):
|
||
i = np.r_[rng.choice(pos_i, len(pos_i)), rng.choice(neg_i, len(neg_i))]
|
||
boots.append(roc_auc_score(ry[i], rs[i]))
|
||
res['round_auc_lo'], res['round_auc_hi'] = np.percentile(boots, [2.5, 97.5])
|
||
neg = np.sort(rs[ry == 0])[::-1]
|
||
k = int(np.floor(ROUND_FPR * len(neg)))
|
||
rthr = neg[min(k, len(neg) - 1)]
|
||
fp = int((rs[ry == 0] > rthr).sum())
|
||
res['round_thr_fp'] = fp
|
||
res['round_fpr'] = fp / len(neg)
|
||
res['round_fpr_lo'], res['round_fpr_hi'] = clopper_pearson(fp, len(neg))
|
||
res['round_recall@1%'] = float(np.mean(rs[ry == 1] > rthr))
|
||
else:
|
||
rthr = np.nan
|
||
per = []
|
||
st = meta.strength.to_numpy()
|
||
for s_ in sorted(set(st[y == 1].tolist())):
|
||
sel = st == s_
|
||
d = dict(strength=int(s_), n_win=int(sel.sum()), n_round=int(((rd.y == 1) & (rd.strength == s_)).sum()))
|
||
for f in FPRS:
|
||
d[f'win_tpr@{f:g}'] = float(np.mean(score[sel] > thr[f]))
|
||
rsel = (rd.y.to_numpy() == 1) & (rd.strength.to_numpy() == s_)
|
||
d['round_recall@1%'] = float(np.mean(rs[rsel] > rthr)) if rsel.any() and not np.isnan(rthr) else np.nan
|
||
per.append(d)
|
||
return res, per
|
||
|
||
|
||
# ---------------------------------------------------------------- 模型
|
||
def balanced_weight(y):
|
||
w = np.ones(len(y))
|
||
for c in (0, 1):
|
||
m = y == c
|
||
if m.any():
|
||
w[m] = 0.5 * len(y) / m.sum()
|
||
return w
|
||
|
||
|
||
def fit_predict_gbdt(Xtr, ytr, Xte, seed):
|
||
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 logit(clf.predict_proba(Xte)[:, 1])
|
||
|
||
|
||
def fit_predict_cnn(T, ytr_idx, te_idx, y, groups, seed, epochs, threads):
|
||
import torch
|
||
from torch import nn
|
||
torch.set_num_threads(threads)
|
||
torch.manual_seed(seed)
|
||
X, M, LN = T
|
||
|
||
class Net(nn.Module):
|
||
def __init__(self, c, h=32):
|
||
super().__init__()
|
||
self.conv = nn.Sequential(nn.Conv1d(c, h, 5, padding=2), nn.ReLU(),
|
||
nn.Conv1d(h, h, 5, padding=2), nn.ReLU(),
|
||
nn.Conv1d(h, h, 5, padding=2), nn.ReLU())
|
||
self.head = nn.Sequential(nn.Linear(2 * h + 1, 32), nn.ReLU(), nn.Linear(32, 1))
|
||
|
||
def forward(self, x, m, ln):
|
||
h = self.conv(x.transpose(1, 2))
|
||
mm = m[:, None, :]
|
||
cnt = mm.sum(-1)
|
||
mean = (h * mm).sum(-1) / cnt.clamp(min=1)
|
||
mx = h.masked_fill(mm == 0, -1e4).max(-1).values
|
||
mx = torch.where(cnt > 0, mx, torch.zeros_like(mx))
|
||
return self.head(torch.cat([mean, mx, ln[:, None]], 1)).squeeze(1)
|
||
|
||
# 從訓練回合切 10% 做 early stopping(依回合分)
|
||
rng = np.random.default_rng(seed)
|
||
tr_groups = np.unique(groups[ytr_idx])
|
||
val_g = set(rng.choice(tr_groups, max(1, len(tr_groups) // 10), replace=False).tolist())
|
||
is_val = np.array([g in val_g for g in groups[ytr_idx]])
|
||
tr, va = ytr_idx[~is_val], ytr_idx[is_val]
|
||
if len(np.unique(y[va])) < 2:
|
||
tr, va = ytr_idx, ytr_idx[:0]
|
||
tX, tM, tL = (torch.from_numpy(a) for a in (X, M, LN))
|
||
ty = torch.from_numpy(y.astype(np.float32))
|
||
npos, nneg = (y[tr] == 1).sum(), (y[tr] == 0).sum()
|
||
lossf = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(nneg / max(npos, 1), dtype=torch.float32))
|
||
net = Net(X.shape[2])
|
||
opt = torch.optim.Adam(net.parameters(), lr=2e-3)
|
||
bs = 512
|
||
best, best_state, bad = np.inf, None, 0
|
||
|
||
def predict(idx):
|
||
net.eval()
|
||
out = []
|
||
with torch.no_grad():
|
||
for i in range(0, len(idx), 4096):
|
||
j = torch.from_numpy(idx[i:i + 4096])
|
||
out.append(net(tX[j], tM[j], tL[j]).numpy())
|
||
return np.concatenate(out) if out else np.zeros(0)
|
||
|
||
for ep in range(epochs):
|
||
net.train()
|
||
perm = rng.permutation(tr)
|
||
for i in range(0, len(perm), bs):
|
||
j = torch.from_numpy(perm[i:i + bs])
|
||
opt.zero_grad()
|
||
loss = lossf(net(tX[j], tM[j], tL[j]), ty[j])
|
||
loss.backward()
|
||
opt.step()
|
||
if len(va):
|
||
with torch.no_grad():
|
||
vl = float(lossf(torch.from_numpy(predict(va)), ty[torch.from_numpy(va)]))
|
||
if vl < best - 1e-4:
|
||
best, bad = vl, 0
|
||
best_state = {k: v.clone() for k, v in net.state_dict().items()}
|
||
else:
|
||
bad += 1
|
||
if bad >= 3:
|
||
break
|
||
if best_state is not None:
|
||
net.load_state_dict(best_state)
|
||
return predict(te_idx)
|
||
|
||
|
||
# ---------------------------------------------------------------- 實驗流程
|
||
def assign_folds(rounds, n_folds=N_FOLDS, seed=0):
|
||
"""以區塊切分:fold = blockIndex // 2。每折每份錄製剛好 2 個區塊(無輔助 10、各強度 2)。"""
|
||
rc = round_code(rounds.player, rounds['round'])
|
||
fold = (rounds.blockIndex.to_numpy() * n_folds // 8).astype(int)
|
||
return dict(zip(rc.tolist(), fold.tolist()))
|
||
|
||
|
||
def assign_folds_random(rounds, n_folds, seed):
|
||
"""phase 1 的切法(依回合隨機分層),干擾檢查用。"""
|
||
y = rounds.player.to_numpy() * 2 + rounds.cheat.to_numpy()
|
||
rc = round_code(rounds.player, rounds['round'])
|
||
fold = np.full(len(rounds), -1)
|
||
sgkf = StratifiedGroupKFold(n_splits=n_folds, shuffle=True, random_state=seed)
|
||
for k, (_, te) in enumerate(sgkf.split(np.zeros(len(rounds)), y, rc)):
|
||
fold[te] = k
|
||
return dict(zip(rc.tolist(), fold.tolist()))
|
||
|
||
|
||
def run_config(model, data, meta, fold_of, rounds, args, rng, do_xfer=True):
|
||
"""回傳 list of (eval 名稱, 摘要, 各強度)。"""
|
||
y = meta.cheat.to_numpy()
|
||
rc = round_code(meta.player, meta['round'])
|
||
fold = np.array([fold_of[c] for c in rc.tolist()])
|
||
oof = np.full(len(y), np.nan)
|
||
for k in range(args.folds):
|
||
tr, te = np.where(fold != k)[0], np.where(fold == k)[0]
|
||
if len(te) == 0:
|
||
continue
|
||
if model == 'gbdt':
|
||
oof[te] = fit_predict_gbdt(data[tr], y[tr], data[te], args.seed + k)
|
||
else:
|
||
oof[te] = fit_predict_cnn(data, tr, te, y, rc, args.seed + k, args.epochs, args.threads)
|
||
out = []
|
||
pl = meta.player.to_numpy()
|
||
splits = [('cv_all', np.ones(len(y), bool), rounds)]
|
||
splits += [(f'cv_r{p}', pl == p, rounds[rounds.player == p]) for p in sorted(set(pl.tolist()))]
|
||
for name, sel, ar in splits:
|
||
s, p = evaluate(meta[sel], oof[sel], ar, args.boot, rng)
|
||
out.append((name, s, p))
|
||
if do_xfer and not args.no_xfer:
|
||
person = np.array([PERSON[p] for p in pl])
|
||
rperson = rounds.player.map(PERSON).to_numpy()
|
||
jobs = [(f'lopo_{q}', person != q, person == q, rperson == q) for q in PERSONS]
|
||
jobs += [('dev_r2to4', pl == 2, pl == 4, rounds.player.to_numpy() == 4),
|
||
('dev_r4to2', pl == 4, pl == 2, rounds.player.to_numpy() == 2)]
|
||
for name, trm, tem, rsel in jobs:
|
||
tr, te = np.where(trm)[0], np.where(tem)[0]
|
||
if not len(tr) or not len(te) or len(np.unique(y[tr])) < 2:
|
||
continue
|
||
if model == 'gbdt':
|
||
sc = fit_predict_gbdt(data[tr], y[tr], data[te], args.seed)
|
||
else:
|
||
sc = fit_predict_cnn(data, tr, te, y, rc, args.seed, args.epochs, args.threads)
|
||
s, p = evaluate(meta.iloc[te], sc, rounds[rsel], args.boot, rng)
|
||
out.append((name, s, p))
|
||
return out
|
||
|
||
|
||
def upsert(path, new, keys):
|
||
if not len(new):
|
||
return
|
||
new = pd.DataFrame(new)
|
||
if path.exists():
|
||
old = pd.read_csv(path)
|
||
k_old = old[keys].astype(str).agg('|'.join, axis=1)
|
||
k_new = set(new[keys].astype(str).agg('|'.join, axis=1))
|
||
old = old[~k_old.isin(k_new)]
|
||
new = pd.concat([old, new], ignore_index=True)
|
||
new.to_csv(path, index=False, float_format='%.6f', encoding='utf-8')
|
||
|
||
|
||
def nuisance_check(groups, rows_cache, segs, rounds, args, rng):
|
||
"""只用無輔助回合,標籤 = 後 4 個區塊。AUC 代表錄製時間的漂移可被學到的程度。
|
||
phase 2 交錯錄製,漂移與輔助標籤無關,所以這個數字只是描述漂移本身,不再代表主實驗的混淆。"""
|
||
nc = rounds[rounds.cheat == 0].copy()
|
||
late = dict(zip(round_code(nc.player, nc['round']).tolist(), (nc.blockIndex >= 4).astype(int).tolist()))
|
||
nc['cheat'] = (nc.blockIndex >= 4).astype(int)
|
||
fold_of = assign_folds_random(nc, 5, args.seed)
|
||
seg_nc = segs[segs.cheat == 0].copy()
|
||
seg_nc['cheat'] = [late[c] for c in round_code(seg_nc.player, seg_nc['round']).tolist()]
|
||
seg_nc['strength'] = 0
|
||
out = []
|
||
W = 300
|
||
wins = make_windows(seg_nc, W)
|
||
for g in groups:
|
||
sl = rows_cache[g].slice(wins)
|
||
F = window_features(sl, True)
|
||
for use_dt in (1, 0):
|
||
X = F.to_numpy() if use_dt else F[[c for c in F.columns if not c.startswith('t_')]].to_numpy()
|
||
a2 = argparse.Namespace(**{**vars(args), 'folds': 5})
|
||
res = run_config('gbdt', X, wins, fold_of, nc, a2, rng, do_xfer=False)
|
||
for name, s, _ in res:
|
||
out.append(dict(group=g, W_ms=W, dt=use_dt, eval=name, win_auc=s.get('win_auc'),
|
||
win_auc_lo=s.get('win_auc_lo'), win_auc_hi=s.get('win_auc_hi'),
|
||
round_auc=s.get('round_auc'), round_auc_lo=s.get('round_auc_lo'),
|
||
round_auc_hi=s.get('round_auc_hi')))
|
||
print(f' nuisance group {g} dt={use_dt}: window AUC {res[0][1].get("win_auc", np.nan):.3f}, '
|
||
f'round AUC {res[0][1].get("round_auc", np.nan):.3f}')
|
||
upsert(RESULTS / 'nuisance.csv', out, ['group', 'W_ms', 'dt', 'eval'])
|
||
|
||
|
||
# ---------------------------------------------------------------- 圖與摘要
|
||
SERIES = {'0': '#8a8984', '1': '#2a78d6', '2': '#eb6834', '3': '#1baf7a', '3f': '#eda100'} # 參考色盤前 4 槽,固定順序
|
||
|
||
|
||
def plot_auc(ab, path):
|
||
import matplotlib
|
||
matplotlib.use('Agg')
|
||
import matplotlib.pyplot as plt
|
||
from matplotlib import font_manager
|
||
for name in ['Microsoft JhengHei', 'Noto Sans CJK TC', 'PingFang TC', 'Microsoft YaHei']:
|
||
if any(f.name == name for f in font_manager.fontManager.ttflist):
|
||
plt.rcParams['font.family'] = name
|
||
break
|
||
plt.rcParams['axes.unicode_minus'] = False
|
||
INK, MUTED, GRID = '#0b0b0b', '#52514e', '#e4e3df'
|
||
d = ab[(ab['eval'] == 'cv_all') & (ab.segset == 'all')]
|
||
models = [m for m in ('gbdt', 'cnn') if (d.model == m).any()]
|
||
if not models:
|
||
return
|
||
fig, axes = plt.subplots(len(models), 2, figsize=(11, 3.9 * len(models)), sharey=True, squeeze=False)
|
||
for i, m in enumerate(models):
|
||
for j, use_dt in enumerate((1, 0)):
|
||
ax = axes[i, j]
|
||
sub = d[(d.model == m) & (d.dt == use_dt)]
|
||
ends = []
|
||
for g in ('0', '1', '2', '3', '3f'):
|
||
s = sub[sub.group.astype(str) == g].sort_values('W_ms')
|
||
if not len(s):
|
||
continue
|
||
ax.fill_between(s.W_ms, s.win_auc_lo, s.win_auc_hi, color=SERIES[g], alpha=0.10, linewidth=0)
|
||
ax.plot(s.W_ms, s.win_auc, color=SERIES[g], linewidth=2, solid_capstyle='round',
|
||
marker='o', markersize=5, markeredgecolor='white', markeredgewidth=1.5, label=GROUP_LABEL[g])
|
||
ends.append([s.win_auc.iloc[-1], g, s.W_ms.iloc[-1]])
|
||
# 末端標籤:依 y 排序後往下推開,避免重疊(間距以軸高比例計)
|
||
gap = (1.0 - np.nanmin(d[['win_auc', 'win_auc_lo']].to_numpy())) * 0.06
|
||
ends.sort(key=lambda e: -e[0])
|
||
prev = None
|
||
for e in ends:
|
||
e.append(e[0] if prev is None else min(e[0], prev - gap))
|
||
prev = e[-1]
|
||
for yv, g, xv, ylab in ends:
|
||
ax.annotate(g, (xv, yv), xytext=(xv * 1.12, ylab), textcoords='data',
|
||
va='center', fontsize=9, color=MUTED)
|
||
ax.set_xscale('log')
|
||
ticks = sorted(sub.W_ms.unique())
|
||
ax.set_xticks(ticks)
|
||
ax.set_xticklabels([str(int(t)) for t in ticks], fontsize=8, color=MUTED)
|
||
ax.minorticks_off()
|
||
ax.grid(True, color=GRID, linewidth=0.8)
|
||
for sp in ('top', 'right'):
|
||
ax.spines[sp].set_visible(False)
|
||
for sp in ('left', 'bottom'):
|
||
ax.spines[sp].set_color(GRID)
|
||
ax.tick_params(colors=MUTED)
|
||
ax.set_title(f'{m.upper()},{"含 Δt" if use_dt else "不含 Δt"}', fontsize=11, color=INK)
|
||
ax.set_xlabel('時間窗長度 (ms,對數刻度)', color=MUTED)
|
||
if j == 0:
|
||
ax.set_ylabel('窗層級 AUC(陰影 = 以回合 bootstrap 的 95% CI)', color=MUTED)
|
||
axes[0, 0].legend(frameon=False, fontsize=9, loc='lower right')
|
||
fig.tight_layout()
|
||
fig.savefig(path, dpi=180)
|
||
plt.close(fig)
|
||
|
||
|
||
def write_summary(args):
|
||
"""簡要摘要(完整報告由 report.py 產生)。"""
|
||
ab_p = RESULTS / 'ablation.csv'
|
||
if not ab_p.exists():
|
||
return
|
||
ab = pd.read_csv(ab_p)
|
||
ab['group'] = ab.group.astype(str)
|
||
plot_auc(ab, RESULTS / 'auc_vs_window.png')
|
||
L = ['# phase 2 時間窗消融(簡要)', '', f'更新時間 {time.strftime("%Y-%m-%d %H:%M:%S")}。完整報告見 `report.md`。', '']
|
||
for m in ('gbdt', 'cnn'):
|
||
for ev in ('cv_all', 'lopo_A', 'lopo_B', 'lopo_C', 'dev_r2to4', 'dev_r4to2'):
|
||
d = ab[(ab.model == m) & (ab['eval'] == ev) & (ab.segset == 'all')]
|
||
if not len(d):
|
||
continue
|
||
L.append(f'## {m.upper()} {ev}:窗層級 AUC')
|
||
L.append('')
|
||
piv = d.pivot_table(index='W_ms', columns=['group', 'dt'], values='win_auc')
|
||
piv.columns = [f'{g} {"Δt" if t else "無Δt"}' for g, t in piv.columns]
|
||
L += [md_table(piv.reset_index()), '']
|
||
(RESULTS / 'summary.md').write_text('\n'.join(L), encoding='utf-8')
|
||
print('summary written:', RESULTS / 'summary.md')
|
||
|
||
|
||
def main():
|
||
utf8_stdout()
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument('--groups', nargs='+', default=['0', '1', '2', '3', '3f'])
|
||
ap.add_argument('--windows', nargs='+', type=int, default=WINDOWS_MS)
|
||
ap.add_argument('--models', nargs='+', default=['gbdt'], choices=['gbdt', 'cnn'])
|
||
ap.add_argument('--dt', choices=['both', 'on', 'off'], default='both')
|
||
ap.add_argument('--units', choices=['deg', 'counts'], default='deg')
|
||
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, help='窗層級 AUC 的 bootstrap 次數')
|
||
ap.add_argument('--fixed-segments', action='store_true', help=f'只用 ≥ {FIXED_SEG_MS} ms 的片段')
|
||
ap.add_argument('--context', action='store_true', help='GBDT 額外加入遊戲情境特徵')
|
||
ap.add_argument('--no-xfer', action='store_true')
|
||
ap.add_argument('--no-nuisance', action='store_true')
|
||
ap.add_argument('--cnn-min-window', type=int, default=50)
|
||
ap.add_argument('--epochs', type=int, default=20)
|
||
ap.add_argument('--threads', type=int, default=6)
|
||
ap.add_argument('--summarize-only', action='store_true')
|
||
args = ap.parse_args()
|
||
RESULTS.mkdir(parents=True, exist_ok=True)
|
||
if args.summarize_only:
|
||
write_summary(args)
|
||
return
|
||
t_all = time.time()
|
||
rng = np.random.default_rng(args.seed)
|
||
segs, rounds = load_segments(), load_rounds()
|
||
fold_of = assign_folds(rounds, args.folds, args.seed)
|
||
pd.DataFrame(dict(round_code=list(fold_of), fold=list(fold_of.values()))).to_csv(RESULTS / 'folds.csv', index=False)
|
||
rows_cache = {g: GroupRows(g, args.units, rounds) for g in args.groups}
|
||
ctx_rows = CtxRows() if args.context else None
|
||
dts = {'both': (1, 0), 'on': (1,), 'off': (0,)}[args.dt]
|
||
segset = f'seg>={FIXED_SEG_MS}' if args.fixed_segments else 'all'
|
||
model_tag = lambda m: m + ('+ctx' if args.context and m == 'gbdt' else '') + ('' if args.units == 'deg' else '-counts')
|
||
for W in args.windows:
|
||
wins = make_windows(segs, W, FIXED_SEG_MS if args.fixed_segments else None)
|
||
print(f'W={W} ms: {len(wins):,} windows (cheat {int(wins.cheat.sum()):,})')
|
||
ctxF = context_features(ctx_rows, wins) if ctx_rows is not None else None
|
||
for g in args.groups:
|
||
sl = rows_cache[g].slice(wins)
|
||
F = window_features(sl, True) if 'gbdt' in args.models else None
|
||
for use_dt in dts:
|
||
for m in args.models:
|
||
if m == 'cnn' and W < args.cnn_min_window:
|
||
continue
|
||
t0 = time.time()
|
||
if m == 'gbdt':
|
||
cols = list(F.columns) if use_dt else [c for c in F.columns if not c.startswith('t_')]
|
||
X = F[cols]
|
||
if ctxF is not None:
|
||
X = pd.concat([X, ctxF], axis=1)
|
||
data = X.to_numpy()
|
||
else:
|
||
data = window_tensor(sl, bool(use_dt))
|
||
res = run_config(m, data, wins, fold_of, rounds, args, rng)
|
||
recs, pers = [], []
|
||
for name, s, per in res:
|
||
base = dict(group=g, W_ms=W, dt=use_dt, model=model_tag(m), segset=segset, eval=name)
|
||
recs.append({**base, **s})
|
||
pers += [{**base, **p} for p in per]
|
||
upsert(RESULTS / 'ablation.csv', recs, KEYS)
|
||
upsert(RESULTS / 'per_strength.csv', pers, KEYS + ['strength'])
|
||
fpr = [{k: r.get(k) for k in KEYS + ['n_round_pos', 'n_round_neg', 'round_thr_fp', 'round_fpr',
|
||
'round_fpr_lo', 'round_fpr_hi', 'round_recall@1%']} for r in recs]
|
||
upsert(RESULTS / 'fpr_ci.csv', fpr, KEYS)
|
||
s0 = res[0][1]
|
||
print(f' group {g:>2} dt={use_dt} {m}: win AUC {s0.get("win_auc", np.nan):.3f} '
|
||
f'[{s0.get("win_auc_lo", np.nan):.3f}, {s0.get("win_auc_hi", np.nan):.3f}] '
|
||
f'round AUC {s0.get("round_auc", np.nan):.3f} TPR@1%FPR {s0.get("[email protected]", np.nan):.3f} '
|
||
f'({time.time() - t0:.0f}s)')
|
||
if not args.no_nuisance and 'gbdt' in args.models and not args.fixed_segments:
|
||
nuisance_check(args.groups, rows_cache, segs, rounds, args, rng)
|
||
write_summary(args)
|
||
print(f'total {time.time() - t_all:.0f}s')
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|