polars_online.spec.rls¶
- polars_online.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), andhuber()withridge_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,groupand the diagnostics, are inpolars_online.spec. This model’s own:deltaThe prior’s strength: the fit starts from
A_0 = delta * I, which isP_0 = I / deltain the classic RLS notation. In the units ofA, a decayed sum ofw * 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 isewridge()’sridgeunderridge_scale = "sum", not under its default: it penalizes the intercept too, and it fades as rows arrive. Finite and above 0.ridgeis refused here, with a message namingdelta.coef_priorThe coefficients the fit starts from and is shrunk toward, one vector per target in the features’ original units,
len(features) + 1long 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_weightis 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_sumcounts every row. The factorRof 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 - predwhere the target is not null.weight_sumThe weight the model has accumulated before the row and before the row’s own decay.
settled_fracHow far the model had come toward its steady state under decay before the row.
withheld_reasonWhy the row’s predictions were withheld, null where they were not.
coefPer target, the intercept (unless
fit_intercept=False) then one entry per feature (coef_index()).
plus the fields of the diagnostics switched on, as
polars_online.specdescribes them.Raises
As every builder does (
polars_online.spec), andValueErrornaming the problem for adeltanot finite or not above 0, and acoef_priorwith the wrong number of vectors, a vector of the wrong length, or a value that is not finite.TypeErrorforridge, which this model callsdelta.The update
Per row,
wis the row’s weight,λ = 0.5 ** (Δclock / half_life)its decay (lam ** Δclockunderlam), andzthe features with the intercept in front.beta0_jis targetj’scoef_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
RofA = R'Randu_j = R^-T b_j, notAitself: a row is folded in by Givens rotations, andbetais read off by one back-substitution (the square-root form).Δclockis the clock’s step since the last row the model did not skip, capped atgap_cap, orsession_gapat 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 = po.spec.rls( "rls", targets=["y"], features=["x0", "x1"], half_life=float("inf"), delta=1e-3, # a weak prior, which the rows outweigh ) bank = po.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 underridge_scale="sum", solved on a schedule, whose defaultridgedoes not wind up.huber(), withridge_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 makesPasymmetric, 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 ofPto zero, which freezes that coefficient for good. The square-root form has neither failure. Its result isewridge()underridge_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 valuecother than 0 shows the fit onlyintercept + 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 defaultridgeis a penalty on the means that never fades, and it centers each feature, so it does not wind up. Measured withhalf_life=20(a row a clock unit),delta=1and 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 - yonce it moves: rms / worstrls, 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 row59
rls, constant at 1e8 from the first row76
rls, held at 00.41 to 0.53
never
0.20 / 0.74
ewridge(ridge=1e-6, solved every row), any of these0 to 0.51
never
0.19 to 0.20 / 0.37 to 0.74