Files
2026-12-01 22:00:26 +08:00

524 lines
26 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""時間窗消融:組別 × 窗長 × Δt 有無 × 模型(GBDT / 1D-CNN),交叉玩家、干擾檢查、FPR 導向的指標。
範例:
python scripts_1/train_ablation.py --models gbdt --windows 8 300 # 冒煙測試
python scripts_1/train_ablation.py --models gbdt # GBDT 全網格
python scripts_1/train_ablation.py --models cnn # CNN(W ≥ 50 ms)
python scripts_1/train_ablation.py --models gbdt --fixed-segments # 只用 ≥ 2 s 的片段
python scripts_1/train_ablation.py --summarize-only # 只重畫圖與 summary
結果會累積寫進 results_1/(同一設定重跑會覆蓋舊結果)。
"""
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 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 = {'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, seed):
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 = []
for name, sel in (('cv_all', np.ones(len(y), 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], oof[sel], ar, args.boot, rng)
out.append((name, s, p))
if do_xfer and not args.no_xfer:
for a, b in ((1, 2), (2, 1)):
tr = np.where(meta.player.to_numpy() == a)[0]
te = np.where(meta.player.to_numpy() == b)[0]
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[rounds.player == b], args.boot, rng)
out.append((f'xfer_p{a}to{b}', 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):
"""只用無作弊回合,標籤 = 回合編號 ≥ 100(後錄的一半)。AUC ≫ 0.5 代表錄製順序的漂移可被學到。"""
nc = rounds[rounds.cheat == 0].copy()
nc['cheat'] = (nc['round'] >= 100).astype(int)
fold_of = assign_folds(nc, args.folds, args.seed)
seg_nc = segs[segs.cheat == 0].copy()
seg_nc['cheat'] = (seg_nc['round'] >= 100).astype(int)
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()
res = run_config('gbdt', X, wins, fold_of, nc, args, 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 = {'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 ('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):
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 = ['# data_1 時間窗消融結果', '', f'更新時間 {time.strftime("%Y-%m-%d %H:%M:%S")}。原始數字在 `ablation.csv`、`per_strength.csv`、'
'`fpr_ci.csv`、`nuisance.csv`;圖在 `auc_vs_window.png`。', '',
'- 窗層級指標:每個時間窗一個樣本,5 折交叉驗證,同一回合的窗只會落在同一折。',
'- 回合層級:同回合所有窗的 logit 平均。門檻設在無作弊回合誤判 ≤ 1% 的位置,FPR 附 Clopper-Pearson 95% 信賴區間。',
'- 門檻是在被評估的資料上選的(ROC 操作點),實際部署要另外用保留資料定門檻。',
'- `W < 17 ms` 時第一組每窗只有 0–1 列(每幀一列),屬於退化情況。', '']
for m in ('gbdt', 'cnn'):
d = ab[(ab.model == m) & (ab['eval'] == 'cv_all') & (ab.segset == 'all')]
if not len(d):
continue
L.append(f'## {m.upper()}:窗層級 AUC(交叉驗證,全部片段)')
L.append('')
piv = d.pivot_table(index='W_ms', columns=['group', 'dt'], values='win_auc')
piv.columns = [f'{GROUP_LABEL.get(g, g)} {"Δt" if t else "無Δt"}' for g, t in piv.columns]
L += [md_table(piv.reset_index()), '']
L.append('各組最佳窗長,以及「最短而不輸最佳超過 1 個標準誤」的窗長(標準誤 ≈ 95% CI 寬 / 3.92):')
L.append('')
best = []
for (g, t), s in d.groupby(['group', 'dt']):
s = s.sort_values('W_ms')
b = s.loc[s.win_auc.idxmax()]
se = (b.win_auc_hi - b.win_auc_lo) / 3.92
short = s[s.win_auc >= b.win_auc - se].W_ms.min()
best.append(dict(組別=GROUP_LABEL.get(g, g), Δt='有' if t else '無', 最佳窗長=int(b.W_ms),
AUC=b.win_auc, CI=f'{b.win_auc_lo:.3f}–{b.win_auc_hi:.3f}', 一個SE內最短窗長=int(short),
回合AUC=b.get('round_auc', np.nan), 回合召回_FPR1=b.get('round_recall@1%', np.nan),
窗召回_FPR1=b.get('[email protected]', np.nan)))
L += [md_table(pd.DataFrame(best)), '']
fx = ab[(ab['eval'] == 'cv_all') & (ab.segset == f'seg>={FIXED_SEG_MS}')]
if len(fx):
L.append(f'## 固定片段集合(只用 ≥ {FIXED_SEG_MS} ms 的片段,各窗長樣本母體相同)')
L.append('')
piv = fx.pivot_table(index='W_ms', columns=['model', 'group', 'dt'], values='win_auc')
piv.columns = [f'{m} {g} {"Δt" if t else "無Δt"}' for m, g, t in piv.columns]
L += [md_table(piv.reset_index()), '']
xf = ab[ab['eval'].str.startswith('xfer') & (ab.segset == 'all')]
if len(xf):
L.append('## 交叉玩家(用一位玩家訓練、另一位測試):窗層級 AUC')
L.append('')
for (m, e), s in xf.groupby(['model', 'eval']):
L.append(f'**{m.upper()},玩家 {e[6]} 訓練 → 玩家 {e[-1]} 測試**')
L.append('')
piv = s.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()), '']
nu_p = RESULTS / 'nuisance.csv'
if nu_p.exists():
nu = pd.read_csv(nu_p)
nu = nu[nu['eval'] == 'cv_all']
L.append('## 干擾檢查:錄製順序')
L.append('')
L.append('只用無作弊回合,把回合 100–149 標為 1、50–99 標為 0,用同樣的特徵與流程訓練(W = 300 ms、GBDT)。'
'兩位玩家的作弊回合都是在 0–49 先錄完的,所以這個 AUC 越高,代表「時間漂移」越可能被主實驗當成作弊特徵。'
'「含 Δt」的特徵也包含速度、加速度等運動學量,所以它和「無 Δt」的差距不只是時間戳本身。'
'無作弊回合在第二、三組完全相同,所以這三組的干擾檢查數字一樣。')
L.append('')
L += [md_table(nu[['group', 'dt', 'win_auc', 'win_auc_lo', 'win_auc_hi', 'round_auc']]), '']
L += ['## 已知限制', '',
'- 兩位玩家都是先錄 50 回合作弊(強度 20→100 遞增),再錄 100 回合無作弊,錄製順序與標籤完全相關。建議 data_2、data_3 交錯錄製。',
'- 兩位玩家的武器、地圖、靈敏度全不同,玩家身分與設定無法拆開;交叉玩家結果是泛化的粗略參考。',
'- 玩家 2 的作弊回合平均 FPS 略高(64.6 vs 63.2),第一組的 Δt 是幀間隔,可能帶到這個與外掛無關的差異;看第一組時以「無 Δt」為準。',
'- 共 200 回合無作弊時,就算全部判對,回合層級 FPR 的 95% 上界也約 1.5%;窗數雖多,但同回合的窗彼此相關,不能當獨立樣本。',
'- 每個強度只有約 20 回合,各強度的召回率波動大。',
'- 警訊:第一組含 Δt 時,強度 20 的召回率反而高於強度 80/100(`per_strength.csv`,W = 50 ms:1.00 vs 0.70)。'
'外掛越強應該越好抓,反過來代表模型抓到的是「最早錄的回合」的特徵(幀時間、手感漂移),不是外掛本身。', '']
(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=['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=5)
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()