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:
@@ -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