# -*- coding: utf-8 -*- """把 phase 2 的結果整理成 results/report_tables.md(只讀 csv,不訓練)。 各節:資料概況、任務效益、主結果(窗長 × 組別)、各錄製、純手負對照、各強度、 phase 1 對照(玩家 B)、錄製順序干擾、留一位玩家與跨裝置、固定門檻、跨組、單一特徵。 用法:python phase_2/scripts_2/report.py """ import time import numpy as np import pandas as pd from mtd_common import DATA, PHASE1_RESULTS, PLAYERS, REC_LABEL, RESULTS, md_table, utf8_stdout from mtd_windows import load_rounds GL = {'0': '0 純手', '1': '1 每幀彙總', '2': '2 逐筆+每幀插入', '3': '3 逐筆+平均分配', '3f': '3f 對照'} FOCUS = [50, 300, 1000] def read(name): p = RESULTS / name if not p.exists(): return None d = pd.read_csv(p) if 'group' in d.columns: d['group'] = d.group.astype(str) return d def dtag(t): return '含Δt' if t else '無Δt' def benefit(rounds): rows = [] for _, r in rounds.iterrows(): e = pd.read_csv(DATA / PLAYERS[int(r.player)] / f'events_{int(r["round"])}.csv') shots = int((e.type == 'shot').sum()) hits = int((e.type == 'hit').sum()) t0 = e.loc[e.type == 'round_start', 't'] tk = e.loc[e.type == 'kill', 't'] rows.append(dict(player=int(r.player), strength=int(r.strength), hit_rate=hits / shots if shots else np.nan, ttk=float(tk.iloc[0] - t0.iloc[0]) if len(tk) and len(t0) else np.nan)) d = pd.DataFrame(rows) a = d.groupby(['player', 'strength']).agg(n=('ttk', 'size'), hit_rate=('hit_rate', 'mean'), ttk=('ttk', 'mean')).reset_index() base = a[a.strength == 0].set_index('player') a['hit_gain'] = a.hit_rate - a.player.map(base.hit_rate) a['ttk_ratio'] = a.ttk / a.player.map(base.ttk) return a def main(): utf8_stdout() rounds = load_rounds() ab = read('ablation.csv') ps = read('per_strength.csv') L = ['# phase 2 結果表', '', f'產生時間 {time.strftime("%Y-%m-%d %H:%M:%S")}(`scripts_2/report.py`)。', '', '- 交叉驗證以區塊切分(fold = blockIndex // 2,4 折),同一回合的窗只在同一折。', '- 窗層級「召回@1%」的門檻是在被評估資料上回溯選的 ROC 操作點;事先決定門檻的結果見「固定門檻」。', '- 錄製:' + ';'.join(f'r{k} = {v}' for k, v in REC_LABEL.items()) + '。r2 與 r4 是同一人(B)。', ''] # ---- 資料概況 L += ['## 1. 資料概況(正式回合)', ''] d = rounds.groupby(['player', 'person', 'cheat']).agg( 回合=('round', 'size'), 遊玩秒=('play_seconds', 'sum'), 瞄準秒=('aim_seconds', 'sum'), 片段=('n_segments', 'sum'), FPS=('fps', 'mean'), 回報週期ms=('poll_period_ms', 'first')).reset_index() L += [md_table(d, '{:.1f}'), ''] # ---- 任務效益 L += ['## 2. 輔助的任務效益', '', '命中率 = 命中 / 開槍(每回合平均);擊倒時間比 = 該強度 / 同錄製無輔助。', ''] b = benefit(rounds) piv = b.pivot_table(index='strength', columns='player', values=['hit_rate', 'ttk_ratio']) piv.columns = [f'{"命中率" if v == "hit_rate" else "擊倒時間比"} r{p}' for v, p in piv.columns] L += [md_table(piv.reset_index()), ''] if ab is None: (RESULTS / 'report_tables.md').write_text('\n'.join(L), encoding='utf-8') return g = ab[(ab.model == 'gbdt') & (ab.segset == 'all')] # ---- 主結果 L += ['## 3. 窗層級 AUC 對窗長(4 份錄製合併,區塊交叉驗證)', ''] for metric, name in (('win_auc', 'AUC'), ('win_tpr@0.01', '召回@誤判1%')): d = g[g['eval'] == 'cv_all'].pivot_table(index='W_ms', columns=['group', 'dt'], values=metric) d.columns = [f'{GL[c]} {dtag(t)}' for c, t in d.columns] L += [f'**{name}**', '', md_table(d.reset_index()), ''] d = g[(g['eval'] == 'cv_all') & g.W_ms.isin(FOCUS)][ ['W_ms', 'group', 'dt', 'win_auc', 'win_auc_lo', 'win_auc_hi', 'win_tpr@0.001', 'win_tpr@0.01', 'win_tpr@0.05', 'round_auc', 'round_recall@1%', 'round_fpr', 'round_fpr_hi', 'n_round_neg']].sort_values(['W_ms', 'group', 'dt']) d['group'] = d.group.map(GL) L += ['**焦點窗長的完整指標**', '', md_table(d), ''] # ---- 各錄製 L += ['## 4. 各錄製分開看(W = 300 ms,召回@誤判1% / AUC)', ''] d = g[(g.W_ms == 300) & g['eval'].str.match(r'cv_r\d')].copy() d['cell'] = d.apply(lambda r: f'{r["win_tpr@0.01"]:.3f} / {r.win_auc:.3f}', axis=1) piv = d.pivot_table(index=['group', 'dt'], columns='eval', values='cell', aggfunc='first').reset_index() piv['group'] = piv.group.map(GL) piv['dt'] = piv.dt.map(dtag) piv.columns = [REC_LABEL.get(int(c[-1]), c) if str(c).startswith('cv_r') else c for c in piv.columns] L += [md_table(piv), ''] # ---- 純手負對照 L += ['## 5. 純手負對照(第零組:只有玩家自己的滑鼠,不含任何外掛修正)', '', 'AUC 越高,代表玩家在有輔助回合的手部動作本身就不同(閉迴路反應,以及準心變色後知道有輔助)。', ''] d = g[(g.group == '0')].pivot_table(index='W_ms', columns=['eval', 'dt'], values='win_auc') keep = [c for c in d.columns if c[0] in ('cv_all', 'cv_r1', 'cv_r2', 'cv_r3', 'cv_r4', 'lopo_A', 'lopo_B', 'lopo_C')] d = d[keep] d.columns = [f'{e} {dtag(t)}' for e, t in d.columns] L += [md_table(d.reset_index()), ''] d = g[(g.group == '0') & (g.W_ms == 300)][['eval', 'dt', 'win_auc', 'round_auc', 'win_tpr@0.01', 'round_recall@1%']] L += ['W = 300 ms:', '', md_table(d), ''] # ---- 各強度 if ps is not None: p = ps[(ps.model == 'gbdt') & (ps.segset == 'all')] for W in (50, 300): L += [f'## 6. 各強度的窗召回率(W = {W} ms,誤判率 1%,門檻由全部無輔助窗決定)', ''] d = p[(p.W_ms == W) & (p['eval'] == 'cv_all')].pivot_table(index=['group', 'dt'], columns='strength', values='win_tpr@0.01').reset_index() d['group'] = d.group.map(GL) d['dt'] = d.dt.map(dtag) L += ['**4 份合併**', '', md_table(d), ''] for ev in ('cv_r1', 'cv_r2', 'cv_r3', 'cv_r4'): d = p[(p.W_ms == W) & (p['eval'] == ev) & p.group.isin(['1', '2', '3'])].pivot_table( index=['group', 'dt'], columns='strength', values='win_tpr@0.01').reset_index() d['group'] = d.group.map(GL) d['dt'] = d.dt.map(dtag) L += [f'**{REC_LABEL[int(ev[-1])]}**', '', md_table(d), ''] # ---- phase 1 對照 p1 = PHASE1_RESULTS / 'ablation.csv' if p1.exists(): a1 = pd.read_csv(p1) a1['group'] = a1.group.astype(str) a1 = a1[(a1.model == 'gbdt') & (a1.segset == 'all') & (a1['eval'] == 'cv_p1')] a2 = g[g['eval'] == 'cv_r2'] L += ['## 7. phase 1 對照:玩家 B(phase 1 玩家 1 → phase 2 r2,同為 Basement、Uzi、60 FPS、125 Hz)', '', 'phase 1 先錄有輔助、後錄無輔助,交叉驗證依回合隨機切分;phase 2 交錯錄製,依區塊切分。', ''] rows = [] for W in FOCUS: for gr in ('1', '2', '3'): for t in (1, 0): x1 = a1[(a1.W_ms == W) & (a1.group == gr) & (a1.dt == t)] x2 = a2[(a2.W_ms == W) & (a2.group == gr) & (a2.dt == t)] if not len(x1) or not len(x2): continue rows.append(dict(W_ms=W, 組別=GL[gr], Δt=dtag(t), AUC_phase1=x1.win_auc.iat[0], AUC_phase2=x2.win_auc.iat[0], 召回1_phase1=x1['win_tpr@0.01'].iat[0], 召回1_phase2=x2['win_tpr@0.01'].iat[0], 回合AUC_phase1=x1.round_auc.iat[0], 回合AUC_phase2=x2.round_auc.iat[0])) L += [md_table(pd.DataFrame(rows)), ''] ps1 = PHASE1_RESULTS / 'per_strength.csv' if ps1.exists() and ps is not None: q1 = pd.read_csv(ps1) q1['group'] = q1.group.astype(str) q1 = q1[(q1.model == 'gbdt') & (q1.segset == 'all') & (q1['eval'] == 'cv_p1') & (q1.W_ms == 300)] q2 = ps[(ps.model == 'gbdt') & (ps.segset == 'all') & (ps['eval'] == 'cv_r2') & (ps.W_ms == 300)] rows = [] for gr in ('1', '2', '3'): for t in (1, 0): for lab, q in (('phase 1', q1), ('phase 2', q2)): s = q[(q.group == gr) & (q.dt == t)].set_index('strength')['win_tpr@0.01'] rows.append({'組別': GL[gr], 'Δt': dtag(t), '階段': lab, **{str(k): s.get(k, np.nan) for k in (20, 40, 60, 80, 100)}}) L += ['玩家 B 各強度的窗召回率(W = 300 ms,誤判率 1%):', '', md_table(pd.DataFrame(rows)), ''] # ---- 干擾 nu = read('nuisance.csv') if nu is not None: nu = nu[nu['eval'] == 'cv_all'] L += ['## 8. 錄製時間漂移(只用無輔助回合,分辨前 4 區塊與後 4 區塊,W = 300 ms)', '', 'phase 2 交錯錄製,這個漂移與輔助標籤無關;數字只描述漂移本身的大小。', ''] n1p = PHASE1_RESULTS / 'nuisance.csv' if n1p.exists(): n1 = pd.read_csv(n1p) n1 = n1[n1['eval'] == 'cv_all'] n1['group'] = n1.group.astype(str) nu = nu.merge(n1[['group', 'dt', 'win_auc', 'round_auc']], on=['group', 'dt'], how='left', suffixes=('', '_phase1')) nu['group'] = nu.group.map(GL) L += [md_table(nu.drop(columns=['W_ms', 'eval'], errors='ignore')), ''] # ---- 留一位玩家與跨裝置 L += ['## 9. 留一位玩家(用其他人訓練)與跨裝置(B 的 125 Hz ↔ 1000 Hz)', ''] for metric, name in (('win_auc', '窗層級 AUC'), ('win_tpr@0.01', '召回@誤判1%(門檻由測試方回溯選)')): d = g[g['eval'].str.match(r'(lopo|dev)_') & g.W_ms.isin(FOCUS)].pivot_table( index=['W_ms', 'group', 'dt'], columns='eval', values=metric).reset_index() d['group'] = d.group.map(GL) d['dt'] = d.dt.map(dtag) L += [f'**{name}**', '', md_table(d), ''] # ---- 固定門檻 fx = read('fixed_threshold.csv') if fx is not None: for W in sorted(fx.W_ms.unique()): d = fx[(fx.W_ms == W) & (fx.target_fpr == 0.01)].copy() d['cell'] = d.apply(lambda r: f'{r.win_fpr:.3f} / {r.win_recall:.3f}', axis=1) piv = d.pivot_table(index=['group', 'dt'], columns='eval', values='cell', aggfunc='first').reset_index() piv['group'] = piv.group.map(GL) piv['dt'] = piv.dt.map(dtag) order = ['group', 'dt'] + [c for c in ('cv_all', 'cv_r1', 'cv_r2', 'cv_r3', 'cv_r4', 'lopo_A', 'lopo_B', 'lopo_C', 'dev_r2to4', 'dev_r4to2') if c in piv.columns] L += [f'## 10. 固定門檻(W = {W} ms,目標窗誤判率 1%):實測窗誤判率 / 窗召回', '', '門檻只由訓練方的校準回合(30%)決定,鎖定後套到測試方。', '', md_table(piv[order]), ''] # ---- 跨組 cg = read('cross_group.csv') if cg is not None: d = cg[cg['eval'] == 'cv_all'].copy() d['cell'] = d.apply(lambda r: f'{r.win_auc:.3f} / {r["win_tpr@0.01"]:.3f}', axis=1) piv = d.pivot_table(index=['W_ms', 'dt', 'train'], columns='test', values='cell', aggfunc='first').reset_index() piv['dt'] = piv.dt.map(dtag) L += ['## 11. 偵測器 × 外掛送出方式(AUC / 召回@誤判1%)', '', '訓練「2」= 只見過每幀插入(A0);「2+3」= 兩種一起訓練(A1)。測試欄是外掛的送出方式。', '', md_table(piv), ''] # ---- 單一特徵 sr = read('single_rule.csv') if sr is not None: L += ['## 12. 單一特徵直接當分數(不訓練),W = 300 ms,前 5 名', ''] d = sr[(sr.kind == 'single') & (sr['eval'] == 'all') & (sr.W_ms == 300)] rows = [] for gr in ('0', '1', '2', '3', '3f'): s = d[d.group == gr].sort_values('auc_oriented', ascending=False).head(5) for i, r in enumerate(s.itertuples(), 1): rows.append(dict(組別=GL[gr], 名次=i, 特徵=r.feature, AUC=r.auc_oriented, 方向=r.direction)) L += [md_table(pd.DataFrame(rows)), ''] lr = sr[(sr.kind == 'logreg') & (sr.W_ms == 300)].pivot_table(index=['group', 'dt'], columns='eval', values='auc_raw').reset_index() lr['group'] = lr.group.map(GL) lr['dt'] = lr.dt.map(dtag) L += ['邏輯斯迴歸(W = 300 ms)AUC:', '', md_table(lr), ''] (RESULTS / 'report_tables.md').write_text('\n'.join(L), encoding='utf-8') print('wrote', RESULTS / 'report_tables.md') if __name__ == '__main__': main()