Files
SirRoboGarage/DevControlBot_garage/DevControlBot/modules/ELM/README.md
T
SirStone 7598f7db4a 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.
2026-10-05 22:42:12 +02:00

151 lines
6.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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`.