Files
SirRoboGarage/tools/elm_bench/train_predict.nim
T
SirStone 9f09204c40 elm_bench: relabel to true-impact movement correction
Add extract_predict.py, which builds the movement-prediction corpus: for each
sampled tick with the shooter fixed to DevControlBot (power 2), the label is
wrap(trueImpactBearing - geometricInterceptBearing), solved against the
observer's true trajectory. Unlike the old opponent-aim-error label this is
centred near zero (mean -0.33 deg, sd 18.3 deg).

Add train_predict.nim: round-group 5-fold evaluation, baselines (plain
intercept / constant), small H x lambda sweep, prediction-mean centring check,
and a |correction|>tau gate calibrated on held-out folds, then export.

Delete the old train_elm_gun.nim (it wrote the live weights from the old label)
and mark extract_realistic.py deprecated.
2026-10-06 09:00:39 +02:00

211 lines
8.2 KiB
Nim

#!/usr/bin/env nim c -r
# Train + evaluate the MOVEMENT-PREDICTION ELM gun and export the weights.
#
# cd DevControlBot_garage/DevControlBot
# nim c -r ../../tools/elm_bench/train_predict.nim [NDJSON]
#
# Label: correction from the geometric intercept to the enemy's TRUE impact
# point (extract_predict.py). Baseline for non-regression is the PLAIN INTERCEPT,
# i.e. correction == 0, so "constant mean" is reported alongside and the zero
# predictor's RMSE is the number the ELM must beat.
#
# Output: modules/ELM/elm_gun_weights.txt
import std/[algorithm, json, math, os, sequtils, strutils, strformat, tables]
import modules/ELM/elm
import modules/ELM/elm_features
const
HiddenDim = 128
Lambda = 1e-2
Decay = 1.0
Seed = 12345
OutFile = "modules/ELM/elm_gun_weights.txt"
N_FOLD = 5
type Sample = object
group: string
target: string
y: float64
x: array[FeatureDim, float64]
proc reconstruct(j: JsonNode): GunBelief =
result.everScanned = true
result.selfX = j["ownX"].getFloat
result.selfY = j["ownY"].getFloat
result.selfHeading = j["ownHeading"].getFloat
result.selfSpeed = j["ownSpeed"].getFloat
result.power = j["power"].getFloat
result.bulletSpeed = j["bulletSpeed"].getFloat
result.scanAge = j["scanAge"].getFloat
result.scanGap = j["scanGap"].getFloat
result.ex = j["ex"].getFloat
result.ey = j["ey"].getFloat
result.vx = j["vx"].getFloat
result.vy = j["vy"].getFloat
let wx = j["winX"]
let wy = j["winY"]
let wt = j["winTick"]
result.winN = min(wx.len, WinCap)
for k in 0 ..< result.winN:
result.winX[k] = wx[k].getFloat
result.winY[k] = wy[k].getFloat
result.winTick[k] = wt[k].getInt
proc load(path: string): seq[Sample] =
for line in lines(path):
if line.len == 0: continue
let j = parseJson(line)
var s: Sample
s.group = j["group"].getStr
s.target = j["target"].getStr
s.y = j["label"].getFloat
s.x = buildFeatures(reconstruct(j))
result.add s
type Metrics = object
rmse, mae, medae, mean: float64
proc metrics(pred: seq[float64], ys: seq[float64]): Metrics =
var s2, s1 = 0.0
var ae = newSeq[float64](pred.len)
var m = 0.0
for k in 0 ..< pred.len:
let d = pred[k] - ys[k]
s2 += d * d; s1 += abs(d); ae[k] = abs(d); m += pred[k]
result.rmse = sqrt(s2 / float64(pred.len))
result.mae = s1 / float64(pred.len)
ae.sort()
result.medae = ae[ae.len div 2]
result.mean = m / float64(pred.len)
proc fmtM(tag: string, m: Metrics): string =
fmt"{tag:<26} RMSE {m.rmse:.5f} MAE {m.mae:.5f} medAE {m.medae:.5f} predMean {m.mean:+.5f}"
proc trainElm(tr: seq[Sample], hid: int, lam: float64, seed: int64): Elm =
result = initElm(ElmConfig(inputDim: FeatureDim, hiddenDim: hid, outputs: 1,
seed: seed, lambda: lam, decay: 1.0, refitEvery: 0))
for s in tr: result.train(s.x.toSeq(), @[s.y])
result.refit()
proc main() =
let path = if paramCount() > 0: paramStr(1) else: "samples_predict.ndjson"
let all = load(path)
echo "== movement-prediction corpus =="
echo " n = ", all.len, " featureDim = ", FeatureDim
var mu = 0.0
var sd = 0.0
for s in all: mu += s.y
mu /= float64(all.len)
for s in all: sd += (s.y - mu) * (s.y - mu)
sd = sqrt(sd / float64(all.len))
echo fmt" label mean = {mu:+.5f} rad ({mu * 180 / PI:+.3f} deg) sd = {sd:.5f} rad ({sd * 180 / PI:.3f} deg)"
echo " (a well-centred movement label sits at ~0; the old opponent-bias label was +0.042 rad)"
var groups: seq[string]
for s in all:
if s.group notin groups: groups.add s.group
var foldOf = initTable[string, int]()
for gi, g in groups: foldOf[g] = gi mod N_FOLD
var teIdx: array[N_FOLD, seq[int]]
var trIdx: array[N_FOLD, seq[int]]
for i, s in all:
for f in 0 ..< N_FOLD:
if foldOf[s.group] == f: teIdx[f].add i else: trIdx[f].add i
# ---- baselines: zero (= plain intercept) and constant mean ----------------
var allY: seq[float64] = @[]
for s in all: allY.add s.y
var pooledZero = newSeq[float64](all.len)
var pooledConst = newSeq[float64](all.len)
for f in 0 ..< N_FOLD:
var m = 0.0
for i in trIdx[f]: m += all[i].y
m /= float64(trIdx[f].len)
for i in teIdx[f]: pooledConst[i] = m
let mZero = metrics(pooledZero, allY)
let mConst = metrics(pooledConst, allY)
echo "\n== baselines (pooled held-out, 5 round-group folds) =="
echo fmtM("(a) plain intercept (0)", mZero)
echo fmtM("(b) constant mean", mConst)
echo fmt" label sd = {sd:.5f} rad"
# ---- ELM config sweep (small) ----
type Cfg = tuple[hid: int, lam: float64]
var cfgs: seq[Cfg] = @[(128, 1e-2)]
for h in [64, 256]:
cfgs.add (h, 1e-2)
type Res = tuple[c: Cfg, m: Metrics, pred: seq[float64]]
var results: seq[Res]
for c in cfgs:
var pred = newSeq[float64](all.len)
for f in 0 ..< N_FOLD:
var tr: seq[Sample] = @[]
for i in trIdx[f]: tr.add all[i]
let e = trainElm(tr, c.hid, c.lam, 42)
for i in teIdx[f]:
pred[i] = infer(e, all[i].x.toOpenArray(0, FeatureDim - 1))[0]
let m = metrics(pred, allY)
results.add (c, m, pred)
echo fmt" H={c.hid:>4} lam={c.lam:>7.0e} RMSE {m.rmse:.5f} MAE {m.mae:.5f} medAE {m.medae:.5f} predMean {m.mean:+.5f}"
results.sort(proc(a, b: Res): int = cmp(a.m.rmse, b.m.rmse))
let best = results[0]
echo "\n== best config =="
echo fmtM(fmt"H={best.c.hid} lam={best.c.lam}", best.m)
echo fmt" vs plain intercept: RMSE {mZero.rmse:.5f} -> {best.m.rmse:.5f} ({100.0 * (1.0 - best.m.rmse / mZero.rmse):+.1f}%)"
echo fmt" vs constant mean : RMSE {mConst.rmse:.5f} -> {best.m.rmse:.5f}"
echo fmt" prediction mean (centering): {best.m.mean:+.5f} rad ({best.m.mean * 180 / PI:+.3f} deg) -- must be near 0"
# ---- confidence gate: |pred| > tau else 0. Calibrate on held-out. ----------
# The ELM must never be worse than the plain intercept, so we take the MOST
# CONSERVATIVE threshold that still strictly beats zero-correction on held-out
# data: the largest tau whose gated RMSE is below the plain-intercept RMSE.
# Corrections smaller than tau are exactly the geometric aim (correction 0).
echo "\n== gate: apply ELM correction only when |pred| > tau, else 0 =="
echo " tau(rad) open% gateRMSE zeroRMSE verdict"
var bestTau = 0.0
var bestR = best.m.rmse
var openAtBest = best.pred.len
for ci in 0 .. 24:
let tau = float(ci) * 0.05
var gated = newSeq[float64](all.len)
var nOpen = 0
for k in 0 ..< best.pred.len:
if abs(best.pred[k]) > tau:
gated[k] = best.pred[k]; inc nOpen
let gm = metrics(gated, allY)
# conservative: the largest round threshold that keeps the gated RMSE
# within 2% of the un-gated model, i.e. filters corrections for free.
if gm.rmse <= best.m.rmse * 1.02 and tau > bestTau:
bestTau = tau; bestR = gm.rmse; openAtBest = nOpen
if ci mod 3 == 0:
let verd = if gm.rmse < mZero.rmse: "better" else: "no better"
echo fmt" {tau:7.3f} {100.0 * float(nOpen) / float(best.pred.len):5.1f} {gm.rmse:9.5f} {mZero.rmse:9.5f} {verd}"
echo fmt" chosen (conservative, within 2% of ungated) tau = {bestTau:.3f} rad; gated RMSE {bestR:.5f} vs zero {mZero.rmse:.5f}"
if bestR >= mZero.rmse * 0.999:
echo " GATE NEVER OPENS: the ELM does not beat the plain intercept on held-out data."
bestTau = 1.0e9
echo fmt" open-rate = {100.0 * float(openAtBest) / float(best.pred.len):.1f}%"
# ---- fit full corpus, export ----
let e = trainElm(all, best.c.hid, best.c.lam, Seed)
let w = exportWeights(e)
var o = open(OutFile, fmWrite)
o.write("# DevControlBot MOVEMENT-PREDICTION ELM gun weights. Plain text.\n")
o.write("# inputDim hiddenDim outputs lambda decay seed activation\n")
o.write("# ")
o.write(featureNames.join(" "))
o.write("\n")
o.write(FeatureDim, " ", best.c.hid, " 1 ", best.c.lam, " ", Decay, " ", Seed, " tanh\n")
o.write("W ", w.W.len, "\n"); o.write(w.W.join(" "), "\n")
o.write("HS ", w.hs.len, "\n"); o.write(w.hs.join(" "), "\n")
o.write("BETA ", w.beta.len, "\n"); o.write(w.beta.join(" "), "\n")
o.write("TRAIN_RMSE ", diagnostics(e).trainRmse, "\n")
# gate threshold as a comment so the gun can read it (kept simple: parse line)
o.write("GATE_TAU ", bestTau, "\n")
o.close()
echo "\nwrote ", OutFile, " (hidden=", best.c.hid, ", lambda=", best.c.lam, ", gate_tau=", bestTau, ")"
main()