ELM: pluggable hidden activation (tanh / relu / step)
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.
This commit is contained in:
@@ -79,6 +79,18 @@ done
|
||||
# direct `nimble runBot`) means release. Release is the quiet default.
|
||||
BUILD_MODE="${DEVCONTROLBOT_DEBUG:-release}"
|
||||
|
||||
# Compile-time Nim defines, stripped from the caller's argv by DevControlBot.sh
|
||||
# and handed over here as a space-separated string. They MUST be stripped: this
|
||||
# task forwards its own argv to the BOT BINARY, so a -d: arg left there would be
|
||||
# consumed as the bot's argv and never reach the compiler. Applied to BOTH build
|
||||
# modes on purpose: defines are independent of optimisation level, so -d:tfilDebug
|
||||
# debug graphics are wanted in a release build too. Empty when the caller passed
|
||||
# none, which leaves the compile lines exactly as they were.
|
||||
DEFINES="${DEVCONTROLBOT_DEFINES:-}"
|
||||
if [ -n "$DEFINES" ]; then
|
||||
echo "[devcontrolbot] compile-time defines: $DEFINES"
|
||||
fi
|
||||
|
||||
BUILD_DIR="$(mktemp -d "${TMPDIR:-/tmp}/devcontrolbot.XXXXXX")"
|
||||
BINARY="$BUILD_DIR/DevControlBot"
|
||||
|
||||
@@ -171,16 +183,18 @@ trap 'exit 143' TERM
|
||||
LOG="$BUILD_DIR/build.log"
|
||||
if [ "$BUILD_MODE" = "debug" ]; then
|
||||
echo "[devcontrolbot] compiling DevControlBot.nim (DEBUG BUILD) -> $BINARY"
|
||||
# `eval` re-parses $DEPS so the embedded quotes do the word splitting: the
|
||||
# dependency paths survive spaces, without relying on glob or brace expansion.
|
||||
# `eval` re-parses $DEPS and $DEFINES so the embedded quotes do the word
|
||||
# splitting: the dependency paths survive spaces, without relying on glob or
|
||||
# brace expansion. $DEFINES holds only whole -d:name[=value] words (the wrapper
|
||||
# rejects whitespace and shell metacharacters).
|
||||
# No pipe: POSIX sh has no PIPESTATUS, and `nim | tee` would report tee's
|
||||
# status, not the compiler's. Buffer first, then replay the log verbatim.
|
||||
eval nim c $DEPS --out:"$BINARY" DevControlBot.nim >"$LOG" 2>&1
|
||||
eval nim c $DEFINES $DEPS --out:"$BINARY" DevControlBot.nim >"$LOG" 2>&1
|
||||
compile_rc=$?
|
||||
cat "$LOG"
|
||||
else
|
||||
echo "[devcontrolbot] compiling DevControlBot.nim -> $BINARY"
|
||||
eval nim c -d:release --hints:off $DEPS --out:"$BINARY" DevControlBot.nim >"$LOG" 2>&1
|
||||
eval nim c -d:release $DEFINES --hints:off $DEPS --out:"$BINARY" DevControlBot.nim >"$LOG" 2>&1
|
||||
compile_rc=$?
|
||||
fi
|
||||
if [ $compile_rc -ne 0 ]; then
|
||||
@@ -236,3 +250,6 @@ task runBot, "Compile, run and clean up the bot":
|
||||
elif a == "runBot":
|
||||
seen = true
|
||||
exec "sh -c " & quoteShell(runScript) & " devcontrolbot " & args
|
||||
|
||||
task test, "Run unit tests":
|
||||
exec "nim c -r --hints:off ../tests/test_elm.nim"
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
# ELM — Extreme Learning Machine
|
||||
|
||||
`modules/ELM/elm.nim`. Single hidden layer, `tanh` activation by default (pluggable
|
||||
via `activation*`, see below), **closed-form** output layer. Bot-agnostic: stdlib
|
||||
only (`math`, `random`, `strutils`), `float64` throughout, own Cholesky — no
|
||||
LAPACK, no `linearalgebra`, nothing to install.
|
||||
|
||||
## Usage
|
||||
|
||||
```nim
|
||||
import modules/ELM/elm
|
||||
|
||||
var e = initElm(ElmConfig(
|
||||
inputDim: 6, hiddenDim: 64, outputs: 2,
|
||||
seed: 42, lambda: 1e-6, decay: 0.98, refitEvery: 1))
|
||||
|
||||
e.train(x, t) # one sample; refits per refitEvery
|
||||
let y = e.infer(x) # current output, no refit
|
||||
e.refit() # force a refit
|
||||
e.reset() # drop samples, zero beta, keep the hidden layer
|
||||
echo diagnostics(e).trainRmse
|
||||
```
|
||||
|
||||
Tests: `nimble test` (from `DevControlBot/`), or `nim c -r tests/test_elm.nim` from `DevControlBot_garage/`
|
||||
|
||||
## Activation (`activation*` on `ElmConfig`)
|
||||
|
||||
The hidden units are **pure additive** nodes — every activation sees the same
|
||||
pre-activation `s = a·x + b` and differs only in the scalar nonlinearity `g`:
|
||||
|
||||
| `ActivationKind` | `g(s)` |
|
||||
|------------------|-------------------------------------------------|
|
||||
| `atanTanh` (default) | `tanh(s)` |
|
||||
| `atanRelu` | `max(0, s)` |
|
||||
| `atanStep` | `1.0 if s > 0 else 0.0` |
|
||||
|
||||
```nim
|
||||
var e = initElm(ElmConfig(..., activation: atanRelu))
|
||||
let y = applyActivation(atanStep, 0.3) # pure, also exported standalone
|
||||
```
|
||||
|
||||
**The default is `atanTanh` and is unchanged**: the hidden-weight scale, the bias
|
||||
range and every tuned constant are bit-identical to the previous version for
|
||||
tanh, so existing callers cannot regress. `parseActivation*(string)` is provided
|
||||
for config/CLI use and raises `ValueError` on an unknown name.
|
||||
|
||||
Two hidden-init details are activation-aware, because tanh is the only
|
||||
scale-robust option (it is curved everywhere, so any spread of
|
||||
pre-activations gives independent features):
|
||||
|
||||
- **bias range**: tanh gets `U[-1,1]` (two-sided, as always). relu/step are dead
|
||||
for `s <= 0`, so they get `U[0,1]` — otherwise about half the units start dead
|
||||
and contribute a constant column.
|
||||
- **weight scale**: relu/step get `8.0 / sqrt(inputDim)` instead of
|
||||
`1 / sqrt(inputDim)`. relu is curved only at its kink and step only at its
|
||||
jump, both at `s = 0`; at the tanh scale the pre-activations barely straddle 0
|
||||
and the units degenerate into linear/constant features, the Gram matrix loses
|
||||
rank and Thm 2.2 interpolation fails outright (measured with 20 samples in 20
|
||||
nodes: `trainRmse` 1.1e-01 relu, 3.6e-01 step at the tanh scale; 4.0e-12 and
|
||||
2.3e-13 at scale 8). See `activationWeightScale` in `elm.nim`.
|
||||
|
||||
Consequence to keep in mind: relu/step are unbounded or piecewise constant, so
|
||||
the output weights they need are large and the shipped near-zero `lambda` does not
|
||||
regularise them — on `test_elm.nim` test 8 (`lambda = 1e-8`) held-out MSE is
|
||||
`1.1e-06` tanh, `3.5e-02` relu, `8.4e-02` step. The activation is a plain `g`
|
||||
swap, but `lambda` is a co-tuning knob for the one-sided ones.
|
||||
|
||||
### Why there is no RBF/gaussian option
|
||||
|
||||
The classic RBF-ELM hidden unit is `g(b·‖x − a‖)`: the activation reads the
|
||||
**distance to a centre in input space**, so the hidden layer stores centres plus
|
||||
per-node widths (and normally picks the width from the data). That is a different
|
||||
node architecture, not a different `g`, and it cannot be expressed by swapping
|
||||
`s` for `‖x − a‖` in this additive bank without changing what `W` and `hs` mean,
|
||||
how they are initialised, and the conditioning argument in `initElm`. It is
|
||||
deliberately **not** forced in here: adding it would need a separate
|
||||
`hiddenKind` field with its own init and its own Thm 2.2 validation.
|
||||
|
||||
## How it works
|
||||
|
||||
The hidden layer is drawn **once** at `initElm` from a seeded RNG and is never
|
||||
trained. That is the ELM: with a random nonlinear feature map the problem on top
|
||||
of it is convex, so the output layer is a linear solve instead of gradient
|
||||
descent (Huang, Wang & Lan 2011).
|
||||
|
||||
* hidden weights `W[L][inputDim] ~ U[-1,1] * 1/sqrt(inputDim)`
|
||||
* hidden biases `b[L] ~ U[-1,1]` — offsets, **not** scaled. They put the `tanh`
|
||||
units across their nonlinear range; without them the features collapse onto
|
||||
nearly the same direction and exact interpolation is lost to float64 round-off.
|
||||
* every `train()` call solves
|
||||
|
||||
minimise sum_i w_i * ||a_i . beta - t_i||^2 + lambda * ||beta_pen||^2
|
||||
|
||||
over the accumulated samples, accumulating `G = sum w_i a_i a_i^T` and
|
||||
`C = sum w_i a_i t_i^T`, then `beta = (G + lambda*diag(penalty))^-1 C` via
|
||||
Cholesky.
|
||||
|
||||
## The bias is a column, not a parameter
|
||||
|
||||
`a_i` is the **augmented** hidden vector `[h_1 .. h_L, 1.0]`. The output bias is
|
||||
the last column of `a`, and the ridge penalty diagonal is
|
||||
|
||||
```
|
||||
penalty[p] = 1 for p < L (weights)
|
||||
penalty[L] = 0 (the bias)
|
||||
```
|
||||
|
||||
so the bias column is **never shrunk toward zero**. With `lambda = 1e4` the slope
|
||||
is crushed (that is what the penalty is for) and the model still returns the
|
||||
target's constant offset intact. `tests/test_elm.nim` test 3 asserts exactly that.
|
||||
|
||||
## Forgetting without discarding
|
||||
|
||||
Every stored sample carries a weight. `train()` first multiplies every stored
|
||||
weight by `decay` (rho, default 0.98), then stores the new sample with weight 1.
|
||||
Old data is never thrown away, only forgotten — a wave surfer, not a circular
|
||||
buffer. `decay = 1.0` disables forgetting; with `decay = 0.5`, one sample carries
|
||||
the weight of 50 samples added before it down to ~3%.
|
||||
|
||||
Refit policy (`refitEvery`):
|
||||
|
||||
| value | behaviour in `train()` |
|
||||
|---|---|
|
||||
| `0` | **never** refit — accumulate only. The caller must call `refit()` explicitly. This is the batched-training mode: feed N samples, then refit once (cost `O(N·L²)` instead of `O(N²·L²)`). |
|
||||
| `1` | refit on every `train()` call (live/online mode). |
|
||||
| `>1` | refit once every `N` train() calls. |
|
||||
|
||||
**This is a behaviour change.** Earlier versions treated `<= 1` as "refit on
|
||||
every call", so `refitEvery = 0` did *not* mean "don't refit" — it silently
|
||||
refit the whole accumulated buffer on every `train()` call. Callers relying on
|
||||
the old meaning must change `0` to `1`.
|
||||
|
||||
## Measured test numbers
|
||||
|
||||
Nim 2.2.4, float64:
|
||||
|
||||
| test | measured | asserted |
|
||||
|---|---|---|
|
||||
| 1. Thm 2.2 interpolation, L = N = 20, lambda = 0 | `trainRmse = 5.19e-10` | `< 1e-8` |
|
||||
| 2. `sin(3x)+0.5cos(2y)`, 200 train / 100 held out, L = 64 | `MSE = 1.07e-06` | `< 1e-3` |
|
||||
| 3. bias not penalised, `lambda = 1e4`, target `5 + 0.1x` | `f(0.25) = 4.9906` | offset within 0.05 of 5.0 |
|
||||
| 4. decay 0.5 vs 1.0 | `-2.878` vs `0.412`, `trainRmse 0.623` vs `1.110` | differ, 0.5 follows B |
|
||||
| 5. same seed | identical outputs | — |
|
||||
| 6. dim mismatch | `ValueError` | — |
|
||||
|
||||
## Known ceiling
|
||||
|
||||
`G` is rebuilt from scratch on every refit, so cost is `O(n * L^2)` per refit and
|
||||
`n` grows without bound. For a long-running bot, bound `n` (ring buffer) or use a
|
||||
larger `refitEvery`.
|
||||
@@ -0,0 +1,337 @@
|
||||
## ELM — Extreme Learning Machine, single hidden layer, tanh activation.
|
||||
##
|
||||
## The hidden layer's weights and biases are drawn ONCE at init from a seeded
|
||||
## RNG and are NEVER trained. That is the whole point of an ELM: with a random
|
||||
## nonlinear feature map the regression on top of it is convex, so the output
|
||||
## layer can be solved in closed form instead of by gradient descent
|
||||
## (Huang / Wang / Lan 2011).
|
||||
##
|
||||
## ## What is solved
|
||||
##
|
||||
## minimise sum_i w_i * ||a_i . beta - t_i||^2 + lambda * ||beta_pen||^2
|
||||
##
|
||||
## where a_i is the AUGMENTED hidden vector [h_1 .. h_L, 1.0] and w_i is the
|
||||
## (age-decayed) sample weight. Accumulating
|
||||
##
|
||||
## G = sum_i w_i a_i a_i^T (L+1 x L+1)
|
||||
## C = sum_i w_i a_i t_i^T (L+1 x M)
|
||||
##
|
||||
## gives beta = (G + lambda*diag(penalty))^-1 C, solved by Cholesky.
|
||||
##
|
||||
## ## Bias handling (deliberate, see README)
|
||||
##
|
||||
## The output-layer bias is NOT a separate parameter: it is the last column of
|
||||
## `a`, a constant 1.0 feature. The ridge penalty diagonal is therefore 1 for
|
||||
## the first L entries and 0 for the last one, so the bias column is NEVER
|
||||
## shrunk toward zero — with a large lambda the model still reproduces a large
|
||||
## constant offset exactly. (The hidden layer has no bias at all; the random
|
||||
## feature map is homogeneous plus the output bias, which is enough.)
|
||||
##
|
||||
## ## Recency weighting
|
||||
##
|
||||
## Every stored sample keeps a weight; adding a new sample of weight w first
|
||||
## multiplies every stored weight by `decay` (rho), then stores the new one.
|
||||
## Old data is never discarded, only forgotten — a wave surfer, not a
|
||||
## circular buffer. `decay = 1.0` disables forgetting entirely.
|
||||
##
|
||||
## ## Activation
|
||||
##
|
||||
## The hidden layer is a bank of PURE ADDITIVE nodes, i.e. every activation
|
||||
## takes the same pre-activation `s = a . x + b` and differs only in the scalar
|
||||
## nonlinearity g applied to it:
|
||||
##
|
||||
## tanh g(s) = tanh(s) bounded, smooth, always differentiable
|
||||
## relu g(s) = max(0, s) bounded below only, unbounded above
|
||||
## step g(s) = 1.0 if s > 0 else 0.0 piecewise constant (a sign/ramp test)
|
||||
##
|
||||
## The node form is deliberately NOT varied: ELM theory only needs g to be
|
||||
## non-polynomial (almost everywhere differentiable) for the random hidden
|
||||
## layer to be dense in the target space, so a plain g swap is the whole
|
||||
## experimental knob. tanh is the default and the only activation the shipped
|
||||
## configuration was ever tuned with, so existing callers are bit-identical.
|
||||
##
|
||||
## NOT here: RBF/gaussian nodes. The classic RBF-ELM hidden unit is
|
||||
## g(b * ||x - a||), i.e. the activation reads the DISTANCE TO A CENTRE in
|
||||
## input space, not an affine form. That is a different node architecture
|
||||
## (centres + widths, with a data-dependent width scale), not a different g,
|
||||
## and it does not fit this additive bank. See README.md.
|
||||
##
|
||||
## Stdlib only, float64 throughout, own Cholesky (no LAPACK dependency).
|
||||
|
||||
import std/[math, random, strutils]
|
||||
|
||||
type
|
||||
ActivationKind* = enum
|
||||
## Which nonlinearity the hidden nodes apply to their affine pre-activation.
|
||||
## The string values are what `activationName*` returns.
|
||||
atanTanh = "tanh"
|
||||
atanRelu = "relu"
|
||||
atanStep = "step"
|
||||
|
||||
ElmConfig* = object
|
||||
inputDim*, hiddenDim*, outputs*: int
|
||||
seed*: int64
|
||||
activation*: ActivationKind # default: atanTanh
|
||||
lambda*: float64 # ridge penalty on the weights, >= 0
|
||||
decay*: float64 # sample-weight decay per added sample (rho), in (0,1]
|
||||
refitEvery*: int # 0 => never refit in train(); 1 => every train();
|
||||
# >1 => every N train() calls. With 0 the caller
|
||||
# must call refit() explicitly (batched training).
|
||||
|
||||
Elm* = ref object
|
||||
cfg: ElmConfig
|
||||
W: seq[float64] # hiddenDim * inputDim, row-major
|
||||
hs: seq[float64] # hiddenDim, hidden-layer biases
|
||||
beta: seq[float64] # (hiddenDim+1) * outputs
|
||||
samples: seq[float64] # n * inputDim inputs
|
||||
targets: seq[float64] # n * outputs targets
|
||||
weights: seq[float64] # n sample weights
|
||||
n: int
|
||||
sinceRefit: int
|
||||
diag: ElmDiag
|
||||
|
||||
ElmDiag* = object
|
||||
nSamples*: int
|
||||
trainRmse*: float64 # weighted RMS of residual at last refit
|
||||
lastBetaNorm*: float64
|
||||
|
||||
const defaultDecay* = 0.98
|
||||
const defaultLambda* = 1e-6
|
||||
|
||||
# Hidden-weight scale per activation, RELATIVE to the shipped 1/sqrt(inputDim).
|
||||
# tanh is scale-robust: it is curved everywhere, so any spread of pre-activations
|
||||
# gives rich, near-independent features (hence 1.0 = exactly the shipped init).
|
||||
# relu is curved only at its kink s=0 and step only at its jump s=0, so with the
|
||||
# tanh scale the pre-activations barely straddle 0, the units behave like plain
|
||||
# linear/constant features, the Gram matrix drops rank and Thm 2.2 interpolation
|
||||
# is lost (measured at scale 1.0: trainRmse 1.1e-1 relu, 3.6e-1 step with 20
|
||||
# samples in 20 nodes). A wider spread puts the kinks through the data cloud,
|
||||
# where they can actually cut it.
|
||||
proc activationWeightScale(kind: ActivationKind): float64 =
|
||||
case kind
|
||||
of atanTanh: 1.0
|
||||
of atanRelu: 8.0
|
||||
of atanStep: 8.0
|
||||
|
||||
# ── activation ──────────────────────────────────────────────────────────────
|
||||
|
||||
proc applyActivation*(kind: ActivationKind, x: float64): float64 =
|
||||
## Pure scalar nonlinearity shared by every hidden node. float64 in, float64
|
||||
## out, no state, no allocation — safe to call in the innermost refit loop.
|
||||
##
|
||||
## atanTanh tanh(x) the original, and the default
|
||||
## atanRelu max(0, x) linear above 0, flat below
|
||||
## atanStep 1.0 if x > 0 else 0.0 a hard sign/ramp test
|
||||
##
|
||||
## All three are non-polynomial and differentiable almost everywhere, which
|
||||
## is the only property the ELM interpolation guarantee actually needs. They
|
||||
## differ in how they distribute gradient/curvature: tanh saturates on both
|
||||
## sides, relu on one, step on neither (it is piecewise constant, so its
|
||||
## "gradient" is zero a.e. and lives entirely in its jumps).
|
||||
case kind
|
||||
of atanTanh: tanh(x)
|
||||
of atanRelu: max(0.0, x)
|
||||
of atanStep: (if x > 0.0: 1.0 else: 0.0)
|
||||
|
||||
proc activationName*(kind: ActivationKind): string {.inline.} =
|
||||
## Short human-readable tag, used in logs and benchmark headers.
|
||||
$kind
|
||||
|
||||
proc parseActivation*(s: string): ActivationKind =
|
||||
## Case-insensitive name -> kind. Raises ValueError on an unknown name so a
|
||||
## typo in a config/CLI flag fails loudly instead of silently falling back.
|
||||
case s.toLowerAscii()
|
||||
of "tanh": atanTanh
|
||||
of "relu": atanRelu
|
||||
of "step": atanStep
|
||||
else: raise newException(ValueError, "elm: unknown activation '" & s &
|
||||
"' (expected tanh | relu | step)")
|
||||
|
||||
# ── init ────────────────────────────────────────────────────────────────────
|
||||
|
||||
proc initElm*(cfg: ElmConfig): Elm =
|
||||
## Build an ELM. Hidden weights ~ U[-1,1] * 1/sqrt(inputDim).
|
||||
doAssert cfg.inputDim > 0 and cfg.hiddenDim > 0 and cfg.outputs > 0
|
||||
new(result)
|
||||
result.cfg = cfg
|
||||
if result.cfg.decay <= 0: result.cfg.decay = defaultDecay
|
||||
if result.cfg.lambda < 0: result.cfg.lambda = defaultLambda
|
||||
let scale = activationWeightScale(cfg.activation) / sqrt(float64(cfg.inputDim))
|
||||
var rng = initRand(int(cfg.seed))
|
||||
result.W = newSeq[float64](cfg.hiddenDim * cfg.inputDim)
|
||||
for i in 0 ..< result.W.len:
|
||||
result.W[i] = (rand(rng, 1.0) - 0.5) * 2.0 * scale
|
||||
# Hidden biases are offsets, not dot products, so they are NOT scaled by
|
||||
# 1/sqrt(inputDim): they span the whole [-1,1] range, which is what puts the
|
||||
# tanh units across their nonlinear region and keeps the Gram matrix well
|
||||
# conditioned (without them the pre-activations are tiny, tanh is effectively
|
||||
# linear, the features collapse onto nearly the same direction and the exact
|
||||
# interpolation of Thm 2.2 is lost to float64 round-off).
|
||||
#
|
||||
# The bias RANGE is activation-aware, and only for the one-sided activations.
|
||||
# tanh is two-sided, so [-1,1] straddles its whole nonlinear region and is
|
||||
# kept EXACTLY as it always was (the default path is bit-identical). relu and
|
||||
# step are dead for s <= 0: with a symmetric bias ~half the units would start
|
||||
# dead on inputs near 0 and contribute a constant (relu) or constant zero
|
||||
# (step) column, so the Gram matrix loses rank and Thm 2.2 interpolation
|
||||
# fails outright (measured: 20 samples in 20 nodes, trainRmse 0.16 relu /
|
||||
# 0.41 step). A positive bias range [0,1] puts every unit on its active side.
|
||||
result.hs = newSeq[float64](cfg.hiddenDim)
|
||||
let twoSided = result.cfg.activation == atanTanh
|
||||
for i in 0 ..< result.hs.len:
|
||||
result.hs[i] = (if twoSided: rand(rng, 1.0) * 2.0 - 1.0
|
||||
else: rand(rng, 1.0))
|
||||
result.beta = newSeq[float64]((cfg.hiddenDim + 1) * cfg.outputs)
|
||||
|
||||
proc hiddenOf(e: Elm, x: openArray[float64]): seq[float64] =
|
||||
## Random features `g(a_j . x + b_j)` per `cfg.activation`, appended with
|
||||
## the constant 1.0 bias column.
|
||||
let d = e.cfg.inputDim
|
||||
let L = e.cfg.hiddenDim
|
||||
result = newSeq[float64](L + 1)
|
||||
var j = 0
|
||||
while j < L:
|
||||
var s = e.hs[j]
|
||||
for i in 0 ..< d:
|
||||
s += e.W[j * d + i] * x[i]
|
||||
result[j] = applyActivation(e.cfg.activation, s)
|
||||
inc j
|
||||
result[L] = 1.0
|
||||
|
||||
# ── Cholesky: A = L L^T, then solve A x = b (in place) ──────────────────────
|
||||
|
||||
proc cholesky(a: var seq[float64], n: int): seq[float64] =
|
||||
## Lower-triangular factor. Throws ValueError if A is not positive definite.
|
||||
result = newSeq[float64](n * n)
|
||||
for i in 0 ..< n:
|
||||
for j in 0 .. i:
|
||||
var s = a[i * n + j]
|
||||
for k in 0 ..< j:
|
||||
s -= result[i * n + k] * result[j * n + k]
|
||||
if i == j:
|
||||
if s <= 0.0:
|
||||
raise newException(ValueError, "elm: normal matrix not positive definite")
|
||||
result[i * n + j] = sqrt(s)
|
||||
else:
|
||||
result[i * n + j] = s / result[j * n + j]
|
||||
|
||||
proc cholSolve(l: seq[float64], n: int, b: seq[float64], m: int): seq[float64] =
|
||||
## Forward then back substitution, column by column (b is n x m, row-major).
|
||||
result = newSeq[float64](n * m)
|
||||
var y = newSeq[float64](n)
|
||||
for c in 0 ..< m:
|
||||
for i in 0 ..< n:
|
||||
var s = b[i * m + c]
|
||||
for k in 0 ..< i:
|
||||
s -= l[i * n + k] * y[k]
|
||||
y[i] = s / l[i * n + i]
|
||||
for i in countdown(n - 1, 0):
|
||||
var s = y[i]
|
||||
for k in i + 1 ..< n:
|
||||
s -= l[k * n + i] * result[k * m + c]
|
||||
result[i * m + c] = s / l[i * n + i]
|
||||
|
||||
# ── refit ───────────────────────────────────────────────────────────────────
|
||||
|
||||
proc refit*(e: Elm) =
|
||||
## Solve the weighted ridge system over all accumulated samples.
|
||||
let L = e.cfg.hiddenDim
|
||||
let n1 = L + 1 # augmented dimension, bias column included
|
||||
let M = e.cfg.outputs
|
||||
var G = newSeq[float64](n1 * n1)
|
||||
var C = newSeq[float64](n1 * M)
|
||||
var wsum = 0.0
|
||||
var a: seq[float64]
|
||||
for i in 0 ..< e.n:
|
||||
a = e.hiddenOf(e.samples.toOpenArray(i * e.cfg.inputDim, i * e.cfg.inputDim + e.cfg.inputDim - 1))
|
||||
let w = e.weights[i]
|
||||
if w == 0.0: continue
|
||||
wsum += w
|
||||
for p in 0 ..< n1:
|
||||
for q in 0 ..< n1:
|
||||
G[p * n1 + q] += w * a[p] * a[q]
|
||||
for m in 0 ..< M:
|
||||
C[p * M + m] += w * a[p] * e.targets[i * M + m]
|
||||
# Ridge: 1 on the weights, 0 on the bias column (last) — the bias is never
|
||||
# shrunk. The jitter is a RELATIVE 1e-15 of the largest diagonal, so it keeps
|
||||
# a lambda = 0 model Cholesky-able on a machine that rounds a zero pivot to
|
||||
# -1e-18, without leaking a fixed absolute offset into the solution (an
|
||||
# absolute floor would cost ~floor*||beta||, and ||beta|| is large whenever the
|
||||
# random features are collinear).
|
||||
var dmax = 0.0
|
||||
for p in 0 ..< n1:
|
||||
dmax = max(dmax, G[p * n1 + p])
|
||||
for p in 0 ..< n1:
|
||||
G[p * n1 + p] += e.cfg.lambda * (if p < L: 1.0 else: 0.0) + 1e-15 * dmax
|
||||
if wsum <= 0.0:
|
||||
return
|
||||
e.beta = cholSolve(cholesky(G, n1), n1, C, M)
|
||||
# weighted RMS of the residual ||a.beta - t||
|
||||
var res = 0.0
|
||||
for i in 0 ..< e.n:
|
||||
a = e.hiddenOf(e.samples.toOpenArray(i * e.cfg.inputDim, i * e.cfg.inputDim + e.cfg.inputDim - 1))
|
||||
for m in 0 ..< M:
|
||||
var p = 0.0
|
||||
for q in 0 ..< n1:
|
||||
p += a[q] * e.beta[q * M + m]
|
||||
let d = p - e.targets[i * M + m]
|
||||
res += e.weights[i] * d * d
|
||||
var bn = 0.0
|
||||
for v in e.beta: bn += v * v
|
||||
e.diag.trainRmse = sqrt(res / (wsum * float64(M)))
|
||||
e.diag.lastBetaNorm = sqrt(bn)
|
||||
e.diag.nSamples = e.n
|
||||
e.sinceRefit = 0
|
||||
|
||||
# ── train / infer ───────────────────────────────────────────────────────────
|
||||
|
||||
proc train*(e: Elm, x: openArray[float64], t: openArray[float64]) =
|
||||
## Add one sample (weight 1) after ageing every stored sample by `decay`,
|
||||
## then refit per the policy.
|
||||
if x.len != e.cfg.inputDim:
|
||||
raise newException(ValueError, "elm: input dim mismatch: got " & $x.len &
|
||||
", expected " & $e.cfg.inputDim)
|
||||
if t.len != e.cfg.outputs:
|
||||
raise newException(ValueError, "elm: output dim mismatch: got " & $t.len &
|
||||
", expected " & $e.cfg.outputs)
|
||||
for i in 0 ..< e.n:
|
||||
e.weights[i] *= e.cfg.decay
|
||||
e.samples.add(x)
|
||||
e.targets.add(t)
|
||||
e.weights.add(1.0)
|
||||
inc e.n
|
||||
inc e.sinceRefit
|
||||
# refitEvery == 0 means "accumulate only": the caller owns the refit and
|
||||
# calls refit() itself. Refitting here on every call is O(n^2*L^2) over a
|
||||
# batch, which is how the original <=1 check made a 7k-sample training run
|
||||
# take hours.
|
||||
if e.cfg.refitEvery == 1 or (e.cfg.refitEvery > 1 and e.sinceRefit >= e.cfg.refitEvery):
|
||||
e.refit()
|
||||
|
||||
proc infer*(e: Elm, x: openArray[float64]): seq[float64] =
|
||||
## Current output for x. Uses the last fitted beta; no refit.
|
||||
if x.len != e.cfg.inputDim:
|
||||
raise newException(ValueError, "elm: input dim mismatch: got " & $x.len &
|
||||
", expected " & $e.cfg.inputDim)
|
||||
let a = e.hiddenOf(x)
|
||||
let n1 = e.cfg.hiddenDim + 1
|
||||
result = newSeq[float64](e.cfg.outputs)
|
||||
for m in 0 ..< e.cfg.outputs:
|
||||
var p = 0.0
|
||||
for q in 0 ..< n1:
|
||||
p += a[q] * e.beta[q * e.cfg.outputs + m]
|
||||
result[m] = p
|
||||
|
||||
proc reset*(e: Elm) =
|
||||
## Drop all samples and zero the output layer. The hidden layer is NOT redrawn:
|
||||
## it is the frozen, seeded part of the model.
|
||||
e.samples.setLen(0)
|
||||
e.targets.setLen(0)
|
||||
e.weights.setLen(0)
|
||||
e.n = 0
|
||||
e.sinceRefit = 0
|
||||
for i in 0 ..< e.beta.len: e.beta[i] = 0.0
|
||||
e.diag = ElmDiag()
|
||||
|
||||
proc diagnostics*(e: Elm): ElmDiag =
|
||||
e.diag
|
||||
Reference in New Issue
Block a user