phase 2 data
This commit is contained in:
1 parent
f0be88a372
commit
189e4dc68f
1950 files changed
+510775
No files matched your search
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,69 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""輔助的任務效益:每回合命中率、爆頭率、擊倒時間,依玩家 × 強度彙總,並對照偵測率。
|
||||
|
||||
輸出:
|
||||
results_1/benefit_rounds.csv 每回合一列
|
||||
results_1/benefit.csv 玩家 × 強度(附同設定下的偵測率)
|
||||
"""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from mtd_common import DATA, PLAYERS, RESULTS, utf8_stdout
|
||||
from mtd_windows import load_rounds
|
||||
|
||||
DET_W = 300 # 對照用的偵測設定
|
||||
DET_GROUPS = ('1', '2', '3')
|
||||
|
||||
|
||||
def round_stats(player, idx):
|
||||
e = pd.read_csv(DATA / PLAYERS[player] / f'events_{idx}.csv')
|
||||
shots = int((e.type == 'shot').sum())
|
||||
hit = e[e.type == 'hit']
|
||||
t0 = e.loc[e.type == 'round_start', 't']
|
||||
tk = e.loc[e.type == 'kill', 't']
|
||||
return dict(player=player, round=idx, shots=shots, hits=len(hit),
|
||||
head_hits=int((hit.part == 'Head').sum()),
|
||||
hit_rate=len(hit) / shots if shots else np.nan,
|
||||
head_rate=(hit.part == 'Head').mean() if len(hit) else np.nan,
|
||||
time_to_kill=float(tk.iloc[0] - t0.iloc[0]) if len(tk) and len(t0) else np.nan)
|
||||
|
||||
|
||||
def main():
|
||||
utf8_stdout()
|
||||
rounds = load_rounds()
|
||||
per = pd.DataFrame([round_stats(int(r.player), int(r['round'])) for _, r in rounds.iterrows()])
|
||||
per = per.merge(rounds[['player', 'round', 'cheat', 'strength', 'play_seconds', 'aim_seconds']],
|
||||
on=['player', 'round'])
|
||||
per.to_csv(RESULTS / 'benefit_rounds.csv', index=False, float_format='%.6f')
|
||||
|
||||
agg = per.groupby(['player', 'strength']).agg(
|
||||
n_rounds=('round', 'size'), shots=('shots', 'sum'), hits=('hits', 'sum'),
|
||||
hit_rate_mean=('hit_rate', 'mean'), hit_rate_sd=('hit_rate', 'std'),
|
||||
head_rate_mean=('head_rate', 'mean'),
|
||||
ttk_mean=('time_to_kill', 'mean'), ttk_median=('time_to_kill', 'median'), ttk_sd=('time_to_kill', 'std'),
|
||||
play_seconds_mean=('play_seconds', 'mean')).reset_index()
|
||||
agg['hit_rate_pooled'] = agg.hits / agg.shots
|
||||
base = agg[agg.strength == 0].set_index('player')
|
||||
agg['hit_rate_gain'] = agg.hit_rate_mean - agg.player.map(base.hit_rate_mean)
|
||||
agg['ttk_ratio'] = agg.ttk_mean / agg.player.map(base.ttk_mean)
|
||||
|
||||
ps = pd.read_csv(RESULTS / 'per_strength.csv')
|
||||
ps = ps[(ps.model == 'gbdt') & (ps.segset == 'all') & (ps.W_ms == DET_W) & ps['eval'].isin(['cv_p1', 'cv_p2'])]
|
||||
ps['player'] = ps['eval'].str[-1].astype(int)
|
||||
ps['group'] = ps.group.astype(str)
|
||||
for g in DET_GROUPS:
|
||||
for dt in (1, 0):
|
||||
s = ps[(ps.group == g) & (ps.dt == dt)][['player', 'strength', '[email protected]', 'round_recall@1%']]
|
||||
tag = f'g{g}_{"dt" if dt else "nodt"}'
|
||||
s = s.rename(columns={'[email protected]': f'win_tpr1_{tag}', 'round_recall@1%': f'round_recall1_{tag}'})
|
||||
agg = agg.merge(s, on=['player', 'strength'], how='left')
|
||||
agg.to_csv(RESULTS / 'benefit.csv', index=False, float_format='%.6f')
|
||||
show = ['player', 'strength', 'n_rounds', 'hit_rate_mean', 'hit_rate_gain', 'ttk_mean', 'ttk_ratio',
|
||||
'win_tpr1_g2_nodt', 'win_tpr1_g3_nodt']
|
||||
print(agg[show].round(3).to_string(index=False))
|
||||
print('shots', int(per.shots.sum()), 'hits', int(per.hits.sum()),
|
||||
'rounds without kill', int(per.time_to_kill.isna().sum()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,472 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""產生 data_1 的三組資料(+第三組對照版)與共用表,並寫出驗證報告。
|
||||
|
||||
第一組 Unity Input System:每幀一列,dx = 該幀滑鼠總和 + 該幀外掛修正(整數)
|
||||
第二組 Raw Input + 每幀插入:真實回報原樣,外掛修正在幀時間插入一列
|
||||
第三組 Raw Input + 平均補償:外掛修正均分到該幀的真實回報;該幀沒有回報時沿滑鼠輪詢相位合成回報
|
||||
第三組對照版(rows_frameinsert.csv):無回報幀改在幀時間插入一列
|
||||
|
||||
用法:python scripts_1/build_groups.py [--seed 0]
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from mtd_common import (COMMON, DATA, GROUPS, 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]
|
||||
|
||||
# 第一組
|
||||
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 (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'],
|
||||
play_seconds=cfg['duration'] - cfg['pausedSeconds'], frames=nF, mouse_events=len(mt),
|
||||
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(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(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, 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) < 0.5), lt_half_P=np.mean(g.gap < 0.5 * g.p)))
|
||||
for c, g in tab.groupby('cheat'):
|
||||
out.append(dict(group=key, 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) < 0.5), 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`。插入列落在 60 Hz 幀格點、和滑鼠 8 ms 輪詢格點錯開,是刻意保留的時間戳破綻。
|
||||
修正量四捨五入成 (0,0) 的幀不插入。
|
||||
""",
|
||||
'3': """# 第三組:Windows Raw Input + 平均補償
|
||||
|
||||
外掛每幀的修正量平均分到該幀的真實回報上(餘數用累加器帶到下一筆,每幀總和與第一組最多差 ±1 count)。
|
||||
該幀沒有任何真實回報時(手沒動),沿著滑鼠既有的輪詢相位(週期由該回合真實回報估計,加上實測的到達抖動)
|
||||
在幀時間前 40 ms 內合成回報(`src=2`),把修正量均分上去;取整後是 (0,0) 的合成列不輸出。
|
||||
合成回報都在該幀之前到達,遊戲會在該幀套用,所以手不動時外掛照樣生效。
|
||||
|
||||
`rows_frameinsert.csv` 是對照版:無回報的幀改在幀時間插入一列(`src=2`),手不動時等於第二組,用來量化「靜止時的時間戳破綻」。
|
||||
""",
|
||||
}
|
||||
|
||||
FIELDS_DOC = """
|
||||
## 欄位
|
||||
|
||||
| 欄位 | 說明 | 可當模型輸入 |
|
||||
|---|---|---|
|
||||
| `player` | 1 = raw_1,2 = raw_2 | 否(分組/交叉玩家評估用) |
|
||||
| `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_1/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 ('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}: {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 ('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 = {'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):,}')
|
||||
for key in ('1', '2', '3'):
|
||||
(group_path(key).parent / 'README.md').write_text(GROUP_README[key] + 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(data_1)', '', 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` = 間隔與輪詢週期相差 < 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()
|
||||
@@ -0,0 +1,311 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""第四章補跑實驗(data_1)。與 train_ablation.py 共用同一批窗、同一批 fold、同一套指標。
|
||||
|
||||
子命令:
|
||||
cross 跨組交叉:用第二組(A0)、第三組、第二+第三組(A1)訓練,測第二組(B0)、第三組(B1)、對照組
|
||||
rule 單一特徵不訓練的 AUC,以及邏輯斯迴歸
|
||||
fixed 固定門檻:訓練回合切 30% 當校準回合定門檻,再到測試回合量實際誤判率;另做跨玩家
|
||||
oof 焦點設定(W = 50、300)的 out-of-fold 分數,給 ROC 圖與回合分數圖用
|
||||
all 以上全部
|
||||
|
||||
範例:
|
||||
python scripts_1/extra_experiments.py all
|
||||
python scripts_1/extra_experiments.py cross --windows 300
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import roc_auc_score
|
||||
from sklearn.pipeline import make_pipeline
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
from mtd_common import RESULTS, utf8_stdout
|
||||
from mtd_windows import GroupRows, load_rounds, load_segments, make_windows, round_code, window_features
|
||||
from train_ablation import (assign_folds, balanced_weight, clopper_pearson, evaluate, fit_predict_gbdt, logit,
|
||||
upsert)
|
||||
|
||||
GROUPS = ['1', '2', '3', '3f']
|
||||
FOCUS_W = [50, 300, 1000]
|
||||
CROSS_TRAIN = {'2': ['2'], '3': ['3'], '2+3': ['2', '3']}
|
||||
CROSS_TEST = ['2', '3', '3f']
|
||||
TARGET_FPR = (0.01, 0.05)
|
||||
CALIB_FRAC = 0.30
|
||||
|
||||
|
||||
def feat_cols(F, use_dt):
|
||||
return list(F.columns) if use_dt else [c for c in F.columns if not c.startswith('t_')]
|
||||
|
||||
|
||||
class Ctx:
|
||||
"""載入一次:窗、fold、四組列。每個窗長的特徵快取起來。"""
|
||||
|
||||
def __init__(self, args):
|
||||
self.args = args
|
||||
self.segs, self.rounds = load_segments(), load_rounds()
|
||||
self.fold_of = assign_folds(self.rounds, args.folds, args.seed)
|
||||
self.rows = {g: GroupRows(g, 'deg', self.rounds) for g in GROUPS}
|
||||
self._cache = {}
|
||||
|
||||
def windows(self, W):
|
||||
if W not in self._cache:
|
||||
wins = make_windows(self.segs, W)
|
||||
F = {g: window_features(self.rows[g].slice(wins), True) for g in GROUPS}
|
||||
rc = round_code(wins.player, wins['round'])
|
||||
fold = np.array([self.fold_of[c] for c in rc.tolist()])
|
||||
self._cache[W] = (wins, F, rc, fold)
|
||||
return self._cache[W]
|
||||
|
||||
|
||||
def summary_rows(base, res):
|
||||
return [{**base, 'eval': name, **s} for name, s, _ in res]
|
||||
|
||||
|
||||
def eval_splits(meta, score, rounds, args, rng):
|
||||
out = []
|
||||
for name, sel in (('cv_all', np.ones(len(meta), bool)), ('cv_p1', meta.player.to_numpy() == 1),
|
||||
('cv_p2', meta.player.to_numpy() == 2)):
|
||||
ar = rounds if name == 'cv_all' else rounds[rounds.player == int(name[-1])]
|
||||
s, p = evaluate(meta[sel], score[sel], ar, args.boot, rng)
|
||||
out.append((name, s, p))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 1a 跨組交叉
|
||||
def run_cross(ctx, rng):
|
||||
a = ctx.args
|
||||
out = []
|
||||
for W in a.windows:
|
||||
wins, F, rc, fold = ctx.windows(W)
|
||||
y = wins.cheat.to_numpy()
|
||||
for use_dt in (1, 0):
|
||||
cols = feat_cols(F['2'], use_dt)
|
||||
X = {g: F[g][cols].to_numpy() for g in CROSS_TEST}
|
||||
for tname, tgroups in CROSS_TRAIN.items():
|
||||
oof = {g: np.full(len(y), np.nan) for g in CROSS_TEST}
|
||||
for k in range(a.folds):
|
||||
tr, te = np.where(fold != k)[0], np.where(fold == k)[0]
|
||||
Xtr = np.vstack([X[g][tr] for g in tgroups])
|
||||
ytr = np.concatenate([y[tr]] * len(tgroups))
|
||||
clf = gbdt_fit(Xtr, ytr, a.seed + k)
|
||||
for g in CROSS_TEST:
|
||||
oof[g][te] = logit(clf.predict_proba(X[g][te])[:, 1])
|
||||
for g in CROSS_TEST:
|
||||
res = eval_splits(wins, oof[g], ctx.rounds, a, rng)
|
||||
out += summary_rows(dict(train=tname, test=g, W_ms=W, dt=use_dt), res)
|
||||
s0 = res[0][1]
|
||||
print(f' cross W={W} dt={use_dt} train {tname:>3} -> test {g:>2}: '
|
||||
f'AUC {s0["win_auc"]:.3f} TPR@1% {s0["[email protected]"]:.3f} '
|
||||
f'round recall@1% {s0.get("round_recall@1%", np.nan):.3f}')
|
||||
upsert(RESULTS / 'cross_group.csv', out, ['train', 'test', 'W_ms', 'dt', 'eval'])
|
||||
out = []
|
||||
|
||||
|
||||
def gbdt_fit(Xtr, ytr, seed):
|
||||
from sklearn.ensemble import HistGradientBoostingClassifier
|
||||
clf = HistGradientBoostingClassifier(max_iter=200, learning_rate=0.1, l2_regularization=1.0,
|
||||
early_stopping=True, n_iter_no_change=10, random_state=seed)
|
||||
clf.fit(Xtr, ytr, sample_weight=balanced_weight(ytr))
|
||||
return clf
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 1b 單一規則 + 邏輯斯迴歸
|
||||
def run_rule(ctx, rng):
|
||||
a = ctx.args
|
||||
for W in a.windows:
|
||||
wins, F, rc, fold = ctx.windows(W)
|
||||
y = wins.cheat.to_numpy()
|
||||
pl = wins.player.to_numpy()
|
||||
out = []
|
||||
for g in GROUPS:
|
||||
Fg = F[g]
|
||||
for f in Fg.columns:
|
||||
v = Fg[f].to_numpy()
|
||||
for name, sel in (('all', np.ones(len(y), bool)), ('p1', pl == 1), ('p2', pl == 2)):
|
||||
if np.unique(v[sel]).size < 2:
|
||||
auc = 0.5
|
||||
else:
|
||||
auc = roc_auc_score(y[sel], v[sel])
|
||||
out.append(dict(group=g, W_ms=W, dt=int(f.startswith('t_')), feature=f, eval=name,
|
||||
kind='single', auc_raw=auc, auc_oriented=max(auc, 1 - auc),
|
||||
direction='higher=cheat' if auc >= 0.5 else 'lower=cheat'))
|
||||
for use_dt in (1, 0):
|
||||
cols = feat_cols(Fg, use_dt)
|
||||
Xg = Fg[cols].to_numpy()
|
||||
oof = np.full(len(y), np.nan)
|
||||
for k in range(a.folds):
|
||||
tr, te = np.where(fold != k)[0], np.where(fold == k)[0]
|
||||
m = make_pipeline(StandardScaler(), LogisticRegression(class_weight='balanced', max_iter=2000))
|
||||
m.fit(Xg[tr], y[tr])
|
||||
oof[te] = m.decision_function(Xg[te])
|
||||
res = eval_splits(wins, oof, ctx.rounds, a, rng)
|
||||
for name, s, _ in res:
|
||||
out.append(dict(group=g, W_ms=W, dt=use_dt, feature='logreg', eval=name.replace('cv_', ''),
|
||||
kind='logreg', auc_raw=s.get('win_auc'), auc_oriented=s.get('win_auc'),
|
||||
direction='', win_tpr_1=s.get('[email protected]'),
|
||||
round_auc=s.get('round_auc'), round_recall_1=s.get('round_recall@1%')))
|
||||
print(f' rule W={W} group {g:>2} dt={use_dt}: logreg AUC {res[0][1]["win_auc"]:.3f}')
|
||||
top = sorted([r for r in out if r['group'] == g and r['eval'] == 'all' and r['kind'] == 'single'],
|
||||
key=lambda r: -r['auc_oriented'])[:3]
|
||||
print(f' rule W={W} group {g:>2}: top single ' +
|
||||
', '.join(f'{r["feature"]} {r["auc_oriented"]:.3f}' for r in top))
|
||||
upsert(RESULTS / 'single_rule.csv', out, ['group', 'W_ms', 'dt', 'feature', 'eval'])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 1c 固定門檻
|
||||
def split_calib(rounds_df, frac, seed):
|
||||
"""依 player × cheat 分層,回傳校準回合的 round_code 集合。"""
|
||||
rng = np.random.default_rng(seed)
|
||||
cal = set()
|
||||
for _, s in rounds_df.groupby(['player', 'cheat']):
|
||||
codes = round_code(s.player, s['round'])
|
||||
n = max(1, int(round(frac * len(codes))))
|
||||
cal |= set(rng.choice(codes, n, replace=False).tolist())
|
||||
return cal
|
||||
|
||||
|
||||
def round_means(rc, y, s):
|
||||
d = pd.DataFrame(dict(rc=rc, y=y, s=s)).groupby('rc').agg(y=('y', 'first'), s=('s', 'mean'))
|
||||
return d.index.to_numpy(), d.y.to_numpy(), d.s.to_numpy()
|
||||
|
||||
|
||||
def thresholds(y_cal, s_cal, rc_cal):
|
||||
"""校準資料上的窗門檻與回合門檻(目標 FPR → 無作弊分數的上分位點)。"""
|
||||
neg = s_cal[y_cal == 0]
|
||||
_, ry, rs = round_means(rc_cal, y_cal, s_cal)
|
||||
rneg = rs[ry == 0]
|
||||
return ({f: float(np.quantile(neg, 1 - f)) for f in TARGET_FPR},
|
||||
{f: float(np.quantile(rneg, 1 - f)) for f in TARGET_FPR}, len(rneg))
|
||||
|
||||
|
||||
def apply_thr(y, s, rc, wthr, rthr):
|
||||
"""回傳每個目標 FPR 的 (窗 FP, 窗 N, 窗 TP, 窗 P, 回合 FP, 回合 N, 回合 TP, 回合 P)。"""
|
||||
_, ry, rs = round_means(rc, y, s)
|
||||
out = {}
|
||||
for f in TARGET_FPR:
|
||||
out[f] = np.array([((s > wthr[f]) & (y == 0)).sum(), (y == 0).sum(), ((s > wthr[f]) & (y == 1)).sum(),
|
||||
(y == 1).sum(), ((rs > rthr[f]) & (ry == 0)).sum(), (ry == 0).sum(),
|
||||
((rs > rthr[f]) & (ry == 1)).sum(), (ry == 1).sum()], dtype=float)
|
||||
return out
|
||||
|
||||
|
||||
def fixed_record(base, f, acc, n_cal_neg_rounds, fold_wfpr):
|
||||
wfp, wn, wtp, wp, rfp, rn, rtp, rp = acc
|
||||
lo, hi = clopper_pearson(int(rfp), int(rn)) if rn else (np.nan, np.nan)
|
||||
d = dict(**base, target_fpr=f, win_fpr=wfp / max(wn, 1), win_recall=wtp / max(wp, 1),
|
||||
round_fp=int(rfp), round_n_neg=int(rn), round_fpr=rfp / max(rn, 1), round_fpr_lo=lo, round_fpr_hi=hi,
|
||||
round_recall=rtp / max(rp, 1), n_calib_neg_rounds=n_cal_neg_rounds)
|
||||
if fold_wfpr:
|
||||
d['win_fpr_fold_min'] = float(np.min(fold_wfpr))
|
||||
d['win_fpr_fold_max'] = float(np.max(fold_wfpr))
|
||||
return d
|
||||
|
||||
|
||||
def run_fixed(ctx, rng):
|
||||
a = ctx.args
|
||||
for W in a.windows:
|
||||
wins, F, rc, fold = ctx.windows(W)
|
||||
y = wins.cheat.to_numpy()
|
||||
pl = wins.player.to_numpy()
|
||||
out = []
|
||||
for g in GROUPS:
|
||||
for use_dt in (1, 0):
|
||||
X = F[g][feat_cols(F[g], use_dt)].to_numpy()
|
||||
# 同玩家交叉驗證:每折都從訓練回合切出校準回合
|
||||
acc = {e: {f: np.zeros(8) for f in TARGET_FPR} for e in ('cv_all', 'cv_p1', 'cv_p2')}
|
||||
fold_wfpr = {f: [] for f in TARGET_FPR}
|
||||
ncal = []
|
||||
for k in range(a.folds):
|
||||
tr_rounds = ctx.rounds[[ctx.fold_of[c] != k for c in
|
||||
round_code(ctx.rounds.player, ctx.rounds['round']).tolist()]]
|
||||
cal = split_calib(tr_rounds, CALIB_FRAC, a.seed + k)
|
||||
is_cal = np.isin(rc, list(cal))
|
||||
tr = np.where((fold != k) & ~is_cal)[0]
|
||||
ca = np.where((fold != k) & is_cal)[0]
|
||||
te = np.where(fold == k)[0]
|
||||
clf = gbdt_fit(X[tr], y[tr], a.seed + k)
|
||||
s_ca = logit(clf.predict_proba(X[ca])[:, 1])
|
||||
s_te = logit(clf.predict_proba(X[te])[:, 1])
|
||||
wthr, rthr, nn = thresholds(y[ca], s_ca, rc[ca])
|
||||
ncal.append(nn)
|
||||
for e, sel in (('cv_all', np.ones(len(te), bool)), ('cv_p1', pl[te] == 1),
|
||||
('cv_p2', pl[te] == 2)):
|
||||
r = apply_thr(y[te][sel], s_te[sel], rc[te][sel], wthr, rthr)
|
||||
for f in TARGET_FPR:
|
||||
acc[e][f] += r[f]
|
||||
if e == 'cv_all':
|
||||
fold_wfpr[f].append(r[f][0] / max(r[f][1], 1))
|
||||
for e in acc:
|
||||
for f in TARGET_FPR:
|
||||
out.append(fixed_record(dict(group=g, W_ms=W, dt=use_dt, eval=e), f, acc[e][f],
|
||||
int(np.mean(ncal)), fold_wfpr[f] if e == 'cv_all' else None))
|
||||
# 跨玩家:門檻由訓練玩家的校準回合決定,鎖定後套到另一位玩家
|
||||
for pa, pb in ((1, 2), (2, 1)):
|
||||
ra = ctx.rounds[ctx.rounds.player == pa]
|
||||
cal = split_calib(ra, CALIB_FRAC, a.seed)
|
||||
is_cal = np.isin(rc, list(cal))
|
||||
tr = np.where((pl == pa) & ~is_cal)[0]
|
||||
ca = np.where((pl == pa) & is_cal)[0]
|
||||
te = np.where(pl == pb)[0]
|
||||
clf = gbdt_fit(X[tr], y[tr], a.seed)
|
||||
wthr, rthr, nn = thresholds(y[ca], logit(clf.predict_proba(X[ca])[:, 1]), rc[ca])
|
||||
r = apply_thr(y[te], logit(clf.predict_proba(X[te])[:, 1]), rc[te], wthr, rthr)
|
||||
for f in TARGET_FPR:
|
||||
out.append(fixed_record(dict(group=g, W_ms=W, dt=use_dt, eval=f'xfer_p{pa}to{pb}'), f, r[f],
|
||||
nn, None))
|
||||
cv1 = [o for o in out if o['group'] == g and o['dt'] == use_dt and o['eval'] == 'cv_all'
|
||||
and o['target_fpr'] == 0.01][-1]
|
||||
x12 = [o for o in out if o['group'] == g and o['dt'] == use_dt and o['eval'] == 'xfer_p1to2'
|
||||
and o['target_fpr'] == 0.01][-1]
|
||||
print(f' fixed W={W} group {g:>2} dt={use_dt}: target 1% -> CV win FPR {cv1["win_fpr"]:.4f} '
|
||||
f'recall {cv1["win_recall"]:.3f}; P1->P2 win FPR {x12["win_fpr"]:.3f} recall {x12["win_recall"]:.3f}')
|
||||
upsert(RESULTS / 'fixed_threshold.csv', out, ['group', 'W_ms', 'dt', 'target_fpr', 'eval'])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 1d OOF 分數
|
||||
def run_oof(ctx, rng):
|
||||
a = ctx.args
|
||||
parts = []
|
||||
for W in [w for w in a.windows if w in (50, 300)] or [300]:
|
||||
wins, F, rc, fold = ctx.windows(W)
|
||||
y = wins.cheat.to_numpy()
|
||||
for g in GROUPS:
|
||||
for use_dt in (1, 0):
|
||||
X = F[g][feat_cols(F[g], use_dt)].to_numpy()
|
||||
oof = np.full(len(y), np.nan)
|
||||
for k in range(a.folds):
|
||||
tr, te = np.where(fold != k)[0], np.where(fold == k)[0]
|
||||
oof[te] = fit_predict_gbdt(X[tr], y[tr], X[te], a.seed + k)
|
||||
d = wins[['player', 'round', 'cheat', 'strength', 'w0']].copy()
|
||||
d.insert(0, 'dt', use_dt)
|
||||
d.insert(0, 'W_ms', W)
|
||||
d.insert(0, 'group', g)
|
||||
d['score'] = oof
|
||||
parts.append(d)
|
||||
print(f' oof W={W} group {g:>2} dt={use_dt}: AUC {roc_auc_score(y, oof):.3f}')
|
||||
pd.concat(parts, ignore_index=True).to_csv(RESULTS / 'oof_scores.csv', index=False, float_format='%.6f')
|
||||
|
||||
|
||||
def main():
|
||||
utf8_stdout()
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('what', choices=['all', 'cross', 'rule', 'fixed', 'oof'])
|
||||
ap.add_argument('--windows', nargs='+', type=int, default=FOCUS_W)
|
||||
ap.add_argument('--folds', type=int, default=5)
|
||||
ap.add_argument('--seed', type=int, default=0)
|
||||
ap.add_argument('--boot', type=int, default=200)
|
||||
args = ap.parse_args()
|
||||
t0 = time.time()
|
||||
rng = np.random.default_rng(args.seed)
|
||||
ctx = Ctx(args)
|
||||
todo = ['cross', 'rule', 'fixed', 'oof'] if args.what == 'all' else [args.what]
|
||||
for w in todo:
|
||||
print(f'== {w} ==', flush=True)
|
||||
{'cross': run_cross, 'rule': run_rule, 'fixed': run_fixed, 'oof': run_oof}[w](ctx, rng)
|
||||
print(f'total {time.time() - t0:.0f}s')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,862 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""第四章的所有圖與表(data_1)。只讀 results_1/*.csv 與 data_1/ 的檔案,不訓練模型。
|
||||
|
||||
輸出:results_1/figures/*.png、results_1/chapter4_tables.md
|
||||
python scripts_1/make_figures.py # 全部
|
||||
python scripts_1/make_figures.py timeline # 只畫指定的圖(名稱見 FIGS)
|
||||
"""
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from mtd_common import COMMON, PLAYERS, RESULTS, group_path, load_round, md_table, utf8_stdout
|
||||
from mtd_windows import load_rounds, load_segments
|
||||
|
||||
FIG = RESULTS / 'figures'
|
||||
GL = {'1': '第一組 Unity', '2': '第二組 Raw+插入', '3': '第三組 Raw+平均', '3f': '對照組 幀時間插入'}
|
||||
GS = {'1': '第一組', '2': '第二組', '3': '第三組', '3f': '對照組'}
|
||||
SERIES = {'1': '#2a78d6', '2': '#eb6834', '3': '#1baf7a', '3f': '#eda100'} # 參考色盤前 4 槽,固定順序
|
||||
CAT = ['#2a78d6', '#eb6834', '#1baf7a', '#eda100']
|
||||
INK, MUTED, GRID, FAINT = '#0b0b0b', '#52514e', '#e4e3df', '#b9b7b0'
|
||||
GROUPS = ['1', '2', '3', '3f']
|
||||
DTL = {1: '含 Δt', 0: '不含 Δt'}
|
||||
|
||||
plt = None
|
||||
|
||||
|
||||
def setup():
|
||||
global plt
|
||||
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.update({'axes.unicode_minus': False, 'mathtext.fontset': 'dejavusans', 'font.size': 9, 'axes.titlesize': 10,
|
||||
'axes.edgecolor': GRID, 'axes.labelcolor': MUTED, 'xtick.color': MUTED,
|
||||
'ytick.color': MUTED, 'axes.grid': True, 'grid.color': GRID, 'grid.linewidth': 0.7,
|
||||
'axes.spines.top': False, 'axes.spines.right': False, 'legend.frameon': False,
|
||||
'figure.dpi': 100, 'savefig.dpi': 200, 'savefig.bbox': 'tight'})
|
||||
plt = _plt
|
||||
FIG.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def save(fig, name):
|
||||
fig.savefig(FIG / name)
|
||||
plt.close(fig)
|
||||
print(' wrote', FIG / name)
|
||||
|
||||
|
||||
def plain_ticks(ax, axis='y'):
|
||||
from matplotlib.ticker import FuncFormatter
|
||||
fmt = FuncFormatter(lambda v, _: f'{v:g}')
|
||||
(ax.yaxis if axis == 'y' else ax.xaxis).set_major_formatter(fmt)
|
||||
|
||||
|
||||
def line(ax, x, y, color, label=None, **kw):
|
||||
ax.plot(x, y, color=color, linewidth=2, marker='o', markersize=5, markeredgecolor='white',
|
||||
markeredgewidth=1.2, label=label, solid_capstyle='round', **kw)
|
||||
|
||||
|
||||
def logx_windows(ax, ticks, sparse=False):
|
||||
ax.set_xscale('log')
|
||||
ax.set_xticks(ticks)
|
||||
show = {8, 50, 300, 2000} if sparse else set(int(t) for t in ticks)
|
||||
ax.set_xticklabels([str(int(t)) if int(t) in show else '' for t in ticks], fontsize=8)
|
||||
ax.minorticks_off()
|
||||
|
||||
|
||||
def read_ab():
|
||||
ab = pd.read_csv(RESULTS / 'ablation.csv')
|
||||
ab['group'] = ab.group.astype(str)
|
||||
return ab
|
||||
|
||||
|
||||
# ================================================================ 時間軸圖
|
||||
_rows_cache = {}
|
||||
|
||||
|
||||
def group_rows(g):
|
||||
if g not in _rows_cache:
|
||||
_rows_cache[g] = pd.read_csv(group_path(g), usecols=['player', 'round', 'cheat', 'strength', 'frame', 't',
|
||||
'dx', 'dy', 'dx_deg', 'dy_deg', 'src', 'aim'])
|
||||
return _rows_cache[g]
|
||||
|
||||
|
||||
def pick_window(player, cheat, strength, mode, span=0.4, step=0.02):
|
||||
"""在瞄準片段內滑動,挑一段最能說明的 span 秒。mode: moving / still / nocheat。"""
|
||||
segs = load_segments()
|
||||
s = segs[(segs.player == player) & (segs.cheat == cheat) & (segs.strength == strength)
|
||||
& (segs.duration_ms >= span * 1000)]
|
||||
g2, g3 = group_rows('2'), group_rows('3')
|
||||
best, best_score = None, -np.inf
|
||||
for _, sg in s.iterrows():
|
||||
r2 = g2[(g2.player == player) & (g2['round'] == sg['round'])]
|
||||
r3 = g3[(g3.player == player) & (g3['round'] == sg['round'])]
|
||||
t2, src2, mv2 = r2.t.to_numpy(), r2.src.to_numpy(), ((r2.dx != 0) | (r2.dy != 0)).to_numpy()
|
||||
t3, src3 = r3.t.to_numpy(), r3.src.to_numpy()
|
||||
for w0 in np.arange(sg.t_start, sg.t_end - span, step):
|
||||
m2 = (t2 > w0) & (t2 <= w0 + span)
|
||||
m3 = (t3 > w0) & (t3 <= w0 + span)
|
||||
n_real = int((m2 & (src2 == 0) & mv2).sum())
|
||||
n_ins = int((m2 & (src2 == 1)).sum())
|
||||
n_syn = int((m3 & (src3 == 2)).sum())
|
||||
if mode == 'moving':
|
||||
score = n_real + 2 * min(n_ins, 20) if n_ins >= 15 and n_syn == 0 else -np.inf
|
||||
elif mode == 'still':
|
||||
score = 3 * n_syn + n_ins - 2 * n_real + (5 if n_real >= 3 else 0)
|
||||
else:
|
||||
score = n_real
|
||||
if score > best_score:
|
||||
best_score, best = score, (int(sg['round']), float(w0))
|
||||
return best
|
||||
|
||||
|
||||
def timeline(player, cheat, strength, mode, fname, span=0.4):
|
||||
pick = pick_window(player, cheat, strength, mode, span)
|
||||
if pick is None:
|
||||
print(' no window for', fname)
|
||||
return
|
||||
rnd, w0 = pick
|
||||
cfg, frames, _, _ = load_round(player, rnd)
|
||||
ft = frames.t.to_numpy()
|
||||
ft = ft[(ft > w0) & (ft <= w0 + span)]
|
||||
fig, axes = plt.subplots(3, 2, figsize=(10, 6.2), sharex=True, sharey='col')
|
||||
style = {0: dict(c=CAT[0], m='o', fc=CAT[0], label='滑鼠回報(第三組已加上平均分配的修正)'),
|
||||
1: dict(c=CAT[1], m='D', fc=CAT[1], label='第二組:每幀插入一列的外掛修正'),
|
||||
2: dict(c=CAT[2], m='o', fc='white', label='第三組:手不動時合成的回報')}
|
||||
g1style = dict(c=CAT[0], m='s', fc=CAT[0], label='第一組:每幀一列(滑鼠總和 + 修正)')
|
||||
handles = {}
|
||||
for i, g in enumerate(['1', '2', '3']):
|
||||
r = group_rows(g)
|
||||
r = r[(r.player == player) & (r['round'] == rnd) & (r.t > w0) & (r.t <= w0 + span)]
|
||||
x_ms = (r.t.to_numpy() - w0) * 1000
|
||||
for j, col in enumerate(['dx_deg', 'dy_deg']):
|
||||
ax = axes[i, j]
|
||||
for t in ft:
|
||||
ax.axvline((t - w0) * 1000, color=FAINT, linewidth=0.8, linestyle=(0, (3, 3)), zorder=0)
|
||||
ax.axhline(0, color=MUTED, linewidth=0.6, zorder=1)
|
||||
v = r[col].to_numpy()
|
||||
for sv in sorted(r.src.unique()):
|
||||
st = g1style if g == '1' else style[int(sv)]
|
||||
m = r.src.to_numpy() == sv
|
||||
ax.vlines(x_ms[m], 0, v[m], color=st['c'], linewidth=1.3, zorder=2)
|
||||
h = ax.scatter(x_ms[m], v[m], marker=st['m'], s=26, facecolor=st['fc'], edgecolor=st['c'],
|
||||
linewidth=1.3, zorder=3)
|
||||
handles.setdefault(st['label'], h)
|
||||
ax.grid(False)
|
||||
if i == 0:
|
||||
ax.set_title('水平位移 dx' if j == 0 else '垂直位移 dy', color=INK)
|
||||
if j == 0:
|
||||
ax.set_ylabel(f'{GL[g]}\n(度)', color=INK)
|
||||
if i == 2:
|
||||
ax.set_xlabel('時間 (ms,相對窗起點)')
|
||||
from matplotlib.lines import Line2D
|
||||
handles['幀邊界(遊戲讀取輸入的時刻)'] = Line2D([], [], color=FAINT, linestyle=(0, (3, 3)), linewidth=1)
|
||||
fig.legend(list(handles.values()), list(handles.keys()), loc='lower center', ncol=3, fontsize=8.5,
|
||||
bbox_to_anchor=(0.5, -0.06))
|
||||
cname = '無作弊' if cheat == 0 else f'輔助強度 {strength}%'
|
||||
fig.suptitle(f'玩家 {player},{cname},回合 {rnd},{int(span * 1000)} ms', color=INK, fontsize=11)
|
||||
fig.tight_layout()
|
||||
save(fig, fname)
|
||||
return rnd, w0
|
||||
|
||||
|
||||
def fig_timelines():
|
||||
meta = []
|
||||
for args in ((1, 1, 60, 'moving', 'fig_timeline_moving.png'), (2, 1, 60, 'still', 'fig_timeline_still.png'),
|
||||
(1, 0, 0, 'nocheat', 'fig_timeline_nocheat.png')):
|
||||
r = timeline(*args)
|
||||
if r:
|
||||
meta.append(dict(figure=args[4], player=args[0], cheat=args[1], strength=args[2], round=r[0],
|
||||
w0=r[1]))
|
||||
pd.DataFrame(meta).to_csv(FIG / 'timeline_windows.csv', index=False)
|
||||
|
||||
|
||||
# ================================================================ 間隔分布
|
||||
def row_gaps(g):
|
||||
r = group_rows(g)
|
||||
r = r.sort_values(['player', 'round', 't'])
|
||||
gap = r.t.diff().to_numpy() * 1000
|
||||
same = (r.player.diff() == 0) & (r['round'].diff() == 0)
|
||||
keep = same.to_numpy() & (r.aim.to_numpy() == 1)
|
||||
return gap[keep], r.cheat.to_numpy()[keep], r.player.to_numpy()[keep]
|
||||
|
||||
|
||||
def fig_gap_hist():
|
||||
fig, axes = plt.subplots(2, 2, figsize=(10, 6), sharey=True)
|
||||
bins = np.arange(0, 20.25, 0.25)
|
||||
for ax, g in zip(axes.ravel(), GROUPS):
|
||||
gap, c, _ = row_gaps(g)
|
||||
for cv, col, lab in ((0, CAT[0], '無作弊'), (1, CAT[1], '作弊')):
|
||||
h, e = np.histogram(gap[c == cv], bins=bins)
|
||||
ax.step(e[:-1], h / max(h.sum(), 1), where='post', color=col, linewidth=1.6, label=lab)
|
||||
for k in (8, 16):
|
||||
ax.axvline(k, color=MUTED, linewidth=0.8, linestyle=(0, (3, 3)))
|
||||
ax.axvline(1000 / 60, color=FAINT, linewidth=0.8)
|
||||
ax.set_yscale('log')
|
||||
plain_ticks(ax)
|
||||
ax.set_title(GL[g], color=INK)
|
||||
ax.set_xlabel('相鄰兩列的時間間隔 (ms)')
|
||||
axes[0, 0].set_ylabel('比例(對數刻度)')
|
||||
axes[1, 0].set_ylabel('比例(對數刻度)')
|
||||
axes[0, 0].legend(loc='upper left')
|
||||
fig.text(0.5, -0.02, '虛線:8 ms 與 16 ms(滑鼠 125 Hz 的回報格點);淺實線:16.7 ms(60 Hz 幀間隔)。只計瞄準期間的列。',
|
||||
ha='center', color=MUTED, fontsize=8.5)
|
||||
fig.tight_layout()
|
||||
save(fig, 'fig_gap_hist.png')
|
||||
|
||||
|
||||
def fig_ongrid():
|
||||
gt = pd.read_csv(COMMON / 'gap_table.csv')
|
||||
gt['group'] = gt.group.astype(str)
|
||||
cats = [('無作弊 全部列', lambda d: d[(d.cheat == 0) & (d.src == 'all')]),
|
||||
('作弊 滑鼠回報列', lambda d: d[(d.cheat == 1) & (d.src == '0')]),
|
||||
('作弊 插入或合成列', lambda d: d[(d.cheat == 1) & d.src.isin(['1', '2'])]),
|
||||
('作弊 全部列', lambda d: d[(d.cheat == 1) & (d.src == 'all')])]
|
||||
gs = ['2', '3', '3f']
|
||||
fig, ax = plt.subplots(figsize=(8.5, 3.6))
|
||||
wbar = 0.2
|
||||
for i, (lab, f) in enumerate(cats):
|
||||
vals = []
|
||||
for g in gs:
|
||||
s = f(gt[gt.group == g])
|
||||
vals.append(float(s.on_grid.iloc[0]) if len(s) else np.nan)
|
||||
xs = np.arange(len(gs)) + (i - 1.5) * wbar
|
||||
ax.bar(xs, vals, width=wbar - 0.02, color=CAT[i], label=lab)
|
||||
for x, v in zip(xs, vals):
|
||||
if not np.isnan(v):
|
||||
ax.text(x, v + 0.015, f'{v:.2f}', ha='center', fontsize=7.5, color=MUTED)
|
||||
ax.set_xticks(range(len(gs)))
|
||||
ax.set_xticklabels([GL[g] for g in gs])
|
||||
ax.set_ylim(0, 1.08)
|
||||
ax.set_ylabel('間隔落在 8 ms 格點(±0.5 ms)的比例')
|
||||
ax.grid(axis='x', visible=False)
|
||||
ax.legend(ncol=4, loc='upper center', bbox_to_anchor=(0.5, -0.12), fontsize=8)
|
||||
save(fig, 'fig_ongrid.png')
|
||||
|
||||
|
||||
# ================================================================ AUC 對窗長
|
||||
def auc_grid(ab, evals, titles, fname, model='gbdt'):
|
||||
d = ab[(ab.model == model) & (ab.segset == 'all')]
|
||||
fig, axes = plt.subplots(len(evals), 2, figsize=(10, 3.6 * len(evals)), sharey=True, squeeze=False)
|
||||
for i, ev in enumerate(evals):
|
||||
for j, dt in enumerate((1, 0)):
|
||||
ax = axes[i, j]
|
||||
sub = d[(d['eval'] == ev) & (d.dt == dt)]
|
||||
for g in GROUPS:
|
||||
s = sub[sub.group == 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)
|
||||
line(ax, s.W_ms, s.win_auc, SERIES[g], GL[g])
|
||||
ax.axhline(0.5, color=MUTED, linewidth=0.8, linestyle=(0, (3, 3)))
|
||||
logx_windows(ax, sorted(sub.W_ms.unique()))
|
||||
ax.set_title(f'{titles[i]},{DTL[dt]}', color=INK)
|
||||
ax.set_xlabel('時間窗長度 (ms,對數刻度)')
|
||||
if j == 0:
|
||||
ax.set_ylabel('窗層級 AUC')
|
||||
h, l = axes[0, 0].get_legend_handles_labels()
|
||||
fig.legend(h, l, loc='lower center', ncol=4, fontsize=8.5, bbox_to_anchor=(0.5, -0.01))
|
||||
fig.tight_layout(rect=(0, 0.04 if len(evals) > 1 else 0.07, 1, 1))
|
||||
save(fig, fname)
|
||||
|
||||
|
||||
def fig_auc_windows():
|
||||
ab = read_ab()
|
||||
auc_grid(ab, ['cv_all'], ['GBDT 5 折交叉驗證(兩位玩家合併)'], 'fig_auc_vs_window.png')
|
||||
auc_grid(ab, ['cv_p1', 'cv_p2'], ['玩家 1 的窗', '玩家 2 的窗'], 'fig_auc_vs_window_players.png')
|
||||
auc_grid(ab, ['xfer_p1to2', 'xfer_p2to1'], ['玩家 1 訓練 → 玩家 2 測試', '玩家 2 訓練 → 玩家 1 測試'],
|
||||
'fig_auc_vs_window_xfer.png')
|
||||
|
||||
|
||||
def fig_tpr_windows():
|
||||
"""誤判率 1% 時的窗召回率對窗長(比 AUC 更接近部署條件)。"""
|
||||
ab = read_ab()
|
||||
d = ab[(ab.model == 'gbdt') & (ab.segset == 'all') & (ab['eval'] == 'cv_all')]
|
||||
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), sharey=True)
|
||||
for ax, dt in zip(axes, (1, 0)):
|
||||
sub = d[d.dt == dt]
|
||||
for g in GROUPS:
|
||||
s = sub[sub.group == g].sort_values('W_ms')
|
||||
line(ax, s.W_ms, s['[email protected]'], SERIES[g], GL[g])
|
||||
logx_windows(ax, sorted(sub.W_ms.unique()))
|
||||
ax.set_ylim(0, 1.03)
|
||||
ax.set_title(f'GBDT,{DTL[dt]}', color=INK)
|
||||
ax.set_xlabel('時間窗長度 (ms,對數刻度)')
|
||||
axes[0].set_ylabel('窗召回率(窗誤判率 1%)')
|
||||
axes[0].legend(loc='lower right', fontsize=8)
|
||||
fig.tight_layout()
|
||||
save(fig, 'fig_tpr1_vs_window.png')
|
||||
|
||||
|
||||
def fig_models():
|
||||
ab = read_ab()
|
||||
d = ab[(ab.segset == 'all') & (ab['eval'] == 'cv_all')]
|
||||
fig, axes = plt.subplots(1, 4, figsize=(13, 3.4), sharey=True)
|
||||
combos = [('gbdt', 1, CAT[0], '-'), ('gbdt', 0, CAT[1], '-'), ('cnn', 1, CAT[2], '--'), ('cnn', 0, CAT[3], '--')]
|
||||
for ax, g in zip(axes, GROUPS):
|
||||
for m, dt, c, ls in combos:
|
||||
s = d[(d.group == g) & (d.model == m) & (d.dt == dt)].sort_values('W_ms')
|
||||
line(ax, s.W_ms, s.win_auc, c, f'{m.upper()} {DTL[dt]}', linestyle=ls)
|
||||
logx_windows(ax, sorted(d.W_ms.unique()), sparse=True)
|
||||
ax.set_title(GL[g], color=INK)
|
||||
ax.set_xlabel('時間窗 (ms,對數刻度)')
|
||||
axes[0].set_ylabel('窗層級 AUC')
|
||||
axes[0].legend(loc='lower right', fontsize=7.5)
|
||||
fig.tight_layout()
|
||||
save(fig, 'fig_gbdt_vs_cnn.png')
|
||||
|
||||
|
||||
def fig_window_coverage():
|
||||
"""各窗長下仍能使用的瞄準時間比例(片段短於窗長就丟棄)。"""
|
||||
segs = load_segments()
|
||||
Ws = np.array([8, 16, 33, 50, 100, 200, 300, 500, 1000, 2000])
|
||||
fig, ax = plt.subplots(figsize=(6.5, 3.6))
|
||||
i = 0
|
||||
for p in (1, 2):
|
||||
for c in (0, 1):
|
||||
s = segs[(segs.player == p) & (segs.cheat == c)]
|
||||
tot = s.duration_ms.sum()
|
||||
cov = [s.duration_ms[s.duration_ms >= W].sum() / tot for W in Ws]
|
||||
line(ax, Ws, cov, CAT[i], f'玩家 {p} {"作弊" if c else "無作弊"}')
|
||||
i += 1
|
||||
logx_windows(ax, Ws)
|
||||
ax.set_ylim(0, 1.03)
|
||||
ax.set_xlabel('時間窗長度 (ms,對數刻度)')
|
||||
ax.set_ylabel('可用瞄準時間比例')
|
||||
ax.legend(fontsize=8, loc='lower left')
|
||||
save(fig, 'fig_window_coverage.png')
|
||||
|
||||
|
||||
# ================================================================ 強度、ROC、回合分數
|
||||
def fig_strength():
|
||||
ps = pd.read_csv(RESULTS / 'per_strength.csv')
|
||||
ps['group'] = ps.group.astype(str)
|
||||
ps = ps[(ps.model == 'gbdt') & (ps.segset == 'all') & (ps['eval'] == 'cv_all')]
|
||||
fig, axes = plt.subplots(2, 2, figsize=(10, 6.4), sharey=True, sharex=True)
|
||||
for i, W in enumerate((50, 300)):
|
||||
for j, dt in enumerate((1, 0)):
|
||||
ax = axes[i, j]
|
||||
for g in GROUPS:
|
||||
s = ps[(ps.W_ms == W) & (ps.dt == dt) & (ps.group == g)].sort_values('strength')
|
||||
line(ax, s.strength, s['[email protected]'], SERIES[g], GL[g])
|
||||
ax.set_ylim(0, 1.03)
|
||||
ax.set_xticks([20, 40, 60, 80, 100])
|
||||
ax.set_title(f'W = {W} ms,{DTL[dt]}', color=INK)
|
||||
if i == 1:
|
||||
ax.set_xlabel('輔助強度 (%)')
|
||||
if j == 0:
|
||||
ax.set_ylabel('窗召回率(窗誤判率 1%)')
|
||||
axes[1, 1].legend(loc='lower right', fontsize=8)
|
||||
fig.tight_layout()
|
||||
save(fig, 'fig_strength.png')
|
||||
|
||||
|
||||
def read_oof():
|
||||
p = RESULTS / 'oof_scores.csv'
|
||||
if not p.exists():
|
||||
return None
|
||||
o = pd.read_csv(p, dtype={'group': str})
|
||||
o['group'] = o.group.astype(str)
|
||||
return o
|
||||
|
||||
|
||||
def fig_roc():
|
||||
from sklearn.metrics import roc_curve
|
||||
o = read_oof()
|
||||
if o is None:
|
||||
return
|
||||
fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
|
||||
for ax, dt in zip(axes, (1, 0)):
|
||||
for g in GROUPS:
|
||||
s = o[(o.W_ms == 300) & (o.dt == dt) & (o.group == g)]
|
||||
fpr, tpr, _ = roc_curve(s.cheat, s.score)
|
||||
ax.plot(np.maximum(fpr, 1e-4), tpr, color=SERIES[g], linewidth=2, label=GL[g])
|
||||
ax.axvline(0.01, color=MUTED, linewidth=0.8, linestyle=(0, (3, 3)))
|
||||
ax.text(0.0105, 0.03, '誤判率 1%', color=MUTED, fontsize=8)
|
||||
ax.set_xscale('log')
|
||||
plain_ticks(ax, 'x')
|
||||
ax.set_xlim(1e-3, 1)
|
||||
ax.set_ylim(0, 1.02)
|
||||
ax.set_title(f'W = 300 ms,{DTL[dt]}', color=INK)
|
||||
ax.set_xlabel('窗誤判率 FPR(對數刻度)')
|
||||
axes[0].set_ylabel('窗召回率 TPR')
|
||||
axes[1].legend(loc='lower right', fontsize=8)
|
||||
fig.tight_layout()
|
||||
save(fig, 'fig_roc.png')
|
||||
|
||||
|
||||
def fig_round_scores():
|
||||
o = read_oof()
|
||||
if o is None:
|
||||
return
|
||||
W = 300
|
||||
cats = [0, 20, 40, 60, 80, 100]
|
||||
fig, axes = plt.subplots(2, 4, figsize=(13, 6), sharex=True)
|
||||
rng = np.random.default_rng(0)
|
||||
for i, dt in enumerate((1, 0)):
|
||||
for j, g in enumerate(GROUPS):
|
||||
ax = axes[i, j]
|
||||
s = o[(o.W_ms == W) & (o.dt == dt) & (o.group == g)]
|
||||
rd = s.groupby(['player', 'round']).agg(score=('score', 'mean'), cheat=('cheat', 'first'),
|
||||
strength=('strength', 'first')).reset_index()
|
||||
neg = np.sort(rd.score[rd.cheat == 0].to_numpy())[::-1]
|
||||
thr = neg[int(np.floor(0.01 * len(neg)))]
|
||||
for k, st in enumerate(cats):
|
||||
for p, mk in ((1, 'o'), (2, '^')):
|
||||
v = rd[(rd.strength == st) & (rd.player == p)].score.to_numpy()
|
||||
x = k + (p - 1.5) * 0.3 + rng.uniform(-0.1, 0.1, len(v))
|
||||
ax.scatter(x, v, s=12, marker=mk, color=CAT[0] if st == 0 else CAT[1], alpha=0.7,
|
||||
edgecolor='white', linewidth=0.4,
|
||||
label=(f'玩家 {p}' if k == 1 else None))
|
||||
ax.axhline(thr, color=INK, linewidth=0.9, linestyle=(0, (4, 3)))
|
||||
fp = int((rd.score[rd.cheat == 0] > thr).sum())
|
||||
miss = int((rd.score[rd.cheat == 1] <= thr).sum())
|
||||
ax.set_title(f'{GL[g]},{DTL[dt]}\n漏抓 {miss} / {int((rd.cheat == 1).sum())} 個作弊回合', color=INK, fontsize=9)
|
||||
ax.set_xticks(range(len(cats)))
|
||||
ax.set_xticklabels(['無作弊'] + [f'{c}%' for c in cats[1:]], fontsize=8)
|
||||
ax.grid(axis='x', visible=False)
|
||||
if j == 0:
|
||||
ax.set_ylabel('回合平均 logit')
|
||||
from matplotlib.lines import Line2D
|
||||
hs = [Line2D([], [], marker='o', linestyle='', color=MUTED, label='玩家 1'),
|
||||
Line2D([], [], marker='^', linestyle='', color=MUTED, label='玩家 2'),
|
||||
Line2D([], [], marker='o', linestyle='', color=CAT[0], label='無作弊回合'),
|
||||
Line2D([], [], marker='o', linestyle='', color=CAT[1], label='作弊回合'),
|
||||
Line2D([], [], color=INK, linestyle=(0, (4, 3)), label='回合誤判率 1% 門檻')]
|
||||
fig.legend(handles=hs, loc='lower center', ncol=5, bbox_to_anchor=(0.5, -0.03))
|
||||
fig.tight_layout(rect=(0, 0.03, 1, 1))
|
||||
save(fig, 'fig_round_scores.png')
|
||||
|
||||
|
||||
# ================================================================ 補跑實驗
|
||||
def fig_cross_group():
|
||||
p = RESULTS / 'cross_group.csv'
|
||||
if not p.exists():
|
||||
return
|
||||
cg = pd.read_csv(p, dtype={'train': str, 'test': str})
|
||||
cg = cg[cg['eval'] == 'cv_all']
|
||||
trains = [('2', '只用第二組訓練(A0)'), ('3', '只用第三組訓練'), ('2+3', '第二 + 第三組訓練(A1)')]
|
||||
tests = ['2', '3', '3f']
|
||||
Ws = sorted(cg.W_ms.unique())
|
||||
fig, axes = plt.subplots(len(Ws), 2, figsize=(10, 3.1 * len(Ws)), sharey=True, squeeze=False)
|
||||
for i, W in enumerate(Ws):
|
||||
for j, dt in enumerate((1, 0)):
|
||||
ax = axes[i, j]
|
||||
for k, (t, lab) in enumerate(trains):
|
||||
vals = [cg[(cg.W_ms == W) & (cg.dt == dt) & (cg.train == t) & (cg.test == g)]['[email protected]']
|
||||
.mean() for g in tests]
|
||||
xs = np.arange(len(tests)) + (k - 1) * 0.26
|
||||
ax.bar(xs, vals, width=0.24, color=CAT[k], label=lab)
|
||||
for x, v in zip(xs, vals):
|
||||
ax.text(x, v + 0.02, f'{v:.2f}', ha='center', fontsize=7, color=MUTED)
|
||||
ax.set_xticks(range(len(tests)))
|
||||
ax.set_xticklabels([f'測試:{GS[g]}' for g in tests])
|
||||
ax.set_ylim(0, 1.12)
|
||||
ax.grid(axis='x', visible=False)
|
||||
ax.set_title(f'W = {W} ms,{DTL[dt]}', color=INK)
|
||||
if j == 0:
|
||||
ax.set_ylabel('窗召回率(誤判率 1%)')
|
||||
h, l = axes[0, 0].get_legend_handles_labels()
|
||||
fig.legend(h, l, loc='upper center', ncol=3, fontsize=8.5, bbox_to_anchor=(0.5, 1.0))
|
||||
fig.tight_layout(rect=(0, 0, 1, 0.97))
|
||||
save(fig, 'fig_cross_group.png')
|
||||
|
||||
|
||||
FEAT_ZH = {
|
||||
'n_rows': '列數', 'sum_x': '水平位移總和', 'sum_y': '垂直位移總和', 'path': '路徑長', 'net': '淨位移',
|
||||
'straight': '直線度', 'mean_m': '平均位移量', 'std_x': '水平位移標準差', 'std_y': '垂直位移標準差',
|
||||
'std_m': '位移量標準差', 'max_abs_x': '最大水平位移', 'max_abs_y': '最大垂直位移', 'max_m': '最大位移量',
|
||||
'frac_zero': '零位移列比例', 'frac_one': '±1 count 列比例', 'frac_left': '按住左鍵比例',
|
||||
'mean_dd': '相鄰列位移差平均', 'std_dd': '相鄰列位移差標準差', 'max_dd': '相鄰列位移差最大',
|
||||
'mean_cos': '相鄰列方向餘弦平均', 'frac_reverse': '方向反轉比例', 'ac1_m': '位移量 lag-1 自相關',
|
||||
't_rate': '列率', 't_gap_mean': '間隔平均', 't_gap_std': '間隔標準差', 't_gap_min': '最小間隔',
|
||||
't_gap_max': '最大間隔', 't_frac_offgrid': '間隔不在 8 ms 格點的比例', 't_mean_resid': '間隔離格點的平均距離',
|
||||
't_frac_short': '短間隔(< 0.5 週期)比例', 't_frac_long': '長間隔(> 1.5 週期)比例',
|
||||
't_first': '第一列離窗起點', 't_last': '最後一列離窗終點', 't_speed_mean': '速度平均', 't_speed_max': '速度最大',
|
||||
't_acc_mean': '加速度平均', 't_acc_max': '加速度最大'}
|
||||
|
||||
|
||||
def fig_single_rule(W=300):
|
||||
p = RESULTS / 'single_rule.csv'
|
||||
if not p.exists():
|
||||
return
|
||||
sr = pd.read_csv(p, dtype={'group': str})
|
||||
s = sr[(sr.W_ms == W) & (sr['eval'] == 'all') & (sr.kind == 'single')]
|
||||
top = s.groupby('feature').auc_oriented.max().sort_values(ascending=False).head(14).index.tolist()[::-1]
|
||||
fig, ax = plt.subplots(figsize=(8, 5.6))
|
||||
for k, g in enumerate(GROUPS):
|
||||
v = s[s.group == g].set_index('feature').auc_oriented.reindex(top)
|
||||
ax.scatter(v.to_numpy(), np.arange(len(top)) + (k - 1.5) * 0.15, s=30, color=SERIES[g],
|
||||
edgecolor='white', linewidth=0.8, label=GL[g], zorder=3)
|
||||
lr = sr[(sr.W_ms == W) & (sr['eval'] == 'all') & (sr.kind == 'logreg') & (sr.dt == 1)]
|
||||
ax.set_yticks(range(len(top)))
|
||||
ax.set_yticklabels([f'{FEAT_ZH.get(f, f)}{" [時間]" if f.startswith("t_") else ""}' for f in top], fontsize=8)
|
||||
ax.axvline(0.5, color=MUTED, linewidth=0.8, linestyle=(0, (3, 3)))
|
||||
ax.set_xlabel('單一特徵直接當分數的 AUC(不訓練;取較好的方向)')
|
||||
ax.set_title(f'W = {W} ms,兩位玩家合併', color=INK)
|
||||
ax.legend(loc='lower right', fontsize=8)
|
||||
ax.grid(axis='y', visible=False)
|
||||
save(fig, 'fig_single_rule.png')
|
||||
|
||||
|
||||
def fig_baselines(W=300):
|
||||
"""同一窗長:最佳單一特徵、邏輯斯迴歸、GBDT 的 AUC 與誤判率 1% 召回率。"""
|
||||
p = RESULTS / 'single_rule.csv'
|
||||
if not p.exists():
|
||||
return
|
||||
sr = pd.read_csv(p, dtype={'group': str})
|
||||
ab = read_ab()
|
||||
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), sharey=True)
|
||||
for ax, dt in zip(axes, (1, 0)):
|
||||
vals = {'最佳單一特徵': [], '邏輯斯迴歸': [], 'GBDT': []}
|
||||
for g in GROUPS:
|
||||
s = sr[(sr.W_ms == W) & (sr['eval'] == 'all') & (sr.group == g)]
|
||||
single = s[(s.kind == 'single') & ((s.dt == 0) | (dt == 1))]
|
||||
vals['最佳單一特徵'].append(single.auc_oriented.max())
|
||||
vals['邏輯斯迴歸'].append(s[(s.kind == 'logreg') & (s.dt == dt)].auc_raw.mean())
|
||||
vals['GBDT'].append(ab[(ab.model == 'gbdt') & (ab.segset == 'all') & (ab['eval'] == 'cv_all')
|
||||
& (ab.group == g) & (ab.W_ms == W) & (ab.dt == dt)].win_auc.mean())
|
||||
for k, (lab, v) in enumerate(vals.items()):
|
||||
xs = np.arange(len(GROUPS)) + (k - 1) * 0.26
|
||||
ax.bar(xs, v, width=0.24, color=CAT[k], label=lab)
|
||||
for x, y in zip(xs, v):
|
||||
ax.text(x, y + 0.005, f'{y:.2f}', ha='center', fontsize=7, color=MUTED)
|
||||
ax.set_xticks(range(len(GROUPS)))
|
||||
ax.set_xticklabels([GS[g] for g in GROUPS])
|
||||
ax.set_ylim(0, 1.08)
|
||||
ax.grid(axis='x', visible=False)
|
||||
ax.set_title(f'W = {W} ms,{DTL[dt]}', color=INK)
|
||||
axes[0].set_ylabel('窗層級 AUC')
|
||||
h, l = axes[0].get_legend_handles_labels()
|
||||
fig.legend(h, l, loc='lower center', ncol=3, fontsize=8.5, bbox_to_anchor=(0.5, -0.02))
|
||||
fig.tight_layout(rect=(0, 0.06, 1, 1))
|
||||
save(fig, 'fig_baselines.png')
|
||||
|
||||
|
||||
def fig_fixed_threshold(W=300):
|
||||
p = RESULTS / 'fixed_threshold.csv'
|
||||
if not p.exists():
|
||||
return
|
||||
ft = pd.read_csv(p, dtype={'group': str})
|
||||
ft = ft[ft.W_ms == W]
|
||||
evs = [('cv_all', '同玩家交叉驗證', CAT[0], 'o'), ('xfer_p1to2', '玩家 1 → 玩家 2', CAT[1], 'D'),
|
||||
('xfer_p2to1', '玩家 2 → 玩家 1', CAT[2], '^')]
|
||||
cats = [(g, dt) for g in GROUPS for dt in (1, 0)]
|
||||
fig, axes = plt.subplots(2, 2, figsize=(11, 6.4), sharex=True)
|
||||
for j, tf in enumerate((0.01, 0.05)):
|
||||
for i, (col, ylab) in enumerate((('win_fpr', '實測窗誤判率'), ('win_recall', '窗召回率'))):
|
||||
ax = axes[i, j]
|
||||
for k, (ev, lab, c, mk) in enumerate(evs):
|
||||
v = [ft[(ft.group == g) & (ft.dt == dt) & (ft['eval'] == ev) & (ft.target_fpr == tf)][col].mean()
|
||||
for g, dt in cats]
|
||||
ax.scatter(np.arange(len(cats)) + (k - 1) * 0.18, v, color=c, marker=mk, s=34, edgecolor='white',
|
||||
linewidth=0.8, label=lab, zorder=3)
|
||||
if col == 'win_fpr':
|
||||
ax.axhline(tf, color=INK, linewidth=0.9, linestyle=(0, (4, 3)))
|
||||
ax.set_yscale('symlog', linthresh=0.01)
|
||||
plain_ticks(ax)
|
||||
ax.set_ylim(0, 1)
|
||||
ax.set_title(f'目標誤判率 {tf:.0%}(由校準回合決定門檻)', color=INK)
|
||||
else:
|
||||
ax.set_ylim(0, 1.03)
|
||||
ax.set_xticks(range(len(cats)))
|
||||
ax.set_xticklabels([f'{GS[g]}\n{DTL[dt]}' for g, dt in cats], fontsize=7.5)
|
||||
ax.grid(axis='x', visible=False)
|
||||
if j == 0:
|
||||
ax.set_ylabel(ylab)
|
||||
axes[0, 0].legend(loc='upper left', fontsize=8)
|
||||
fig.tight_layout()
|
||||
save(fig, 'fig_fixed_threshold.png')
|
||||
|
||||
|
||||
def fig_benefit():
|
||||
p = RESULTS / 'benefit.csv'
|
||||
if not p.exists():
|
||||
return
|
||||
b = pd.read_csv(p)
|
||||
fig, axes = plt.subplots(1, 3, figsize=(13, 3.8))
|
||||
for k, pl in enumerate((1, 2)):
|
||||
s = b[b.player == pl].sort_values('strength')
|
||||
line(axes[0], s.strength, s.hit_rate_mean, CAT[k], f'玩家 {pl}')
|
||||
line(axes[1], s.strength, s.ttk_mean, CAT[k], f'玩家 {pl}')
|
||||
axes[0].set_xlabel('輔助強度 (%),0 = 無作弊')
|
||||
axes[0].set_ylabel('命中率(命中 / 開槍)')
|
||||
axes[1].set_xlabel('輔助強度 (%),0 = 無作弊')
|
||||
axes[1].set_ylabel('平均擊倒時間 (s)')
|
||||
for ax in axes[:2]:
|
||||
ax.set_xticks([0, 20, 40, 60, 80, 100])
|
||||
ax.legend(fontsize=8)
|
||||
ax = axes[2]
|
||||
s = b[b.strength > 0]
|
||||
for g in ('1', '2', '3'):
|
||||
for pl, mk in ((1, 'o'), (2, '^')):
|
||||
q = s[s.player == pl]
|
||||
ax.scatter(q.hit_rate_gain, q[f'win_tpr1_g{g}_nodt'], color=SERIES[g], marker=mk, s=34,
|
||||
edgecolor='white', linewidth=0.8, zorder=3)
|
||||
from matplotlib.lines import Line2D
|
||||
hs = [Line2D([], [], marker='o', linestyle='', color=SERIES[g], label=GS[g]) for g in ('1', '2', '3')]
|
||||
hs += [Line2D([], [], marker='o', linestyle='', color=MUTED, label='玩家 1'),
|
||||
Line2D([], [], marker='^', linestyle='', color=MUTED, label='玩家 2')]
|
||||
ax.set_xlabel('命中率提升(相對該玩家無作弊)')
|
||||
ax.set_ylabel('窗召回率(誤判率 1%,W = 300,不含 Δt)')
|
||||
ax.set_ylim(0, 1.05)
|
||||
ax.legend(handles=hs, fontsize=8, loc='lower right', ncol=2)
|
||||
ax.set_title('每點 = 一位玩家的一個強度', color=MUTED, fontsize=9)
|
||||
fig.tight_layout()
|
||||
save(fig, 'fig_benefit.png')
|
||||
|
||||
|
||||
def fig_nuisance():
|
||||
nu = pd.read_csv(RESULTS / 'nuisance.csv')
|
||||
nu['group'] = nu.group.astype(str)
|
||||
nu = nu[nu['eval'] == 'cv_all']
|
||||
cats = [('1', 1), ('1', 0), ('2', 1), ('2', 0)]
|
||||
labels = ['第一組\n含 Δt', '第一組\n不含 Δt', '第二、三組\n含 Δt', '第二、三組\n不含 Δt']
|
||||
fig, ax = plt.subplots(figsize=(7, 3.6))
|
||||
for k, (g, dt) in enumerate(cats):
|
||||
r = nu[(nu.group == g) & (nu.dt == dt)].iloc[0]
|
||||
ax.errorbar(k - 0.1, r.win_auc, yerr=[[r.win_auc - r.win_auc_lo], [r.win_auc_hi - r.win_auc]],
|
||||
fmt='o', color=CAT[0], markersize=6, capsize=3, label='窗層級 AUC(95% CI)' if k == 0 else None)
|
||||
ax.scatter(k + 0.1, r.round_auc, marker='D', color=CAT[1], s=34, zorder=3,
|
||||
label='回合層級 AUC' if k == 0 else None)
|
||||
ax.axhline(0.5, color=MUTED, linewidth=0.8, linestyle=(0, (3, 3)))
|
||||
ax.set_xticks(range(len(cats)))
|
||||
ax.set_xticklabels(labels)
|
||||
ax.set_ylim(0.4, 0.9)
|
||||
ax.set_ylabel('AUC(分辨前 50 / 後 50 個無作弊回合)')
|
||||
ax.legend(fontsize=8, loc='upper right')
|
||||
ax.grid(axis='x', visible=False)
|
||||
save(fig, 'fig_nuisance.png')
|
||||
|
||||
|
||||
# ================================================================ 表格
|
||||
def f3(v):
|
||||
return '' if pd.isna(v) else f'{v:.3f}'
|
||||
|
||||
|
||||
def tables():
|
||||
rounds, segs, ab = load_rounds(), load_segments(), read_ab()
|
||||
T = ['# 第四章表格(data_1)', '',
|
||||
'所有數字由 `scripts_1/` 的腳本產生,來源檔寫在每張表前。窗層級指標都是 out-of-fold,'
|
||||
'同一回合的窗只會落在同一折;「誤判率 1%」的門檻若未特別說明,是在被評估的資料上回溯選出的 ROC 操作點。', '']
|
||||
n = 0
|
||||
|
||||
def add(title, src, df, note=None):
|
||||
nonlocal n
|
||||
n += 1
|
||||
T.extend([f'## 表 {n} {title}', '', f'來源:{src}', ''])
|
||||
T.append(md_table(df))
|
||||
if note:
|
||||
T.extend(['', note])
|
||||
T.append('')
|
||||
|
||||
# 1 資料集
|
||||
seg_n = segs.groupby(['player', 'strength']).size().rename('片段數')
|
||||
d = rounds.groupby(['player', 'strength']).agg(回合數=('round', 'size'), 總秒數=('play_seconds', 'sum'),
|
||||
幀數=('frames', 'sum'), 滑鼠回報數=('mouse_events', 'sum'),
|
||||
瞄準秒數=('aim_seconds', 'sum')).join(seg_n).reset_index()
|
||||
d = d.rename(columns={'player': '玩家', 'strength': '強度'})
|
||||
d['總秒數'] = d['總秒數'].round(1)
|
||||
d['瞄準秒數'] = d['瞄準秒數'].round(1)
|
||||
add('資料集概況', '`data_1/common/rounds.csv`、`segments.csv`', d,
|
||||
'強度 0 為無作弊。瞄準 = 敵人可見且在準心 15° 內;片段在相鄰幀間隔 > 50 ms 處切開。')
|
||||
|
||||
# 1b 玩家設定
|
||||
cfg = rounds.groupby('player').agg(靈敏度=('sensitivity', 'first'), 武器=('weapon', 'first'),
|
||||
地圖=('map', 'first'), 刷新率=('refreshRate', 'first'),
|
||||
滑鼠回報週期_ms=('poll_period_ms', 'first')).reset_index()
|
||||
fps = rounds.assign(fps=rounds.frames / rounds.play_seconds).groupby(['player', 'cheat']).fps.mean().unstack()
|
||||
cfg['平均FPS_無作弊'] = cfg.player.map(fps[0]).round(1)
|
||||
cfg['平均FPS_作弊'] = cfg.player.map(fps[1]).round(1)
|
||||
add('兩位玩家的設定', '`rounds.csv`', cfg.rename(columns={'player': '玩家'}))
|
||||
|
||||
# 2 三組列數
|
||||
recs = []
|
||||
for g in GROUPS:
|
||||
r = group_rows(g)
|
||||
r = r[r.aim == 1]
|
||||
for (c, s), k in r.groupby(['cheat', 'src']).size().items():
|
||||
recs.append(dict(組別=GL[g], 類別='作弊' if c else '無作弊',
|
||||
列來源={0: '滑鼠回報' if g != '1' else '每幀一列', 1: '插入列', 2: '合成列'}[int(s)],
|
||||
列數=int(k)))
|
||||
d = pd.DataFrame(recs)
|
||||
d['佔該類別比例'] = d.列數 / d.groupby(['組別', '類別']).列數.transform('sum')
|
||||
add('三組資料在瞄準期間的列數', '三組 `rows.csv`(aim = 1)', d)
|
||||
|
||||
# 3 窗數與覆蓋率
|
||||
w = ab[(ab.model == 'gbdt') & (ab.segset == 'all') & (ab['eval'] == 'cv_all') & (ab.group == '1') & (ab.dt == 1)]
|
||||
w = w.sort_values('W_ms')[['W_ms', 'n_win_pos', 'n_win_neg', 'n_round_pos', 'n_round_neg']]
|
||||
tot = segs.duration_ms.sum()
|
||||
w['可用瞄準時間比例'] = [segs.duration_ms[segs.duration_ms >= W].sum() / tot for W in w.W_ms]
|
||||
add('各窗長的窗數', '`ablation.csv`、`segments.csv`',
|
||||
w.rename(columns={'W_ms': '窗長_ms', 'n_win_pos': '作弊窗', 'n_win_neg': '無作弊窗',
|
||||
'n_round_pos': '有窗的作弊回合', 'n_round_neg': '有窗的無作弊回合'}),
|
||||
'窗的步進為窗長的一半,同一片段內相鄰窗重疊 50%。')
|
||||
|
||||
# 4 主表
|
||||
for m in ('gbdt', 'cnn'):
|
||||
d = ab[(ab.model == m) & (ab['eval'] == 'cv_all') & (ab.segset == 'all')]
|
||||
if not len(d):
|
||||
continue
|
||||
piv = d.pivot_table(index='W_ms', columns=['group', 'dt'], values='win_auc')
|
||||
piv = piv[[c for g in GROUPS for c in [(g, 1), (g, 0)] if c in piv.columns]]
|
||||
piv.columns = [f'{GS[g]} {"Δt" if t else "無Δt"}' for g, t in piv.columns]
|
||||
add(f'{m.upper()} 窗層級 AUC 對窗長', '`ablation.csv`(eval = cv_all)', piv.reset_index())
|
||||
|
||||
# 5 焦點窗長完整指標
|
||||
d = ab[(ab.model == 'gbdt') & (ab['eval'] == 'cv_all') & (ab.segset == 'all') & ab.W_ms.isin([50, 300, 1000])]
|
||||
d = d.assign(gi=d.group.map({g: i for i, g in enumerate(GROUPS)})).sort_values(['W_ms', 'gi', 'dt'],
|
||||
ascending=[True, True, False])
|
||||
out = pd.DataFrame({'窗長': d.W_ms, '組別': d.group.map(GS), 'Δt': d.dt.map({1: '有', 0: '無'}),
|
||||
'窗AUC': [f'{a:.3f} ({l:.3f}–{h:.3f})' for a, l, h in zip(d.win_auc, d.win_auc_lo, d.win_auc_hi)],
|
||||
'召回@0.1%': d['[email protected]'], '召回@1%': d['[email protected]'], '召回@5%': d['[email protected]'],
|
||||
'回合AUC': d.round_auc, '回合召回@1%': d['round_recall@1%'],
|
||||
'回合FPR(95%CI)': [f'{f:.3f} ({l:.3f}–{h:.3f})' for f, l, h in
|
||||
zip(d.round_fpr, d.round_fpr_lo, d.round_fpr_hi)]})
|
||||
add('焦點窗長的完整指標(GBDT)', '`ablation.csv`、`fpr_ci.csv`', out,
|
||||
'窗 AUC 括號為以回合為單位 bootstrap 的 95% CI;回合 FPR 括號為 Clopper-Pearson 95% CI。'
|
||||
'無作弊回合共 200 個,即使 0 誤判,95% 上界仍約 1.8%。')
|
||||
|
||||
# 6 強度
|
||||
ps = pd.read_csv(RESULTS / 'per_strength.csv')
|
||||
ps['group'] = ps.group.astype(str)
|
||||
for W in (50, 300):
|
||||
s = ps[(ps.model == 'gbdt') & (ps.segset == 'all') & (ps['eval'] == 'cv_all') & (ps.W_ms == W)]
|
||||
piv = s.pivot_table(index=['group', 'dt'], columns='strength', values='[email protected]')
|
||||
piv = piv.reindex([(g, t) for g in GROUPS for t in (1, 0)])
|
||||
piv.index = [f'{GS[g]} {"Δt" if t else "無Δt"}' for g, t in piv.index]
|
||||
piv.columns = [f'{c}%' for c in piv.columns]
|
||||
add(f'各強度的窗召回率(W = {W} ms,誤判率 1%)', '`per_strength.csv`', piv.reset_index().rename(
|
||||
columns={'index': '組別'}), '門檻由全部無作弊窗決定,所以各強度共用同一門檻。')
|
||||
|
||||
# 7 跨玩家
|
||||
x = ab[(ab.model == 'gbdt') & (ab.segset == 'all') & ab['eval'].str.startswith('xfer') & ab.W_ms.isin([50, 300, 1000])]
|
||||
x = x.assign(gi=x.group.map({g: i for i, g in enumerate(GROUPS)})).sort_values(['eval', 'W_ms', 'gi', 'dt'],
|
||||
ascending=[True, True, True, False])
|
||||
add('跨玩家(一位訓練、另一位測試)', '`ablation.csv`',
|
||||
pd.DataFrame({'方向': x['eval'].map({'xfer_p1to2': '玩家1→玩家2', 'xfer_p2to1': '玩家2→玩家1'}),
|
||||
'窗長': x.W_ms, '組別': x.group.map(GS), 'Δt': x.dt.map({1: '有', 0: '無'}),
|
||||
'窗AUC': x.win_auc, '召回@1%': x['[email protected]'], '回合AUC': x.round_auc,
|
||||
'回合召回@1%': x['round_recall@1%']}),
|
||||
'這裡的誤判率 1% 門檻是用測試玩家自己的無作弊資料回溯定的;門檻也從訓練玩家帶過去的結果見固定門檻表。')
|
||||
|
||||
# 8 跨組
|
||||
p = RESULTS / 'cross_group.csv'
|
||||
if p.exists():
|
||||
cg = pd.read_csv(p, dtype={'train': str, 'test': str})
|
||||
cg = cg[cg['eval'] == 'cv_all']
|
||||
for W in sorted(cg.W_ms.unique()):
|
||||
rows_ = []
|
||||
for dt in (1, 0):
|
||||
for t, lab in (('2', '第二組(A0)'), ('3', '第三組'), ('2+3', '第二 + 第三組(A1)')):
|
||||
r = {'Δt': '有' if dt else '無', '訓練': lab}
|
||||
for g in ('2', '3', '3f'):
|
||||
c = cg[(cg.W_ms == W) & (cg.dt == dt) & (cg.train == t) & (cg.test == g)]
|
||||
r[f'測{GS[g]} AUC'] = c.win_auc.mean()
|
||||
r[f'測{GS[g]} 召回@1%'] = c['[email protected]'].mean()
|
||||
rows_.append(r)
|
||||
add(f'跨組測試:偵測器 × 外掛策略(W = {W} ms)', '`cross_group.csv`', pd.DataFrame(rows_),
|
||||
'第二組 = 外掛每幀插入一筆修正(B0);第三組 = 修正平均分配到滑鼠回報、手不動時沿回報相位合成(B1)。'
|
||||
'同一批窗、同一批折,只換訓練與測試用的組。')
|
||||
|
||||
# 9 單一特徵
|
||||
p = RESULTS / 'single_rule.csv'
|
||||
if p.exists():
|
||||
sr = pd.read_csv(p, dtype={'group': str})
|
||||
s = sr[(sr.W_ms == 300) & (sr['eval'] == 'all')]
|
||||
rows_ = []
|
||||
for g in GROUPS:
|
||||
sg = s[(s.group == g) & (s.kind == 'single')].sort_values('auc_oriented', ascending=False)
|
||||
for rk, (_, r) in enumerate(sg.head(5).iterrows(), 1):
|
||||
rows_.append({'組別': GS[g], '名次': rk, '特徵': FEAT_ZH.get(r.feature, r.feature),
|
||||
'時間類': '是' if r.feature.startswith('t_') else '', 'AUC': r.auc_oriented,
|
||||
'方向': '越大越像作弊' if r.direction == 'higher=cheat' else '越小越像作弊'})
|
||||
for dt in (1, 0):
|
||||
lr = s[(s.group == g) & (s.kind == 'logreg') & (s.dt == dt)]
|
||||
rows_.append({'組別': GS[g], '名次': '', '特徵': f'邏輯斯迴歸({DTL[dt]})', '時間類': '',
|
||||
'AUC': lr.auc_raw.mean(), '方向': ''})
|
||||
add('單一特徵直接當分數(不訓練)與邏輯斯迴歸(W = 300 ms)', '`single_rule.csv`', pd.DataFrame(rows_),
|
||||
'單一特徵的 AUC 取兩個方向中較好的一個,所以最低是 0.5。')
|
||||
|
||||
# 10 固定門檻
|
||||
p = RESULTS / 'fixed_threshold.csv'
|
||||
if p.exists():
|
||||
ft = pd.read_csv(p, dtype={'group': str})
|
||||
for W in sorted(ft.W_ms.unique()):
|
||||
s = ft[ft.W_ms == W]
|
||||
s = s.assign(gi=s.group.map({g: i for i, g in enumerate(GROUPS)}),
|
||||
ei=s['eval'].map({'cv_all': 0, 'cv_p1': 1, 'cv_p2': 2, 'xfer_p1to2': 3, 'xfer_p2to1': 4}))
|
||||
s = s[s['eval'].isin(['cv_all', 'xfer_p1to2', 'xfer_p2to1'])].sort_values(
|
||||
['target_fpr', 'gi', 'dt', 'ei'], ascending=[True, True, False, True])
|
||||
add(f'固定門檻:先在校準回合定門檻,再到沒看過的回合量(W = {W} ms)', '`fixed_threshold.csv`',
|
||||
pd.DataFrame({'目標FPR': s.target_fpr, '組別': s.group.map(GS), 'Δt': s.dt.map({1: '有', 0: '無'}),
|
||||
'評估': s['eval'].map({'cv_all': '同玩家交叉驗證', 'xfer_p1to2': '玩家1→玩家2',
|
||||
'xfer_p2to1': '玩家2→玩家1'}),
|
||||
'實測窗FPR': s.win_fpr, '窗召回': s.win_recall,
|
||||
'實測回合FPR': [f'{f:.3f} ({l:.3f}–{h:.3f})' for f, l, h in
|
||||
zip(s.round_fpr, s.round_fpr_lo, s.round_fpr_hi)],
|
||||
'回合召回': s.round_recall}),
|
||||
'每折從訓練回合依玩家 × 類別分層抽 30% 當校準回合,模型只用其餘回合訓練;'
|
||||
'窗門檻 = 校準無作弊窗分數的 (1 − 目標) 分位點,回合門檻 = 校準無作弊回合平均 logit 的分位點。'
|
||||
'校準無作弊回合每折約 48 個,回合門檻在 1% 時等於取最大值,偏粗。'
|
||||
'跨玩家時,門檻只用訓練玩家的校準回合決定。')
|
||||
|
||||
# 11 效益
|
||||
p = RESULTS / 'benefit.csv'
|
||||
if p.exists():
|
||||
b = pd.read_csv(p)
|
||||
add('輔助的任務效益與偵測率', '`benefit.csv`(events 檔);偵測率取 `per_strength.csv`,W = 300 ms、各玩家自己的交叉驗證',
|
||||
pd.DataFrame({'玩家': b.player, '強度': b.strength, '回合數': b.n_rounds, '命中率': b.hit_rate_mean,
|
||||
'命中率提升': b.hit_rate_gain, '平均擊倒時間_s': b.ttk_mean, '擊倒時間比': b.ttk_ratio,
|
||||
'第一組召回@1%(無Δt)': b.win_tpr1_g1_nodt, '第二組召回@1%(無Δt)': b.win_tpr1_g2_nodt,
|
||||
'第三組召回@1%(無Δt)': b.win_tpr1_g3_nodt}),
|
||||
'命中率 = 命中事件 / 開槍事件,每回合算完再平均;擊倒時間比 = 該強度平均擊倒時間 / 同玩家無作弊。')
|
||||
|
||||
# 12 干擾檢查
|
||||
nu = pd.read_csv(RESULTS / 'nuisance.csv')
|
||||
nu['group'] = nu.group.astype(str)
|
||||
nu = nu[(nu['eval'] == 'cv_all') & nu.group.isin(['1', '2'])]
|
||||
add('干擾檢查:只用無作弊回合,分辨前 50 與後 50 回合(W = 300 ms)', '`nuisance.csv`',
|
||||
pd.DataFrame({'組別': nu.group.map({'1': '第一組', '2': '第二、三組(無作弊列相同)'}),
|
||||
'Δt': nu.dt.map({1: '有', 0: '無'}),
|
||||
'窗AUC(95%CI)': [f'{a:.3f} ({l:.3f}–{h:.3f})' for a, l, h in
|
||||
zip(nu.win_auc, nu.win_auc_lo, nu.win_auc_hi)],
|
||||
'回合AUC': nu.round_auc}),
|
||||
'兩位玩家都是先錄 50 回合作弊,再錄 100 回合無作弊。這個 AUC 高於 0.5,代表時間先後的漂移本身就可被學到。')
|
||||
|
||||
# 13 固定片段母體
|
||||
fx = ab[(ab['eval'] == 'cv_all') & (ab.segset == 'seg>=2000') & (ab.model == 'gbdt')]
|
||||
if len(fx):
|
||||
piv = fx.pivot_table(index='W_ms', columns=['group', 'dt'], values='win_auc')
|
||||
piv = piv[[c for g in GROUPS for c in [(g, 1), (g, 0)] if c in piv.columns]]
|
||||
piv.columns = [f'{GS[g]} {"Δt" if t else "無Δt"}' for g, t in piv.columns]
|
||||
add('固定片段母體(只用 ≥ 2000 ms 的片段)的窗層級 AUC', '`ablation.csv`(segset = seg>=2000)',
|
||||
piv.reset_index(), '所有窗長都從同一批長片段切窗,排除「短窗多用了短片段」造成的差異。')
|
||||
|
||||
(RESULTS / 'chapter4_tables.md').write_text('\n'.join(T), encoding='utf-8')
|
||||
print(' wrote', RESULTS / 'chapter4_tables.md', f'({n} tables)')
|
||||
|
||||
|
||||
FIGS = {'timeline': fig_timelines, 'gap': fig_gap_hist, 'ongrid': fig_ongrid, 'auc': fig_auc_windows,
|
||||
'tpr': fig_tpr_windows, 'models': fig_models, 'coverage': fig_window_coverage, 'strength': fig_strength,
|
||||
'roc': fig_roc, 'round': fig_round_scores, 'cross': fig_cross_group, 'rule': fig_single_rule,
|
||||
'baselines': fig_baselines, 'fixed': fig_fixed_threshold, 'benefit': fig_benefit,
|
||||
'nuisance': fig_nuisance, 'tables': tables}
|
||||
|
||||
|
||||
def main():
|
||||
utf8_stdout()
|
||||
setup()
|
||||
which = sys.argv[1:] or list(FIGS)
|
||||
for k in which:
|
||||
print(f'== {k} ==', flush=True)
|
||||
FIGS[k]()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""圖:遊戲一幀內的執行順序(依 MouseTrailCollector 程式碼的 DefaultExecutionOrder 與 Update/LateUpdate 整理)。
|
||||
|
||||
輸出 results_1/figures/fig_frame_flow.png
|
||||
"""
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch
|
||||
|
||||
from mtd_common import RESULTS
|
||||
|
||||
INK, MUTED, GRID = '#1f2328', '#6b7280', '#d9dde3'
|
||||
BAND = {'in': '#eaf2fc', 'upd': '#fff4ea', 'late': '#eafaf3', 'out': '#f3f4f6'}
|
||||
EDGE = {'in': '#2a78d6', 'upd': '#eb6834', 'late': '#1baf7a', 'out': '#9ca3af'}
|
||||
|
||||
|
||||
def box(ax, x, y, w, h, title, body, kind):
|
||||
ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle='round,pad=0.02,rounding_size=0.12',
|
||||
fc='white', ec=EDGE[kind], lw=1.6))
|
||||
ax.text(x + 0.12, y + h - 0.16, title, fontsize=10.5, fontweight='bold', color=INK, va='top')
|
||||
ax.text(x + 0.12, y + h - 0.52, body, fontsize=8.8, color=INK, va='top', linespacing=1.35)
|
||||
|
||||
|
||||
def arrow(ax, p, q, text=None, dashed=False):
|
||||
ax.add_patch(FancyArrowPatch(p, q, arrowstyle='-|>', mutation_scale=12, lw=1.3,
|
||||
color=MUTED, linestyle='--' if dashed else '-', shrinkA=0, shrinkB=0))
|
||||
if text:
|
||||
ax.text((p[0] + q[0]) / 2 + 0.08, (p[1] + q[1]) / 2, text, fontsize=8, color=MUTED, va='center')
|
||||
|
||||
|
||||
def main():
|
||||
plt.rcParams['font.family'] = ['Microsoft JhengHei', 'DejaVu Sans']
|
||||
plt.rcParams['axes.unicode_minus'] = False
|
||||
fig, ax = plt.subplots(figsize=(10.2, 11.2))
|
||||
ax.set_xlim(0, 10.2); ax.set_ylim(0, 11.2); ax.axis('off')
|
||||
|
||||
def band(y0, y1, label, kind):
|
||||
ax.add_patch(FancyBboxPatch((0.15, y0), 9.9, y1 - y0, boxstyle='round,pad=0.01,rounding_size=0.08',
|
||||
fc=BAND[kind], ec='none'))
|
||||
ax.text(0.3, y1 - 0.08, label, fontsize=9.5, color=EDGE[kind], fontweight='bold', va='top')
|
||||
|
||||
# 背景執行緒(幀外)
|
||||
band(9.85, 11.1, '幀外:Raw Input 背景執行緒(持續運作)', 'in')
|
||||
box(ax, 0.5, 9.95, 9.2, 0.85, 'RawMouseInput(WndProc,背景執行緒)',
|
||||
'每收到一筆 WM_INPUT 立即以 Stopwatch 蓋時間戳,換算到 Unity 的 realtime 時間軸,推入佇列(t, dx, dy, left)', 'in')
|
||||
|
||||
# 幀開頭
|
||||
band(8.3, 9.65, '幀開頭:Update,執行順序 −10000', 'in')
|
||||
box(ax, 0.5, 8.4, 9.2, 0.85, 'RawMouseInputRunner.Update → RawMouseInput.BeginFrame',
|
||||
'把佇列中累積的回報全部取出成 FrameEvents;算出本幀總位移 FrameDelta 與左鍵狀態', 'in')
|
||||
arrow(ax, (5.1, 9.95), (5.1, 9.25))
|
||||
|
||||
# Update
|
||||
band(4.35, 8.1, 'Update:預設執行順序(各腳本先後由引擎決定)', 'upd')
|
||||
box(ax, 0.5, 6.2, 4.45, 1.45, 'PlayerLook.Update',
|
||||
'位移 = FrameDelta + 待套用的輔助位移\n→ 更新 yaw / pitch,後座力偏移另行疊加\n→ 記下 LastMouseDelta、LastAssistDelta', 'upd')
|
||||
box(ax, 5.25, 6.2, 4.45, 1.45, 'AimAssist.Update',
|
||||
'讀 EnemyPerceptor.Output(上一幀 LateUpdate 的結果)\n→ 新取樣則重設剩餘誤差 → 算本幀修正量\n→ PlayerLook.AddAssistDelta(度 → 滑鼠單位)', 'upd')
|
||||
box(ax, 0.5, 4.5, 4.45, 1.45, 'HitscanWeapon.Update',
|
||||
'讀 Raw Input 左鍵 → 射線命中判定\n→ Fired / HitLanded 事件 → PlayerLook.AddRecoil', 'upd')
|
||||
box(ax, 5.25, 4.5, 4.45, 1.45, 'BotBrain + PlayerController(MotionCore)',
|
||||
'機器人 AI 餵輸入;玩家與機器人的移動物理\n在 FixedUpdate 由同一套 PlayerController 處理', 'upd')
|
||||
arrow(ax, (5.1, 8.4), (5.1, 8.1))
|
||||
arrow(ax, (5.25, 6.85), (4.95, 6.85), dashed=True)
|
||||
|
||||
# LateUpdate
|
||||
band(1.35, 4.15, 'LateUpdate:視角與敵人位置皆已更新', 'late')
|
||||
box(ax, 0.5, 2.85, 9.2, 1.0, 'EnemyPerceptor.LateUpdate(執行順序 0)',
|
||||
'Truth = 以相機對敵人各部位取樣,算角度誤差與遮擋比例;到刷新率取樣時刻則入佇列並決定該次延遲(含抖動)\n'
|
||||
'擷取時間 + 延遲已到的樣本 → Output(輔助下一幀才讀得到)', 'late')
|
||||
box(ax, 0.5, 1.45, 9.2, 1.3, 'RoundRecorder.LateUpdate(執行順序 100)',
|
||||
'先寫暫停 / 換彈事件 → FrameEvents 每筆寫入 mouse_N.csv(各自到達時間,frame = 本幀列號)\n'
|
||||
'→ frames_N.csv 寫一列:t, dt, 視角, 後座力, mouse_dx, assist_dx, 玩家與機器人狀態, Truth, Output, assist_engaged\n'
|
||||
'→ 機器人已倒下:寫 kill,Commit 三個 CSV 與 config_N.json', 'late')
|
||||
arrow(ax, (5.1, 4.5), (5.1, 4.15))
|
||||
arrow(ax, (5.1, 2.85), (5.1, 2.75))
|
||||
|
||||
# 渲染
|
||||
band(0.15, 1.2, '幀尾:渲染', 'out')
|
||||
box(ax, 0.5, 0.25, 9.2, 0.7, '畫面輸出',
|
||||
'以本幀的相機旋轉渲染;感知器以螢幕刷新率取樣,對應外掛擷取畫面的頻率', 'out')
|
||||
arrow(ax, (5.1, 1.45), (5.1, 1.2))
|
||||
|
||||
out = RESULTS / 'figures' / 'fig_frame_flow.png'
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
fig.savefig(out, dpi=200, bbox_inches='tight', facecolor='white')
|
||||
print('wrote', out)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,131 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""data_1 共用:路徑、常數、讀取回合、外掛修正整數化、瞄準片段。"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent # MouseTrailDataset/
|
||||
DATA = ROOT / 'data_1'
|
||||
RESULTS = ROOT / 'results_1'
|
||||
PLAYERS = {1: 'raw_1', 2: 'raw_2'}
|
||||
COMMON = DATA / 'common'
|
||||
|
||||
# 組別 -> (資料夾, 檔名)。'3f' 是第三組的對照版:無回報幀改在幀時間插入
|
||||
GROUPS = {
|
||||
'1': ('第一組', 'rows.csv'),
|
||||
'2': ('第二組', 'rows.csv'),
|
||||
'3': ('第三組', 'rows.csv'),
|
||||
'3f': ('第三組', 'rows_frameinsert.csv'),
|
||||
}
|
||||
|
||||
DEG_PER_COUNT = 0.022 # 視角角度 = counts × 0.022 × 靈敏度
|
||||
AIM_FOV_DEG = 15.0 # 瞄準判定:敵人在準心 15° 內
|
||||
SEG_BREAK_S = 0.05 # 相鄰幀時間間隔超過此值(暫停、卡頓)就切斷片段
|
||||
SYNTH_SPAN_S = 0.040 # 第三組合成回報只放在幀時間前 40 ms 內(避免卡頓幀補一大串)
|
||||
|
||||
# 模型只能看到反作弊拿得到的欄位
|
||||
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):
|
||||
d, f = GROUPS[g]
|
||||
return DATA / d / f
|
||||
|
||||
|
||||
def iter_rounds(player):
|
||||
"""依回合編號排序,回傳實際存在的回合(編號有缺號)。"""
|
||||
folder = DATA / PLAYERS[player]
|
||||
idx = sorted(int(p.stem.split('_')[1]) for p in folder.glob('config_*.json'))
|
||||
return idx
|
||||
|
||||
|
||||
def load_round(player, idx):
|
||||
folder = DATA / PLAYERS[player]
|
||||
with open(folder / f'config_{idx}.json', encoding='utf-8') as fh:
|
||||
cfg = json.load(fh)
|
||||
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_{f-1};第 0 幀用 t_0 - dt_0。"""
|
||||
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)。
|
||||
回傳 aim(bool 陣列), seg(int 陣列, 非瞄準 -1), segs(list of (f_start, f_end))。"""
|
||||
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}'):
|
||||
"""不依賴 tabulate 的 markdown 表格。"""
|
||||
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)
|
||||
@@ -0,0 +1,249 @@
|
||||
# -*- 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, 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 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 >= 0.0005)).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
|
||||
@@ -0,0 +1,523 @@
|
||||
# -*- 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()
|
||||
Reference in new issue
Block a user