階段二分析

This commit is contained in:
Sahik committed 2026-12-02 02:58:04 +08:00
1 parent 1b00d27da6
commit 370e430173
37 files changed
+4092565

No files matched your search

+487
View File
@@ -0,0 +1,487 @@
# -*- coding: utf-8 -*-
"""產生 phase 2 的各組資料與共用表,並寫出驗證報告(由 phase_1/scripts_1/build_groups.py 改寫)。
第零組 純手:只有真實回報,不加外掛修正(負對照:有無輔助的差異只剩玩家自己的反應)
第一組 Unity Input System:每幀一列,dx = 該幀滑鼠總和 + 該幀外掛修正(整數)
第二組 Raw Input + 每幀插入:真實回報原樣,外掛修正在幀時間插入一列
第三組 Raw Input + 平均補償:外掛修正均分到該幀的真實回報;該幀沒有回報時沿滑鼠輪詢相位合成回報
第三組對照版(rows_frameinsert.csv):無回報幀改在幀時間插入一列
用法:python phase_2/scripts_2/build_groups.py [--seed 0]
"""
import argparse
import time
import numpy as np
import pandas as pd
from mtd_common import (COMMON, DATA, DERIVED, GRID_TOL_FRAC, GROUPS, PERSON, PLAYERS, ROW_COLS, SYNTH_SPAN_S,
aim_segments, carry_round, frame_prev_t, group_path, iter_rounds, load_round, md_table,
to_deg, utf8_stdout)
CTX_COLS = ['truth_detected', 'truth_visible', 'truth_err_x', 'truth_err_y', 'truth_screen_x',
'truth_screen_y', 'recoil_x', 'recoil_y', 'view_yaw', 'view_pitch', 'vx', 'vy', 'vz',
'bvx', 'bvy', 'bvz', 'state', 'bot_hp', 'ammo', 'reloading']
WINDOWS_MS = [8, 16, 33, 50, 100, 200, 300, 500, 1000, 2000]
def poll_model(time_arrays):
"""由同一位玩家所有回合的真實回報估計輪詢週期 P(秒)與到達抖動的樣本池(秒)。
回報率是滑鼠的屬性,所以每位玩家估一次;單一回合回報太少時(手幾乎沒動)中位數會失準。"""
g = np.concatenate([np.diff(rt) for rt in time_arrays if len(rt) > 1] or [np.zeros(0)])
g = g[g > 1e-5]
if len(g) < 3:
return 0.008, np.zeros(1)
p0 = np.median(g)
near = g[np.abs(g - p0) < 0.25 * p0]
if len(near) < 2:
return p0, np.zeros(1)
p = near.mean()
# 相鄰間隔的殘差 = 兩次到達抖動相減,單次抖動的標準差約為它的 1/√2
return p, (near - p) / np.sqrt(2.0)
def synth_ticks(f, t_f, t_prev, rt, period, eps_pool, rng):
"""沿真實回報的輪詢相位,產生落在 (max(t_prev, t_f-40ms), t_f] 的合成回報時間。"""
hi = t_f
lo = max(t_prev, t_f - SYNTH_SPAN_S)
if len(rt):
a = np.searchsorted(rt, hi, side='right') - 1
base = rt[a] if a >= 0 else rt[0]
else:
base = lo + period / 2
kmin = int(np.ceil((lo - base) / period))
kmax = int(np.floor((hi - base) / period))
if kmax < kmin:
return np.empty(0)
k = np.arange(kmin, kmax + 1)
ticks = base + k * period + rng.choice(eps_pool, size=len(k))
ticks = ticks[(ticks > lo) & (ticks <= hi)]
if len(rt) and len(ticks):
j = np.searchsorted(rt, ticks)
d_left = np.abs(ticks - rt[np.clip(j - 1, 0, len(rt) - 1)])
d_right = np.abs(rt[np.clip(j, 0, len(rt) - 1)] - ticks)
ticks = ticks[np.minimum(d_left, d_right) >= 0.5 * period]
return np.sort(ticks)
def build_g3(nF, tF, prevF, ax, ay, mf, mt, mdx, mdy, mleft, left_frame, mode, rng, poll):
"""第三組:回傳 (真實列加上的修正 ex, ey)、合成列 list、每幀殘值最大值。"""
ex = np.zeros(len(mt), dtype=np.int64)
ey = np.zeros(len(mt), dtype=np.int64)
synth = [] # (frame, t, dx, dy, left)
if not (np.any(ax != 0) or np.any(ay != 0)):
return ex, ey, synth, 0.0, 0
period, eps_pool = poll
first = np.searchsorted(mf, np.arange(nF), side='left')
last = np.searchsorted(mf, np.arange(nF), side='right')
accx = accy = 0.0
max_acc = 0.0
tickless = 0
for f in range(nF):
a_x, a_y = ax[f], ay[f]
s, e = first[f], last[f]
n = e - s
if n >= 1:
if a_x == 0 and a_y == 0 and abs(accx) < 0.5 and abs(accy) < 0.5:
continue
sx, sy = a_x / n, a_y / n
for i in range(s, e):
accx += sx
accy += sy
vx = np.floor(accx + 0.5)
vy = np.floor(accy + 0.5)
accx -= vx
accy -= vy
ex[i] += int(vx)
ey[i] += int(vy)
else:
if a_x == 0 and a_y == 0 and abs(accx) < 0.5 and abs(accy) < 0.5:
continue
if mode == 'frame':
ticks = np.array([tF[f]])
else:
ticks = synth_ticks(f, tF[f], prevF[f], mt, period, eps_pool, rng)
k = len(ticks)
if k == 0:
accx += a_x
accy += a_y
tickless += 1
else:
sx, sy = a_x / k, a_y / k
for tk in ticks:
accx += sx
accy += sy
vx = np.floor(accx + 0.5)
vy = np.floor(accy + 0.5)
accx -= vx
accy -= vy
if vx != 0 or vy != 0:
synth.append((f, tk, int(vx), int(vy), left_frame[f]))
max_acc = max(max_acc, abs(accx), abs(accy))
return ex, ey, synth, max_acc, tickless
def frame_sums(frame, v, nF):
return np.bincount(frame, weights=v, minlength=nF).round().astype(np.int64)
def build_round(player, idx, seed, poll):
cfg, fr, ms, ev = load_round(player, idx)
rng = np.random.default_rng([seed, player, idx])
sens = float(cfg['sensitivity'])
cheat = int(cfg['assistMode'] == 1)
strength = int(cfg['assistStrength'])
nF = len(fr)
tF = fr['t'].to_numpy()
prevF = frame_prev_t(fr)
f_mdx = fr['mouse_dx'].to_numpy().astype(np.int64)
f_mdy = fr['mouse_dy'].to_numpy().astype(np.int64)
ax = fr['assist_dx'].to_numpy(dtype=np.float64)
ay = fr['assist_dy'].to_numpy(dtype=np.float64)
A, residA = carry_round(ax)
B, residB = carry_round(ay)
aim, seg, segs = aim_segments(fr)
# 真實回報
ms = ms.sort_values(['frame', 't'], kind='mergesort')
mf_all = ms['frame'].to_numpy().astype(np.int64)
ok = (mf_all >= 0) & (mf_all < nF)
ms = ms[ok]
mf = ms['frame'].to_numpy().astype(np.int64)
mt = ms['t'].to_numpy()
mdx = ms['dx'].to_numpy().astype(np.int64)
mdy = ms['dy'].to_numpy().astype(np.int64)
mleft = ms['left'].to_numpy().astype(np.int64)
lastidx = np.searchsorted(mf, np.arange(nF), side='right') - 1
left_frame = np.where(lastidx >= 0, mleft[np.clip(lastidx, 0, None)], 0)
has_real = np.bincount(mf, minlength=nF) > 0
# 以滑鼠檔為準(暫停恢復的那一幀,遊戲可能丟掉幾筆回報,frames.mouse_dx 會比較小)
raw_fx = frame_sums(mf, mdx, nF)
raw_fy = frame_sums(mf, mdy, nF)
n_frame_mismatch = int(((raw_fx != f_mdx) | (raw_fy != f_mdy)).sum())
f_mdx, f_mdy = raw_fx, raw_fy
base = dict(player=player, round=idx, cheat=cheat, strength=strength)
def finish(df):
df = df.sort_values(['frame', 'src', 't'], kind='mergesort').reset_index(drop=True)
t = df['t'].to_numpy()
dt = np.empty_like(t)
if len(t):
dt[0] = t[0] - prevF[df['frame'].iat[0]]
dt[1:] = np.diff(t)
df['dt'] = dt
df['dx_deg'] = to_deg(df['dx'], sens)
df['dy_deg'] = to_deg(df['dy'], sens)
df['aim'] = aim[df['frame'].to_numpy()].astype(np.int64)
df['seg'] = seg[df['frame'].to_numpy()]
for k, v in base.items():
df[k] = v
return df[ROW_COLS]
# 第零組:純手
g0 = finish(pd.DataFrame(dict(frame=mf, t=mt, dx=mdx, dy=mdy, left=mleft, src=0)))
# 第一組
g1 = finish(pd.DataFrame(dict(frame=np.arange(nF), t=tF, dx=f_mdx + A, dy=f_mdy + B,
left=left_frame, src=0)))
g1['dt'] = tF - prevF
# 第二組
real = pd.DataFrame(dict(frame=mf, t=mt, dx=mdx, dy=mdy, left=mleft, src=0))
inj_f = np.where((A != 0) | (B != 0))[0]
last_real_t = np.where(has_real, mt[np.clip(lastidx, 0, None)], -np.inf)
inj = pd.DataFrame(dict(frame=inj_f, t=np.maximum(tF[inj_f], last_real_t[inj_f]) + 1e-6,
dx=A[inj_f], dy=B[inj_f], left=left_frame[inj_f], src=1))
g2 = finish(pd.concat([real, inj], ignore_index=True))
# 第三組(相位合成)與對照版(幀時間插入)
out3 = {}
stats3 = {}
for key, mode in (('3', 'phase'), ('3f', 'frame')):
ex, ey, synth, max_acc, tickless = build_g3(nF, tF, prevF, ax, ay, mf, mt, mdx, mdy, mleft,
left_frame, mode, rng, poll)
r3 = pd.DataFrame(dict(frame=mf, t=mt, dx=mdx + ex, dy=mdy + ey, left=mleft, src=0))
if synth:
s = np.array(synth, dtype=object)
sy = pd.DataFrame(dict(frame=s[:, 0].astype(np.int64), t=s[:, 1].astype(float),
dx=s[:, 2].astype(np.int64), dy=s[:, 3].astype(np.int64),
left=s[:, 4].astype(np.int64), src=2))
r3 = pd.concat([r3, sy], ignore_index=True)
out3[key] = finish(r3)
stats3[key] = dict(max_acc=max_acc, tickless=tickless)
# ---- 驗證 ----
chk = dict(player=player, round=idx, cheat=cheat, strength=strength)
chk['frames_mouse_mismatch'] = n_frame_mismatch
chk['dropped_rows'] = int((~ok).sum())
chk['A_minus_assist_x'] = float(A.sum() - ax.sum())
chk['A_minus_assist_y'] = float(B.sum() - ay.sum())
chk['max_abs_carry'] = float(max(np.abs(residA).max(initial=0), np.abs(residB).max(initial=0)))
target_x = f_mdx + A
target_y = f_mdy + B
g1x = frame_sums(g1['frame'].to_numpy(), g1['dx'].to_numpy(), nF)
g1y = frame_sums(g1['frame'].to_numpy(), g1['dy'].to_numpy(), nF)
chk['g1_frame_ok'] = bool(np.array_equal(g1x, target_x) and np.array_equal(g1y, target_y))
g2x = frame_sums(g2['frame'].to_numpy(), g2['dx'].to_numpy(), nF)
g2y = frame_sums(g2['frame'].to_numpy(), g2['dy'].to_numpy(), nF)
chk['g2_frame_ok'] = bool(np.array_equal(g2x, target_x) and np.array_equal(g2y, target_y))
chk['g2_injected'] = int((g2['src'] == 1).sum())
chk['g2_inj_ok'] = chk['g2_injected'] == len(inj_f)
for key, d in out3.items():
fx = frame_sums(d['frame'].to_numpy(), d['dx'].to_numpy(), nF)
fy = frame_sums(d['frame'].to_numpy(), d['dy'].to_numpy(), nF)
dev = np.maximum(np.abs(np.cumsum(fx) - np.cumsum(target_x)), np.abs(np.cumsum(fy) - np.cumsum(target_y)))
chk[f'g{key}_cum_dev_max'] = int(dev.max(initial=0))
chk[f'g{key}_cum_dev_gt1_frames'] = int((dev > 1).sum())
chk[f'g{key}_total_dev'] = int(max(abs(fx.sum() - target_x.sum()), abs(fy.sum() - target_y.sum())))
sy = d[d['src'] == 2]
chk[f'g{key}_synth'] = len(sy)
chk[f'g{key}_synth_in_real_frame'] = int(has_real[sy['frame'].to_numpy()].sum())
chk[f'g{key}_synth_zero'] = int(((sy['dx'] == 0) & (sy['dy'] == 0)).sum())
chk[f'g{key}_tickless_frames'] = stats3[key]['tickless']
chk[f'g{key}_max_acc'] = stats3[key]['max_acc']
if not cheat:
same = True
for d in (g0, g2, out3['3'], out3['3f']):
same &= len(d) == len(real) and bool((d['src'] == 0).all())
same &= bool(np.array_equal(d['dx'].to_numpy(), mdx) and np.array_equal(d['dy'].to_numpy(), mdy))
chk['nocheat_identical'] = same
for key, d in (('2', g2), ('3', out3['3']), ('3f', out3['3f'])):
t = d['t'].to_numpy()
back = np.diff(t)
chk[f'g{key}_t_backsteps'] = int((back < 0).sum())
chk[f'g{key}_t_backstep_max_ms'] = float(-back.min() * 1000) if len(back) and back.min() < 0 else 0.0
fr_idx = d['frame'].to_numpy()
late = t - tF[fr_idx]
early = t - prevF[fr_idx]
chk[f'g{key}_late_gt_0.3ms'] = int((late > 3e-4).sum())
chk[f'g{key}_early_rows'] = int((early <= 0).sum())
rounds_row = dict(player=player, round=idx, cheat=cheat, strength=strength, sensitivity=sens,
weapon=cfg['weapon'], map=cfg['map'], refreshRate=cfg['refreshRate'],
person=PERSON[player], planIndex=cfg['planIndex'], blockIndex=cfg['blockIndex'],
orderInBlock=cfg['orderInBlock'], buildId=cfg.get('buildId', ''),
play_seconds=cfg['duration'] - cfg['pausedSeconds'], frames=nF, mouse_events=len(mt),
fps=float(nF / max(tF[-1] - prevF[0], 1e-9)),
poll_period_ms=poll[0] * 1000, n_segments=len(segs),
aim_seconds=float(sum(tF[e] - prevF[s] for s, e in segs)),
startTimeLocal=cfg['startTimeLocal'])
seg_rows = [dict(player=player, round=idx, seg=i, f_start=s, f_end=e, n_frames=e - s + 1,
t_start=prevF[s], t_end=tF[e], duration_ms=(tF[e] - prevF[s]) * 1000,
cheat=cheat, strength=strength) for i, (s, e) in enumerate(segs)]
ctx = fr[CTX_COLS].copy()
ctx.insert(0, 'player', player)
ctx.insert(1, 'round', idx)
ctx.insert(2, 'frame', np.arange(nF))
ctx.insert(3, 't', tF)
ctx.insert(4, 'dt', tF - prevF)
ctx.insert(5, 'aim', aim.astype(np.int64))
ctx.insert(6, 'seg', seg)
return dict(g0=g0, g1=g1, g2=g2, g3=out3['3'], g3f=out3['3f'], chk=chk, round=rounds_row, segs=seg_rows, ctx=ctx)
def gap_table(rows_by_group, rounds):
"""瞄準片段內的相鄰回報間隔分布(每個 src × 類別)。"""
period = rounds.set_index(['player', 'round'])['poll_period_ms']
out = []
for key, df in rows_by_group.items():
d = df[df['aim'] == 1]
# 間隔只算同一個片段內的相鄰列
same = (d['seg'].to_numpy()[1:] == d['seg'].to_numpy()[:-1]) & \
(d['round'].to_numpy()[1:] == d['round'].to_numpy()[:-1]) & \
(d['player'].to_numpy()[1:] == d['player'].to_numpy()[:-1])
gap = np.diff(d['t'].to_numpy())[same] * 1000
sub = d.iloc[1:][same]
p = period.reindex(pd.MultiIndex.from_arrays([sub['player'], sub['round']])).to_numpy()
tab = pd.DataFrame(dict(player=sub['player'].to_numpy(), cheat=sub['cheat'].to_numpy(), src=sub['src'].to_numpy(), gap=gap, p=p))
for (c, s), g in tab.groupby(['cheat', 'src']):
out.append(dict(group=key, player='all', cheat=c, src=s, n=len(g),
p05=np.percentile(g.gap, 5), p50=np.median(g.gap), p95=np.percentile(g.gap, 95),
on_grid=np.mean(np.abs(g.gap - g.p) < GRID_TOL_FRAC * g.p), lt_half_P=np.mean(g.gap < 0.5 * g.p)))
for (pl, c), g in tab.groupby(['player', 'cheat']):
out.append(dict(group=key, player=pl, cheat=c, src='all', n=len(g),
p05=np.percentile(g.gap, 5), p50=np.median(g.gap), p95=np.percentile(g.gap, 95),
on_grid=np.mean(np.abs(g.gap - g.p) < GRID_TOL_FRAC * g.p), lt_half_P=np.mean(g.gap < 0.5 * g.p)))
for c, g in tab.groupby('cheat'):
out.append(dict(group=key, player='all', cheat=c, src='all', n=len(g),
p05=np.percentile(g.gap, 5), p50=np.median(g.gap), p95=np.percentile(g.gap, 95),
on_grid=np.mean(np.abs(g.gap - g.p) < GRID_TOL_FRAC * g.p), lt_half_P=np.mean(g.gap < 0.5 * g.p)))
return pd.DataFrame(out)
GROUP_README = {
'1': """# 第一組:Unity Input System(每幀一列)
模擬引擎以「每幀一次」提供滑鼠位移的情況。每一幀一列,`dx/dy` = 該幀所有滑鼠回報的總和 + 外掛在該幀的修正量(四捨五入成整數 count,餘數累積到下一幀)。
這是基準組:反作弊只看得到每幀的總量,看不到幀內的時間結構。
""",
'2': """# 第二組:Windows Raw Input + 每幀插入一次(最陽春的外掛)
真實滑鼠回報原樣保留(`src=0`)。外掛每幀的修正量(整數化,與第一組完全相同)在該幀的時間插入一列(`src=1`),
`t = max(幀時間, 該幀最後一筆真實回報) + 1 µs`。插入列落在幀時間上、和滑鼠的輪詢格點錯開,是刻意保留的時間戳破綻。
修正量四捨五入成 (0,0) 的幀不插入。
""",
'3': """# 第三組:Windows Raw Input + 平均補償
外掛每幀的修正量平均分到該幀的真實回報上(餘數用累加器帶到下一筆,每幀總和與第一組最多差 ±1 count)。
該幀沒有任何真實回報時(手沒動),沿著滑鼠既有的輪詢相位(週期由該回合真實回報估計,加上實測的到達抖動)
在幀時間前 40 ms 內合成回報(`src=2`),把修正量均分上去;取整後是 (0,0) 的合成列不輸出。
合成回報都在該幀之前到達,遊戲會在該幀套用,所以手不動時外掛照樣生效。
`rows_frameinsert.csv` 是對照版:無回報的幀改在幀時間插入一列(`src=2`),手不動時等於第二組,用來量化「靜止時的時間戳破綻」。
""",
}
FIELDS_DOC = """
## 欄位
| 欄位 | 說明 | 可當模型輸入 |
|---|---|---|
| `player` | 錄製編號 N = data/people_N(people_2 與 people_4 是同一人) | 否(分組/交叉玩家評估用) |
| `round` | 回合編號(同 raw 檔名) | 否(分組用) |
| `cheat` | 標籤:該回合是否開外掛 | 標籤 |
| `strength` | 外掛強度 0/20/40/60/80/100 | 否(分析用) |
| `frame` | 該列被遊戲套用的幀(frames_N.csv 的列號) | 否 |
| `t` | 到達時間(秒,與 raw 同一條時間軸) | 是(轉成間隔) |
| `dt` | 與同回合上一列的時間差(秒);第一組是幀間隔 | 是 |
| `dx`、`dy` | 位移(整數 counts,往右、往上為正) | 是 |
| `dx_deg`、`dy_deg` | 位移換成視角角度 = counts × 0.022 × 靈敏度(度)。預設模型輸入用這個,消除 DPI/靈敏度差異 | 是 |
| `left` | 左鍵狀態 | 是 |
| `src` | 0 = 真實回報(或第一組的幀),1 = 外掛插入列,2 = 第三組合成列 | **否**(等於答案) |
| `aim` | 該幀是否在瞄準中:truth_detected 且準心離敵人胸口 ≤ 15°(有無作弊同一條規則) | 否(篩選用) |
| `seg` | 瞄準片段編號(同回合內),非瞄準為 −1,對應 `common/segments.csv` | 否(切窗用) |
所有回合的列都保留;訓練時用 `common/segments.csv` 的片段在 `(w0, w0+W]` 切時間窗,片段短於窗長就丟棄。
建構程式:`scripts_2/build_groups.py`,驗證結果:`common/BUILD_REPORT.md`。
"""
def main():
utf8_stdout()
ap = argparse.ArgumentParser()
ap.add_argument('--seed', type=int, default=0)
args = ap.parse_args()
t0 = time.time()
acc = {k: [] for k in ('g0', 'g1', 'g2', 'g3', 'g3f', 'chk', 'round', 'segs', 'ctx')}
for player in PLAYERS:
rounds = iter_rounds(player)
folder = DATA / PLAYERS[player]
poll = poll_model([pd.read_csv(folder / f'mouse_{i}.csv', usecols=['t'])['t'].to_numpy() for i in rounds])
print(f'player {player} ({PLAYERS[player]}, person {PERSON[player]}): {len(rounds)} rounds, poll period {poll[0] * 1000:.4f} ms, '
f'jitter sd {poll[1].std() * 1000:.4f} ms')
for idx in rounds:
r = build_round(player, idx, args.seed, poll)
for k in ('g0', 'g1', 'g2', 'g3', 'g3f', 'ctx'):
acc[k].append(r[k])
acc['chk'].append(r['chk'])
acc['round'].append(r['round'])
acc['segs'].extend(r['segs'])
out = {'0': pd.concat(acc['g0'], ignore_index=True), '1': pd.concat(acc['g1'], ignore_index=True), '2': pd.concat(acc['g2'], ignore_index=True),
'3': pd.concat(acc['g3'], ignore_index=True), '3f': pd.concat(acc['g3f'], ignore_index=True)}
rounds = pd.DataFrame(acc['round'])
segs = pd.DataFrame(acc['segs'])
ctx = pd.concat(acc['ctx'], ignore_index=True)
chk = pd.DataFrame(acc['chk'])
COMMON.mkdir(parents=True, exist_ok=True)
for key, df in out.items():
p = group_path(key)
p.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(p, index=False, float_format='%.6f', encoding='utf-8')
print(f'wrote {p.relative_to(DATA.parent)} rows={len(df):,}')
(DERIVED / 'README.md').write_text(
'# phase 2 衍生資料\n\n由 `scripts_2/build_groups.py` 從 `data/` 產生,可隨時重建。'
'`player` = 錄製編號(people_N),實際玩家見 `common/rounds.csv` 的 `person`。只含正式回合(不含熱身)。\n\n'
'`g0_hand.csv` 是第零組(純手):只有真實回報、不加外掛修正,當負對照。\n\n'
+ '\n'.join(GROUP_README[k] for k in ('1', '2', '3')) + FIELDS_DOC, encoding='utf-8')
rounds.to_csv(COMMON / 'rounds.csv', index=False, float_format='%.6f', encoding='utf-8')
segs.to_csv(COMMON / 'segments.csv', index=False, float_format='%.6f', encoding='utf-8')
ctx.to_csv(COMMON / 'frames_ctx.csv', index=False, float_format='%.6f', encoding='utf-8')
chk.to_csv(COMMON / 'build_checks.csv', index=False, encoding='utf-8')
# ---- 報告 ----
L = ['# BUILD_REPORT(phase 2)', '', f'產生時間 {time.strftime("%Y-%m-%d %H:%M:%S")},seed={args.seed},'
f'耗時 {time.time() - t0:.0f} 秒。逐回合明細在 `build_checks.csv`。', '']
L.append('## 1–5. 不變量')
ch = chk[chk.cheat == 1]
nc = chk[chk.cheat == 0]
tests = [
('沒有 frame 欄位超出範圍而被丟掉的回報', (chk.dropped_rows == 0).all()),
('|ΣA − Σassist| < 1(每軸)', (chk.A_minus_assist_x.abs() < 1).all() and (chk.A_minus_assist_y.abs() < 1).all()),
('整數化殘值 |acc| < 0.5', (chk.max_abs_carry <= 0.5).all()),
('第一組每幀 == mouse + A', chk.g1_frame_ok.all()),
('第二組每幀總和 == mouse + A', chk.g2_frame_ok.all()),
('第二組插入列數 == (A,B)≠(0,0) 的幀數', chk.g2_inj_ok.all()),
('第三組回合總和與第一組差 ≤ 1', (chk.g3_total_dev <= 1).all()),
('第三組對照版回合總和與第一組差 ≤ 1', (chk.g3f_total_dev <= 1).all()),
('第三組合成列只在沒有真實回報的幀', (chk.g3_synth_in_real_frame == 0).all() and (chk.g3f_synth_in_real_frame == 0).all()),
('沒有 (0,0) 合成列', (chk.g3_synth_zero == 0).all() and (chk.g3f_synth_zero == 0).all()),
('無作弊回合:第二、三組與 mouse_N.csv 完全相同', nc.nocheat_identical.astype(bool).all()),
]
L += ['| 檢查 | 結果 |', '|---|---|'] + [f'| {n} | {"通過" if ok else "**失敗**"} |' for n, ok in tests]
L.append('')
mm = chk[chk.frames_mouse_mismatch > 0]
L.append(f'原始資料備註:frames.mouse_dx/dy 與該幀 mouse 列加總不同的幀共 {int(chk.frames_mouse_mismatch.sum())} 個,'
f'出現在 {[(int(a), int(b)) for a, b in zip(mm.player, mm["round"])]}(玩家, 回合)。這是暫停恢復後遊戲丟掉的回報;三組一律以 mouse 檔為準。')
L.append('')
L.append('第三組累積和在幀邊界的偏差(理想 ≤ 1;> 1 只發生在合成區間放不下任何回報、修正量延到下一筆的幀):')
L.append('')
dev = pd.DataFrame([
dict(版本='第三組', 最大偏差=ch.g3_cum_dev_max.max(), 偏差大於1的幀=ch.g3_cum_dev_gt1_frames.sum(),
無法放回報的幀=ch.g3_tickless_frames.sum(), 合成列=ch.g3_synth.sum()),
dict(版本='第三組對照版', 最大偏差=ch.g3f_cum_dev_max.max(), 偏差大於1的幀=ch.g3f_cum_dev_gt1_frames.sum(),
無法放回報的幀=ch.g3f_tickless_frames.sum(), 合成列=ch.g3f_synth.sum())])
L += [md_table(dev), '']
L.append('時間順序(原始資料本身約 0.5% 的回報比幀時間晚 ≤ 0.25 ms,另有少數回報比上一幀時間還早):')
L.append('')
tt = []
for key in ('2', '3', '3f'):
tt.append(dict(組別=key, 時間倒退次數=chk[f'g{key}_t_backsteps'].sum(),
最大倒退ms=chk[f'g{key}_t_backstep_max_ms'].max(),
晚於幀時間超過0_3ms=chk[f'g{key}_late_gt_0.3ms'].sum(),
早於上一幀時間=chk[f'g{key}_early_rows'].sum()))
L += [md_table(pd.DataFrame(tt)), '']
L.append('## 6. 瞄準片段內的相鄰間隔(ms)')
L.append('')
L.append('`on_grid` = 間隔與輪詢週期相差 < 週期 × 1/16 的比例(125 Hz 時為 0.5 ms);`lt_half_P` = 間隔小於半個週期的比例。src: 0 真實、1 插入、2 合成。')
L.append('')
gt = gap_table(out, rounds)
gt.to_csv(COMMON / 'gap_table.csv', index=False, encoding='utf-8')
L += [md_table(gt), '']
L.append('## 7. 數量')
L.append('')
cnt = []
for key, df in out.items():
g = df.groupby(['player', 'strength'])
c = pd.DataFrame(dict(rows=g.size(), injected=g['src'].apply(lambda s: int((s == 1).sum())),
synthetic=g['src'].apply(lambda s: int((s == 2).sum())),
aim_rows=g['aim'].sum())).reset_index()
c.insert(0, 'group', key)
cnt.append(c)
cnt = pd.concat(cnt)
sg = segs.groupby(['player', 'strength']).agg(segments=('seg', 'size'), aim_s=('duration_ms', lambda x: x.sum() / 1000)).reset_index()
rd = rounds.groupby(['player', 'strength']).agg(rounds=('round', 'size')).reset_index()
L += [md_table(rd.merge(sg, on=['player', 'strength']), '{:.1f}'), '', md_table(cnt, '{:.0f}'), '']
L.append('各窗長下仍可用的瞄準時間比例(片段 ≥ 窗長才保留)與窗數(步幅 = 窗長/2):')
L.append('')
surv = []
for W in WINDOWS_MS:
for c, g in segs.groupby('cheat'):
d = g.duration_ms.to_numpy()
nwin = np.where(d >= W, np.floor((d - W) / (W / 2)) + 1, 0).sum()
surv.append(dict(W_ms=W, cheat=c, kept_time=d[d >= W].sum() / d.sum(), kept_segments=np.mean(d >= W),
windows=int(nwin)))
L += [md_table(pd.DataFrame(surv)), '']
(COMMON / 'BUILD_REPORT.md').write_text('\n'.join(L), encoding='utf-8')
failed = [n for n, ok in tests if not ok]
print('BUILD_REPORT written;', 'all invariants passed' if not failed else f'FAILED: {failed}')
print(f'done in {time.time() - t0:.0f}s')
if __name__ == '__main__':
main()
+325
View File
@@ -0,0 +1,325 @@
# -*- 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["[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 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('[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()
# 同玩家交叉驗證:每折都從訓練回合切出校準回合
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()
+150
View File
@@ -0,0 +1,150 @@
# -*- coding: utf-8 -*-
"""phase 2 共用:路徑、常數、讀取回合、外掛修正整數化、瞄準片段。
與 phase 1(phase_1/scripts_1/mtd_common.py)的差別:
- 4 份錄製(people_1–4),`player` = 錄製編號,`person` = 實際玩家(people_2 與 people_4 是同一人)。
- 只用正式回合(排除 isWarmup),回合編號沿用檔名的 roundIndex(可能缺號),順序看 planIndex。
- 衍生資料放 phase_2/derived/,結果放 phase_2/results/。
"""
import json
import sys
from pathlib import Path
import numpy as np
import pandas as pd
ROOT = Path(__file__).resolve().parent.parent # phase_2/
DATA = ROOT / 'data'
DERIVED = ROOT / 'derived'
RESULTS = ROOT / 'results'
COMMON = DERIVED / 'common'
PHASE1_RESULTS = ROOT.parent / 'phase_1' / 'results_1'
PLAYERS = {1: 'people_1', 2: 'people_2', 3: 'people_3', 4: 'people_4'}
PERSON = {1: 'A', 2: 'B', 3: 'C', 4: 'B'} # 跨玩家測試以 person 為單位
PERSONS = ['A', 'B', 'C']
REC_LABEL = {1: 'A 125Hz 40FPS', 2: 'B 125Hz', 3: 'C 1000Hz', 4: 'B 1000Hz'}
# 組別 -> 檔名。'0' 是純手(只有真實回報,不加外掛修正),當負對照
GROUPS = {
'0': 'g0_hand.csv',
'1': 'g1_engine.csv',
'2': 'g2_insert.csv',
'3': 'g3_spread.csv',
'3f': 'g3f_frameinsert.csv',
}
DEG_PER_COUNT = 0.022
AIM_FOV_DEG = 15.0
SEG_BREAK_S = 0.05
SYNTH_SPAN_S = 0.040
GRID_TOL_FRAC = 1 / 16 # 間隔「在格點上」的容許誤差 = 週期 × 1/16(125 Hz 時 = 0.5 ms,與 phase 1 相同)
N_FOLDS = 4 # 以區塊切分:fold = blockIndex // 2
MODEL_INPUT_COLS = frozenset({'t', 'dt', 'dx', 'dy', 'dx_deg', 'dy_deg', 'left'})
ROW_COLS = ['player', 'round', 'cheat', 'strength', 'frame', 't', 'dt', 'dx', 'dy',
'dx_deg', 'dy_deg', 'left', 'src', 'aim', 'seg']
def utf8_stdout():
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
pass
def group_path(g):
return DERIVED / GROUPS[g]
def load_config(player, idx):
with open(DATA / PLAYERS[player] / f'config_{idx}.json', encoding='utf-8-sig') as fh:
return json.load(fh)
def iter_rounds(player, include_warmup=False):
"""依 planIndex 排序,回傳正式回合的 roundIndex(檔名編號)。"""
folder = DATA / PLAYERS[player]
out = []
for p in folder.glob('config_*.json'):
idx = int(p.stem.split('_')[1])
c = load_config(player, idx)
if c.get('isWarmup') and not include_warmup:
continue
out.append((c['planIndex'], idx))
return [idx for _, idx in sorted(out)]
def load_round(player, idx):
folder = DATA / PLAYERS[player]
cfg = load_config(player, idx)
frames = pd.read_csv(folder / f'frames_{idx}.csv')
mouse = pd.read_csv(folder / f'mouse_{idx}.csv')
events = pd.read_csv(folder / f'events_{idx}.csv')
return cfg, frames, mouse, events
def carry_round(x):
"""浮點序列 -> 整數序列,餘數累積到下一個值(外掛只能送整數 count)。"""
x = np.asarray(x, dtype=np.float64)
out = np.zeros(len(x), dtype=np.int64)
resid = np.zeros(len(x))
acc = 0.0
for i, v in enumerate(x):
acc += v
e = np.floor(acc + 0.5)
acc -= e
out[i] = int(e)
resid[i] = acc
return out, resid
def frame_prev_t(frames):
t = frames['t'].to_numpy()
prev = np.empty_like(t)
prev[0] = t[0] - frames['dt'].to_numpy()[0]
prev[1:] = t[:-1]
return prev
def aim_segments(frames):
"""瞄準旗標與片段(有無輔助同一條規則,不用 assist_engaged)。"""
t = frames['t'].to_numpy()
prev = frame_prev_t(frames)
err = np.hypot(frames['truth_err_x'].to_numpy(), frames['truth_err_y'].to_numpy())
aim = (frames['truth_detected'].to_numpy() == 1) & (err <= AIM_FOV_DEG)
gap_break = (t - prev) > SEG_BREAK_S
aim &= ~gap_break
seg = np.full(len(t), -1, dtype=np.int64)
segs = []
f = 0
n = len(t)
while f < n:
if not aim[f]:
f += 1
continue
s = f
while f + 1 < n and aim[f + 1]:
f += 1
segs.append((s, f))
seg[s:f + 1] = len(segs) - 1
f += 1
return aim, seg, segs
def to_deg(counts, sens):
return np.asarray(counts, dtype=np.float64) * DEG_PER_COUNT * sens
def md_table(df, floatfmt='{:.3f}'):
cols = list(df.columns)
lines = ['| ' + ' | '.join(str(c) for c in cols) + ' |', '|' + '---|' * len(cols)]
for r in df.itertuples(index=False):
cells = []
for v in r:
if isinstance(v, (float, np.floating)):
cells.append('' if np.isnan(v) else floatfmt.format(v))
else:
cells.append(str(v))
lines.append('| ' + ' | '.join(cells) + ' |')
return '\n'.join(lines)
+253
View File
@@ -0,0 +1,253 @@
# -*- coding: utf-8 -*-
"""時間窗切法、手工特徵(向量化)、序列張量。
- 窗以毫秒定義:每個瞄準片段 (t_start, t_end] 內,w0 = t_start + k·W/2,要求 w0 + W ≤ t_end,
片段短於 W 就丟棄。窗內的列 = t ∈ (w0, w0+W](與幀區間 (t_{f-1}, t_f] 同一個慣例)。
- 三組共用同一批窗(窗只由 segments.csv 決定)。
- 只有 MODEL_INPUT_COLS 的欄位會進到特徵/張量。
"""
import numpy as np
import pandas as pd
from mtd_common import COMMON, GRID_TOL_FRAC, MODEL_INPUT_COLS, group_path
WINDOWS_MS = [8, 16, 33, 50, 100, 200, 300, 500, 1000, 2000]
_BIG = 1e5 # 每回合時間軸的位移量(秒),讓整份資料可以一次 searchsorted
def load_segments():
return pd.read_csv(COMMON / 'segments.csv')
def load_rounds():
return pd.read_csv(COMMON / 'rounds.csv')
def round_code(player, rnd):
return np.asarray(player, dtype=np.int64) * 10000 + np.asarray(rnd, dtype=np.int64)
def code_player(code):
return np.asarray(code, dtype=np.int64) // 10000
def make_windows(segs, W_ms, min_seg_ms=None):
"""回傳窗表:player, round, seg, cheat, strength, w0, w1(秒)。"""
s = segs if min_seg_ms is None else segs[segs.duration_ms >= min_seg_ms]
d = s.duration_ms.to_numpy()
stride = W_ms / 2.0
n = np.where(d >= W_ms, np.floor((d - W_ms) / stride + 1e-9) + 1, 0).astype(np.int64)
rep = np.repeat(np.arange(len(s)), n)
k = np.arange(n.sum()) - np.repeat(np.cumsum(n) - n, n)
w0 = s.t_start.to_numpy()[rep] + k * stride / 1000.0
out = pd.DataFrame({c: s[c].to_numpy()[rep] for c in ('player', 'round', 'seg', 'cheat', 'strength')})
out['w0'] = w0
out['w1'] = w0 + W_ms / 1000.0
return out
class GroupRows:
"""一組資料的列,依 (回合, t) 排序,方便一次切出所有窗。"""
def __init__(self, key, units='deg', rounds=None):
cols = ['player', 'round', 't', 'dx', 'dy', 'dx_deg', 'dy_deg', 'left']
assert set(cols) - {'player', 'round'} <= MODEL_INPUT_COLS
df = pd.read_csv(group_path(key), usecols=cols)
code = round_code(df.player, df['round'])
order = np.lexsort((df.t.to_numpy(), code))
df = df.iloc[order].reset_index(drop=True)
self.code = code[order]
uniq, self.rank = np.unique(self.code, return_inverse=True)
self.code_rank = dict(zip(uniq.tolist(), range(len(uniq))))
self.t = df.t.to_numpy()
self.key = self.rank * _BIG + self.t
if units == 'deg':
self.x, self.y = df.dx_deg.to_numpy(), df.dy_deg.to_numpy()
self.unit_scale = 0.02 # 序列模型 signed-log 的尺度(約一個 count 的角度)
else:
self.x, self.y = df.dx.to_numpy().astype(float), df.dy.to_numpy().astype(float)
self.unit_scale = 1.0
self.cx, self.cy = df.dx.to_numpy(), df.dy.to_numpy()
self.left = df.left.to_numpy().astype(float)
rounds = rounds if rounds is not None else load_rounds()
# 輪詢週期是裝置屬性(反作弊可由回報流估得),用來算間隔落在格點上的比例
per = dict(zip(round_code(rounds.player, rounds['round']).tolist(), rounds.poll_period_ms.to_numpy() / 1000))
self.period_by_code = per
def slice(self, wins):
"""回傳 Slice:每個窗的 [start, end) 與攤平的列索引。"""
rank = np.array([self.code_rank.get(c, -1) for c in round_code(wins.player, wins['round']).tolist()])
valid = rank >= 0
k0 = rank * _BIG + wins.w0.to_numpy()
k1 = rank * _BIG + wins.w1.to_numpy()
start = np.searchsorted(self.key, k0, side='right')
end = np.searchsorted(self.key, k1, side='right')
end = np.where(valid, end, start)
return Slice(self, wins, start, end)
class Slice:
def __init__(self, rows, wins, start, end):
self.rows, self.wins = rows, wins
self.n = (end - start).astype(np.int64)
self.nw = len(wins)
off = np.cumsum(self.n) - self.n
self.win_id = np.repeat(np.arange(self.nw), self.n)
self.pos = np.arange(self.n.sum()) - np.repeat(off, self.n)
self.idx = self.pos + np.repeat(start, self.n)
self.off = off
t = rows.t[self.idx]
prev_t = np.where(self.pos > 0, rows.t[np.maximum(self.idx - 1, 0)], wins.w0.to_numpy()[self.win_id])
self.gap = t - prev_t # 第一列 = t - w0
self.t = t
self.period = np.array([rows.period_by_code.get(c, 0.008)
for c in round_code(wins.player, wins['round']).tolist()])
def _segsum(win_id, v, nw):
return np.bincount(win_id, weights=v, minlength=nw)
def _segreduce(ufunc, v, sl, fill):
out = np.full(sl.nw, fill, dtype=float)
ne = sl.n > 0
if ne.any() and len(v):
out[ne] = ufunc.reduceat(v, sl.off[ne])
return out
def window_features(sl, use_dt=True):
"""每個窗的手工特徵(DataFrame)。時間類特徵以 't_' 開頭,關閉 Δt 時一起拿掉。"""
r, w, nw = sl.rows, sl.win_id, sl.nw
W = (sl.wins.w1 - sl.wins.w0).to_numpy()
x, y = r.x[sl.idx], r.y[sl.idx]
cx, cy = r.cx[sl.idx], r.cy[sl.idx]
left = r.left[sl.idx]
m = np.hypot(x, y)
n = sl.n.astype(float)
nz = np.maximum(n, 1)
F = {}
F['n_rows'] = n
sx, sy = _segsum(w, x, nw), _segsum(w, y, nw)
F['sum_x'], F['sum_y'] = sx, sy
path = _segsum(w, m, nw)
F['path'] = path
F['net'] = np.hypot(sx, sy)
F['straight'] = np.where(path > 0, F['net'] / np.maximum(path, 1e-12), 0)
F['mean_m'] = path / nz
for name, v in (('x', x), ('y', y), ('m', m)):
mu = _segsum(w, v, nw) / nz
F[f'std_{name}'] = np.sqrt(np.maximum(_segsum(w, v * v, nw) / nz - mu * mu, 0))
F['max_abs_x'] = _segreduce(np.maximum, np.abs(x), sl, 0)
F['max_abs_y'] = _segreduce(np.maximum, np.abs(y), sl, 0)
F['max_m'] = _segreduce(np.maximum, m, sl, 0)
zero = (cx == 0) & (cy == 0)
one = (np.maximum(np.abs(cx), np.abs(cy)) == 1)
F['frac_zero'] = _segsum(w, zero.astype(float), nw) / nz
F['frac_one'] = _segsum(w, one.astype(float), nw) / nz
F['frac_left'] = _segsum(w, left, nw) / nz
# 相鄰列的差(不用時間)
has_prev = sl.pos > 0
px = np.where(has_prev, r.x[np.maximum(sl.idx - 1, 0)], 0)
py = np.where(has_prev, r.y[np.maximum(sl.idx - 1, 0)], 0)
dd = np.where(has_prev, np.hypot(x - px, y - py), 0)
npair = np.maximum(_segsum(w, has_prev.astype(float), nw), 1)
F['mean_dd'] = _segsum(w, dd, nw) / npair
F['std_dd'] = np.sqrt(np.maximum(_segsum(w, dd * dd, nw) / npair - F['mean_dd'] ** 2, 0))
F['max_dd'] = _segreduce(np.maximum, dd, sl, 0)
pm = np.hypot(px, py)
both = has_prev & (m > 0) & (pm > 0)
cos = np.where(both, (x * px + y * py) / np.maximum(m * pm, 1e-12), 0)
nboth = _segsum(w, both.astype(float), nw)
F['mean_cos'] = np.where(nboth > 0, _segsum(w, cos, nw) / np.maximum(nboth, 1), 1)
F['frac_reverse'] = np.where(nboth > 0, _segsum(w, (both & (cos < 0)).astype(float), nw) / np.maximum(nboth, 1), 0)
# 列位移大小的 lag-1 相關(平均補償會讓同一幀內的列有共同偏移)
mm = _segsum(w, m, nw) / nz
dm = m - mm[w]
dpm = np.where(has_prev, pm - mm[w], 0)
cov = _segsum(w, np.where(has_prev, dm * dpm, 0), nw)
var = _segsum(w, dm * dm, nw)
F['ac1_m'] = np.where(var > 0, cov / np.maximum(var, 1e-12), 0)
if use_dt:
gap = sl.gap
P = sl.period[w]
F['t_rate'] = n / W
F['t_gap_mean'] = _segsum(w, gap, nw) / nz
F['t_gap_std'] = np.sqrt(np.maximum(_segsum(w, gap * gap, nw) / nz - F['t_gap_mean'] ** 2, 0))
F['t_gap_min'] = _segreduce(np.minimum, gap, sl, 0)
F['t_gap_max'] = _segreduce(np.maximum, gap, sl, 0)
resid = np.abs(gap - P * np.round(gap / P))
inner = sl.pos > 0
ninner = np.maximum(_segsum(w, inner.astype(float), nw), 1)
F['t_frac_offgrid'] = _segsum(w, (inner & (resid >= GRID_TOL_FRAC * P)).astype(float), nw) / ninner
F['t_mean_resid'] = _segsum(w, np.where(inner, resid, 0), nw) / ninner
F['t_frac_short'] = _segsum(w, (inner & (gap < 0.5 * P)).astype(float), nw) / ninner
F['t_frac_long'] = _segsum(w, (inner & (gap > 1.5 * P)).astype(float), nw) / ninner
first_gap = np.zeros(nw)
last_gap = W.copy()
ne = sl.n > 0
first_gap[ne] = sl.gap[sl.off[ne]]
last_gap[ne] = sl.wins.w1.to_numpy()[ne] - sl.t[sl.off[ne] + sl.n[ne] - 1]
F['t_first'] = first_gap / W
F['t_last'] = last_gap / W
v = m / np.maximum(gap, 1e-4)
F['t_speed_mean'] = _segsum(w, v, nw) / nz
F['t_speed_max'] = _segreduce(np.maximum, v, sl, 0)
pv = np.where(has_prev, pm / np.maximum(np.where(has_prev, sl.gap[np.maximum(np.arange(len(gap)) - 1, 0)], 1), 1e-4), 0)
acc = np.where(has_prev, np.abs(v - pv) / np.maximum(gap, 1e-4), 0)
F['t_acc_mean'] = _segsum(w, acc, nw) / npair
F['t_acc_max'] = _segreduce(np.maximum, acc, sl, 0)
return pd.DataFrame(F)
def context_features(ctx_rows, wins):
"""(--context 用)窗內遊戲情境的平均:準心誤差、目標可見度、後座力、玩家/敵人速度。"""
sl = ctx_rows.slice(wins)
w, nw = sl.win_id, sl.nw
nz = np.maximum(sl.n, 1)
F = {}
for name, arr in ctx_rows.extra.items():
F[f'ctx_{name}'] = _segsum(w, arr[sl.idx], nw) / nz
return pd.DataFrame(F)
class CtxRows(GroupRows):
"""frames_ctx.csv 當成「列」切窗(只給 --context 用)。"""
def __init__(self, rounds=None):
df = pd.read_csv(COMMON / 'frames_ctx.csv')
code = round_code(df.player, df['round'])
order = np.lexsort((df.t.to_numpy(), code))
df = df.iloc[order].reset_index(drop=True)
self.code = code[order]
uniq, self.rank = np.unique(self.code, return_inverse=True)
self.code_rank = dict(zip(uniq.tolist(), range(len(uniq))))
self.t = df.t.to_numpy()
self.key = self.rank * _BIG + self.t
self.extra = {
'err': np.hypot(df.truth_err_x, df.truth_err_y).to_numpy(),
'visible': df.truth_visible.to_numpy(),
'recoil_x': df.recoil_x.to_numpy(), 'recoil_y': df.recoil_y.to_numpy(),
'self_speed': np.hypot(df.vx, df.vz).to_numpy(), 'bot_speed': np.hypot(df.bvx, df.bvz).to_numpy(),
}
self.period_by_code = {}
def window_tensor(sl, use_dt=True, max_len=512):
"""序列張量 (N, L, C) 與 mask (N, L)、列數。通道:signed-log dx、dy、left、[間隔/週期]。"""
r = sl.rows
L = int(min(max(sl.n.max(initial=0), 1), max_len))
keep = sl.pos < L
w, p, idx = sl.win_id[keep], sl.pos[keep], sl.idx[keep]
C = 4 if use_dt else 3
X = np.zeros((sl.nw, L, C), dtype=np.float32)
M = np.zeros((sl.nw, L), dtype=np.float32)
s = r.unit_scale
X[w, p, 0] = np.sign(r.x[idx]) * np.log1p(np.abs(r.x[idx]) / s)
X[w, p, 1] = np.sign(r.y[idx]) * np.log1p(np.abs(r.y[idx]) / s)
X[w, p, 2] = r.left[idx]
if use_dt:
X[w, p, 3] = np.clip(sl.gap[keep] / sl.period[w], 0, 8)
M[w, p] = 1
logn = np.log1p(sl.n).astype(np.float32)
return X, M, logn
+240
View File
@@ -0,0 +1,240 @@
# -*- 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'), ('[email protected]', '召回@誤判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', '[email protected]', '[email protected]', '[email protected]',
'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["[email protected]"]:.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', '[email protected]', '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='[email protected]').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='[email protected]').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['[email protected]'].iat[0], 召回1_phase2=x2['[email protected]'].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')['[email protected]']
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'), ('[email protected]', '召回@誤判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["[email protected]"]:.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()
+493
View File
@@ -0,0 +1,493 @@
# -*- 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()