rheon.spec.rls

rheon.spec.rls(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], features: list[str], delta: float | None = None, coef_prior: list[list[float]] | None = None, **common: Unpack[CommonKwargs]) → dict[str, Any][source]

Recursive least squares, which solves the ridge fit exactly on every row.

Use it where every row’s prediction must come from coefficients solved through the row before it, with a prior that fades as rows arrive. Use ewridge() for a long stream whose features can hold one value for a long time, which winds this fit up (Wind-up in Notes), and huber() with ridge_scale="sum" for this fit under a Huber loss.

Parameters

The stream parameters every builder takes, such as clock, half_life, gap_cap, min_weight, group and the diagnostics, are in rheon.spec. This model’s own:

delta

The prior’s strength: the fit starts from A_0 = delta * I, which is P_0 = I / delta in the classic RLS notation. In the units of A, a decayed sum of w * z z': the features’ squared units, summed over rows. Default 1.0, which weighs the prior about as much as one row whose features are of unit scale. It is ewridge()’s ridge under ridge_scale = "sum", not under its default: it penalizes the intercept too, and it fades as rows arrive. Finite and above 0. ridge is refused here, with a message naming delta.

coef_prior

The coefficients the fit starts from and is shrunk toward, one vector per target in the features’ original units, len(features) + 1 long when there is an intercept. Default none, which starts from zeros. Refused with the wrong number of vectors, a vector of the wrong length, or a value that is not finite.

min_weight is checked against the weight of the rows the model learned (those with every target present), decayed, so rows with a null target do not warm up a fit they never reached. weight_sum counts every row. The factor R of The update is shared between the targets, so a row with any null target is predicted for every target and learned for none.

Output

One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#rls gives each field’s type and when it is null:

pred_<t>, resid_<t>

Per target: the prediction, and y - pred where the target is not null.

weight_sum

The weight the model has accumulated before the row and before the row’s own decay.

settled_frac

How far the model had come toward its steady state under decay before the row.

withheld_reason

Why the row’s predictions were withheld, null where they were not.

coef

Per target, the intercept (unless fit_intercept=False) then one entry per feature (coef_index()).

plus the fields of the diagnostics switched on, as rheon.spec describes them.

Raises

As every builder does (rheon.spec), and ValueError naming the problem for a delta not finite or not above 0, and a coef_prior with the wrong number of vectors, a vector of the wrong length, or a value that is not finite. TypeError for ridge, which this model calls delta.

The update

Per row, w is the row’s weight, λ = 0.5 ** (Δclock / half_life) its decay (lam ** Δclock under lam), and z the features with the intercept in front. beta0_j is target j’s coef_prior, 0 without one:

A <- λ * A + w * z z'          b_j <- λ * b_j + w * y_j * z        beta_j = A^-1 b_j
A_0 = delta * I                b_0j = delta * beta0_j

The model keeps the factor R of A = R'R and u_j = R^-T b_j, not A itself: a row is folded in by Givens rotations, and beta is read off by one back-substitution (the square-root form). Δclock is the clock’s step since the last row the model did not skip, capped at gap_cap, or session_gap at a session change.

Example

This code fits a plane with an intercept of 1 and slopes of 2 and -0.5, with no decay, and prints the coefficients found:

import numpy as np

rng = np.random.default_rng(2)
x0, x1 = rng.standard_normal(2_000), rng.standard_normal(2_000)
y = 1.0 + 2.0 * x0 - 0.5 * x1 + 0.3 * rng.standard_normal(2_000)
pl.DataFrame({"x0": x0, "x1": x1, "y": y}).write_parquet("plane.parquet")

rls = rp.spec.rls(
    "rls", targets=["y"], features=["x0", "x1"], half_life=float("inf"),
    delta=1e-3,                           # a weak prior, which the rows outweigh
)
bank = rp.ModelBank([rls])
bank.fit(pl.scan_parquet("plane.parquet"))  # learn every row, keep no output
print("planted: intercept 1.00, x0 2.00, x1 -0.50")
for r in bank.coef().iter_rows(named=True):
    print(f"{r['term']}: {r['coef']:.2f}")
planted: intercept 1.00, x0 2.00, x1 -0.50
intercept: 1.02
x0: 2.00
x1: -0.50

See also

  • ewridge(), the same fit under ridge_scale="sum", solved on a schedule, whose default ridge does not wind up.

  • huber(), with ridge_scale="sum", this fit with each row down-weighted by its residual.

  • kalman(), for coefficients that drift as a random walk.

Notes

The square-root form. In the textbook recursion on the inverse P, rounding makes P asymmetric, and the recursion multiplies the asymmetry by the inverse of the row’s decay factor each row. One extreme row can also cancel a direction of P to zero, which freezes that coefficient for good. The square-root form has neither failure. Its result is ewridge() under ridge_scale = "sum" solved on every row, to better than 1e-9.

Wind-up. A feature that holds one value for a long time winds the fit up, so use ewridge() for a long stream whose features can go quiet. The prior fades with the sums, so nothing holds a coefficient in a direction the data stop exciting. A feature held at a value c other than 0 shows the fit only intercept + c * slope. The information that tells the slope from the intercept then decays with every row, with nothing to renew it. Once it is under a rounding step, rounding sets the slope, and the slope wanders. A feature constant from its first row winds up the same way. Held at exactly 0, it excites nothing in that direction, and the slope stays where it was. ewridge()’s default ridge is a penalty on the means that never fades, and it centers each feature, so it does not wind up. Measured with half_life=20 (a row a clock unit), delta=1 and noise 0.17, on a feature held for 150 half-lives after 300 rows of moving, then moving again for 200 rows (10 half-lives). The fit held for some 30 half-lives in every case measured:

the run

the slope while held (0.5 in the data)

it first passes 1

pred - y once it moves: rms / worst

rls, held at 0.87

-3.1e13 to 3.0e13

54 half-lives in

3.1e11 / 4.4e12

rls, held at 1,000

-8.3e9 to 8.1e9

43

8.3e7 / 1.2e9

rls, held at 1e8

-4.6e5 to 4.5e5

62

4.6e3 / 6.5e4

rls, constant at 0.37 from the first row

-3.0e13 to 3.1e13

50

7.0e11 / 9.9e12

rls, constant at 1,000 from the first row

59

rls, constant at 1e8 from the first row

76

rls, held at 0

0.41 to 0.53

never

0.20 / 0.74

ewridge (ridge=1e-6, solved every row), any of these

0 to 0.51

never

0.19 to 0.20 / 0.37 to 0.74