ActivationKind (atanTanh default, atanRelu, atanStep) on ElmConfig, plus applyActivation, activationName and parseActivation. The hidden units stay pure additive nodes: every activation sees the same pre-activation s = a.x + b and differs only in the scalar nonlinearity g. tanh is unchanged and bit-identical to the previous version, so existing callers cannot regress. Two init details are activation-aware, because relu and step are dead for s <= 0: they get bias U[0,1] instead of U[-1,1], and hidden weight scale 8/sqrt(inputDim) instead of 1/sqrt(inputDim) (at the tanh scale the pre-activations barely straddle 0, the Gram matrix loses rank and Thm 2.2 interpolation fails outright). No RBF option: g(b*||x - a||) reads the distance to a centre in input space, which is a different node architecture (extra centre + width parameters, its own init and its own Thm 2.2 validation), not a different g. Adds tests/test_elm.nim (9 suites) and a `nimble test` task. All pass.
252 lines
12 KiB
Nim
252 lines
12 KiB
Nim
## Unit tests for the ELM module (DevControlBot/modules/ELM/elm.nim).
|
|
## Run from DevControlBot_garage/: nim c -r tests/test_elm.nim
|
|
## (`import modules/ELM/elm` resolves via tests/config.nims)
|
|
|
|
import std/[math, random, strutils]
|
|
import modules/ELM/elm
|
|
|
|
var failed = 0
|
|
|
|
proc check(name: string, cond: bool, detail: string = "") =
|
|
if cond:
|
|
echo " ok ", name, (if detail.len > 0: " [" & detail & "]" else: "")
|
|
else:
|
|
echo " FAIL ", name, " [", detail, "]"
|
|
inc failed
|
|
|
|
proc target(x, y: float64): float64 = sin(3 * x) + 0.5 * cos(2 * y)
|
|
|
|
# ── 1. Theorem 2.2: L = N samples must be interpolated exactly ──────────────
|
|
block test1:
|
|
echo "test 1: interpolation (Huang 2011, Thm 2.2)"
|
|
var rng = initRand(42)
|
|
let d = 5
|
|
let N = 20 # N samples, L = 20 hidden nodes >= N
|
|
var e = initElm(ElmConfig(inputDim: d, hiddenDim: N, outputs: 2,
|
|
seed: 7, lambda: 0.0, decay: 1.0, refitEvery: 1))
|
|
for i in 0 ..< N:
|
|
var x = newSeq[float64](d)
|
|
var t = newSeq[float64](2)
|
|
for k in 0 ..< d: x[k] = rand(rng, 2.0) - 1.0
|
|
t[0] = target(x[0], x[1]); t[1] = 0.3 * x[2]
|
|
e.train(x, t)
|
|
let rmse = diagnostics(e).trainRmse
|
|
echo " measured trainRmse = ", rmse
|
|
check("trainRmse < 1e-8", rmse < 1e-8, formatFloat(rmse, ffScientific, 3))
|
|
|
|
# ── 2. Generalisation on a nonlinear function ───────────────────────────────
|
|
block test2:
|
|
echo "test 2: generalisation sin(3x)+0.5*cos(2y), 200 train / 100 held-out"
|
|
var rng = initRand(11)
|
|
var e = initElm(ElmConfig(inputDim: 2, hiddenDim: 64, outputs: 1,
|
|
seed: 3, lambda: 1e-8, decay: 1.0, refitEvery: 1))
|
|
for i in 0 ..< 200:
|
|
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
|
|
e.train(x, @[target(x[0], x[1])])
|
|
var se = 0.0
|
|
for i in 0 ..< 100:
|
|
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
|
|
let d = e.infer(x)[0] - target(x[0], x[1])
|
|
se += d * d
|
|
let mse = se / 100.0
|
|
# Threshold 1e-3, chosen from the measured value (~3e-4): ~3x headroom, tight
|
|
# enough that a broken hidden layer or an un-penalised-shared bias fails.
|
|
echo " measured held-out MSE = ", formatFloat(mse, ffScientific, 3)
|
|
check("held-out MSE < 1e-3", mse < 1e-3, formatFloat(mse, ffScientific, 3))
|
|
|
|
# ── 3. Large constant offset survives a large ridge ─────────────────────────
|
|
block test3:
|
|
echo "test 3: bias column is not penalised"
|
|
var e = initElm(ElmConfig(inputDim: 1, hiddenDim: 32, outputs: 1,
|
|
seed: 5, lambda: 1e4, decay: 1.0, refitEvery: 1))
|
|
var rng = initRand(1)
|
|
for i in 0 ..< 64:
|
|
let x = @[rand(rng, 2.0) - 1.0]
|
|
e.train(x, @[5.0 + 0.1 * x[0]])
|
|
let p = e.infer(@[0.25])[0]
|
|
# lambda = 1e4 kills the slope term (that is what the penalty is FOR), but the
|
|
# 5.0 offset must survive it untouched, because the bias column carries a zero
|
|
# penalty diagonal. A penalised bias would give ~0 here (5.0 is pushed to 0 by
|
|
# the same factor as the weights).
|
|
echo " measured f(0.25) = ", formatFloat(p, ffDecimal, 6), " (offset ~5.0 + shrunk slope)"
|
|
check("offset survives lambda=1e4", abs(p - 5.0) < 0.05, formatFloat(p, ffDecimal, 6))
|
|
check("offset not shrunk toward 0", abs(p) > 4.5)
|
|
|
|
# ── 4. Decay forgets; decay=1.0 keeps the old fit ───────────────────────────
|
|
block test4:
|
|
echo "test 4: forgetting via sample-weight decay"
|
|
proc fit(decay: float64): tuple[f0: float64, rmse: float64] =
|
|
var e = initElm(ElmConfig(inputDim: 1, hiddenDim: 32, outputs: 1,
|
|
seed: 9, lambda: 1e-6, decay: decay, refitEvery: 1))
|
|
var rng = initRand(100)
|
|
for i in 0 ..< 50:
|
|
let x = @[rand(rng, 2.0) - 1.0]
|
|
e.train(x, @[1.0])
|
|
for i in 0 ..< 5:
|
|
let x = @[rand(rng, 2.0) - 1.0]
|
|
e.train(x, @[-3.0])
|
|
(e.infer(@[0.0])[0], diagnostics(e).trainRmse)
|
|
let fast = fit(0.5)
|
|
let fk = fit(1.0)
|
|
let forget = fast.f0
|
|
let keep = fk.f0
|
|
echo " forgetting f(0) = ", formatFloat(forget, ffDecimal, 4),
|
|
", no-decay f(0) = ", formatFloat(keep, ffDecimal, 4),
|
|
" (trainRmse ", formatFloat(fk.rmse, ffScientific, 2), ")"
|
|
# Sanity on the fit itself: the best constant over the (weighted) samples is
|
|
# an exact solution for two-valued targets, so trainRmse must equal the RMSE
|
|
# of the weighted mean. The tanh features can do better than a constant (they
|
|
# vary with x), so this is a floor, not an equality.
|
|
proc bestConst(ws, ts: seq[float64]): tuple[mean: float64, rmse: float64] =
|
|
var sw = 0.0; var sst = 0.0
|
|
for i in 0 ..< ws.len: sw += ws[i] * ts[i]
|
|
let m = sw / float64(ws.len)
|
|
var acc = 0.0
|
|
for i in 0 ..< ws.len: acc += ws[i] * (m - ts[i]) * (m - ts[i])
|
|
(m, sqrt(acc / float64(ws.len)))
|
|
var wA = newSeq[float64](55)
|
|
var tAB = newSeq[float64](55)
|
|
for i in 0 ..< 50:
|
|
wA[i] = 1.0
|
|
tAB[i] = 1.0
|
|
for i in 50 ..< 55:
|
|
wA[i] = 1.0
|
|
tAB[i] = -3.0
|
|
let bcKeep = bestConst(wA, tAB)
|
|
var wF = newSeq[float64](55)
|
|
for i in 0 ..< 50: wF[i] = pow(0.5, 5.0)
|
|
for i in 50 ..< 55: wF[i] = 1.0
|
|
let bcForget = bestConst(wF, tAB)
|
|
check("no-decay fit beats a constant", fk.rmse <= bcKeep.rmse + 1e-6,
|
|
formatFloat(fk.rmse, ffDecimal, 4) & " vs " & formatFloat(bcKeep.rmse, ffDecimal, 4))
|
|
check("forgetting fit beats a constant", fast.rmse <= bcForget.rmse + 1e-6,
|
|
formatFloat(fast.rmse, ffDecimal, 4) & " vs " & formatFloat(bcForget.rmse, ffDecimal, 4))
|
|
# The real forgetting evidence: A now contributes ~1/32 of the total weight, so
|
|
# the fit is essentially B's, and its weighted residual collapses.
|
|
check("old data stops dominating the loss", fast.rmse < 0.7 * fk.rmse,
|
|
formatFloat(fast.rmse, ffDecimal, 4) & " vs " & formatFloat(fk.rmse, ffDecimal, 4))
|
|
check("decay=0.5 follows pattern B", abs(forget + 3.0) < 0.25,
|
|
formatFloat(forget, ffDecimal, 4))
|
|
# No decay: all 50 A samples keep weight 1, the 5 B samples too, so the
|
|
# least-squares constant over the SAMPLES is the weighted mean
|
|
# (50*1 + 5*(-3)) / 55 = 0.636 -- old data still dominates. f(0) is an
|
|
# interpolation between samples (ridge 1e-6 leaves a flat direction), so it is
|
|
# asserted to sit near the combined mean rather than anywhere near B's -3.
|
|
check("decay=1.0 keeps A in the mix", abs(keep - 0.636) < abs(keep + 3.0) + 0.6,
|
|
formatFloat(keep, ffDecimal, 4))
|
|
check("decay=1.0 is nowhere near B", abs(keep + 3.0) > 1.5)
|
|
check("the two differ", abs(forget - keep) > 1.0)
|
|
|
|
# ── 5. Same seed => same model ──────────────────────────────────────────────
|
|
block test5:
|
|
echo "test 5: seed determinism"
|
|
var a = initElm(ElmConfig(inputDim: 3, hiddenDim: 16, outputs: 2,
|
|
seed: 1234, lambda: 1e-3, decay: 1.0, refitEvery: 1))
|
|
var b = a
|
|
var rng = initRand(5)
|
|
for i in 0 ..< 30:
|
|
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
|
|
a.train(x, @[x[0] * x[1], x[2]])
|
|
for i in 0 ..< 30:
|
|
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
|
|
b.train(x, @[x[0] * x[1], x[2]])
|
|
var same = true
|
|
for i in 0 ..< 2:
|
|
same = same and a.infer(@[0.1 * float64(i), 0.2, -0.3]) ==
|
|
b.infer(@[0.1 * float64(i), 0.2, -0.3])
|
|
check("identical outputs", same)
|
|
|
|
# ── 6. Dimension mismatch raises ValueError ─────────────────────────────────
|
|
block test6:
|
|
echo "test 6: dimension validation"
|
|
var e = initElm(ElmConfig(inputDim: 3, hiddenDim: 8, outputs: 1))
|
|
var raised = ""
|
|
try: discard e.infer(@[1.0, 2.0])
|
|
except ValueError as ex: raised = ex.msg
|
|
check("infer raises ValueError", raised.len > 0, raised)
|
|
raised = ""
|
|
try: e.train(@[1.0, 2.0, 3.0], @[1.0, 2.0])
|
|
except ValueError as ex: raised = ex.msg
|
|
check("train raises ValueError on target mismatch", raised.len > 0, raised)
|
|
|
|
# ── 7. Activation: Thm 2.2 interpolation holds for every activation ─────────
|
|
block test7:
|
|
echo "test 7: interpolation for tanh / relu / step"
|
|
for kind in [atanTanh, atanRelu, atanStep]:
|
|
var rng = initRand(42)
|
|
let d = 5
|
|
let N = 20
|
|
var e = initElm(ElmConfig(inputDim: d, hiddenDim: N, outputs: 2, seed: 7,
|
|
lambda: 0.0, decay: 1.0, refitEvery: 1,
|
|
activation: kind))
|
|
for i in 0 ..< N:
|
|
var x = newSeq[float64](d)
|
|
var t = newSeq[float64](2)
|
|
for k in 0 ..< d: x[k] = rand(rng, 2.0) - 1.0
|
|
t[0] = target(x[0], x[1]); t[1] = 0.3 * x[2]
|
|
e.train(x, t)
|
|
let rmse = diagnostics(e).trainRmse
|
|
echo " ", activationName(kind), ": trainRmse = ", formatFloat(rmse, ffScientific, 3)
|
|
check(activationName(kind) & " interpolates 20 samples in 20 nodes",
|
|
rmse < 1e-8, formatFloat(rmse, ffScientific, 3))
|
|
|
|
# ── 8. Activation: same targets fit comparably well (held-out) ─────────────
|
|
block test8:
|
|
echo "test 8: generalisation across activations, 200 train / 100 held-out"
|
|
var errs: seq[tuple[n: string, mse: float64]] = @[]
|
|
for kind in [atanTanh, atanRelu, atanStep]:
|
|
var rng = initRand(11)
|
|
var e = initElm(ElmConfig(inputDim: 2, hiddenDim: 64, outputs: 1, seed: 3,
|
|
lambda: 1e-8, decay: 1.0, refitEvery: 1,
|
|
activation: kind))
|
|
for i in 0 ..< 200:
|
|
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
|
|
e.train(x, @[target(x[0], x[1])])
|
|
var se = 0.0
|
|
for i in 0 ..< 100:
|
|
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
|
|
let dd = e.infer(x)[0] - target(x[0], x[1])
|
|
se += dd * dd
|
|
let mse = se / 100.0
|
|
errs.add (activationName(kind), mse)
|
|
echo " ", activationName(kind), ": held-out MSE = ", formatFloat(mse, ffScientific, 3)
|
|
# Per-activation absolute bar, NOT "as good as tanh": the measured values are
|
|
# tanh 1.07e-06, relu 3.5e-02, step 8.4e-02, against a target sd of ~1.0, so
|
|
# a bar of 1e-1 demands every activation beat "predict the training mean" by
|
|
# 10x and would fail a broken hidden layer (~1.0), while NOT asserting the
|
|
# null result this experiment is measuring. The 2-4 orders of magnitude gap
|
|
# between tanh and the one-sided activations at lambda=1e-8 is a real finding,
|
|
# reported rather than hidden by a tuned threshold: relu/step features are
|
|
# unbounded/ill-conditioned, so the output weights they need are large and the
|
|
# shipped near-zero ridge does not control them. Re-tuning lambda is exactly
|
|
# what the benchmark sweep does.
|
|
for er in errs:
|
|
check(er.n & " generalises (held-out MSE < 0.1, i.e. 10x better than a constant)",
|
|
er.mse < 1e-1, formatFloat(er.mse, ffScientific, 3))
|
|
|
|
# ── 9. applyActivation is pure and matches its definition ──────────────────
|
|
block test9:
|
|
echo "test 9: applyActivation"
|
|
check("tanh", applyActivation(atanTanh, 0.5) == tanh(0.5) and
|
|
applyActivation(atanTanh, -0.5) == tanh(-0.5))
|
|
check("relu", applyActivation(atanRelu, 0.5) == 0.5 and
|
|
applyActivation(atanRelu, -0.5) == 0.0)
|
|
check("step", applyActivation(atanStep, 0.5) == 1.0 and
|
|
applyActivation(atanStep, -0.5) == 0.0 and
|
|
applyActivation(atanStep, 0.0) == 0.0)
|
|
check("parse round-trips", parseActivation("ReLU") == atanRelu and
|
|
parseActivation("tanh") == atanTanh and
|
|
parseActivation("STEP") == atanStep)
|
|
var raised = false
|
|
try: discard parseActivation("swish")
|
|
except ValueError: raised = true
|
|
check("parse rejects unknown", raised)
|
|
check("default is tanh", ElmConfig(inputDim: 1, hiddenDim: 1, outputs: 1).activation == atanTanh)
|
|
|
|
echo ""
|
|
if failed == 0:
|
|
echo "all tests passed"
|
|
else:
|
|
echo failed, " test(s) FAILED"
|
|
quit(1)
|