polars_online.spec.kalman¶
- polars_online.spec.kalman(name: str, *, targets: Sequence[str | Target | FormulaTarget | Expr], features: list[str], coef_half_life: float | timedelta | str | Expr | list[float | timedelta | str | Expr] | None = None, q: list[float] | None = None, obs_var: float | None = None, p0: float | None = None, share_p: bool = False, revert_half_life: float | timedelta | str | Expr | list[float | timedelta | str | Expr] | None = None, standardize: bool = True, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
A regression whose coefficients drift, tracked by a Kalman filter.
Use it where a coefficient moves at a drift rate of its own, faster than one half-life for the whole fit can follow, or where a coefficient no row supports should be forgotten (
revert_half_life). Useewridge()for coefficients that hold still over a half-life, andrls()for an exact fit whose prior fades.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weight,groupand the diagnostics, are inpolars_online.spec. Herehalf_lifedrives the standardization and the residual variance, not the coefficients’ drift. This model’s own:coef_half_lifeHow fast a coefficient may drift, as a half-life in clock units, on standardized features: an observation
Dclock units after the target’s last adds the process noise(ln 2 * D / h_i) ** 2times the noiseR_j, withh_ithe coefficient’s half-life. The half-life is the same whether rows come every unit or every hundredth, and whether the target is seen on every row or one in ten (The drift in Notes). It is each standardized direction’s memory with the others held still, and a direction of correlated features is learned more slowly (Correlated features in Notes). A scalar, or one value per coefficient with the intercept first where there is one, each above 0.infgives that coefficient no drift: the filter takes it as constant and goes on learning it from every row. Required unlessqis given, and refused beside it. Understandardizethe drift is per standard deviation of each feature as the moments stand: a slope’s random walk in the caller’s units has a variance ofR_j * (ln 2 * D / h_i) ** 2 / s_i ** 2per observation,s_ithe feature’s standard deviation. The diagnostics’ statistics read the fit’s memory as the shortest finite entry (the model’shalf_lifewhere every entry isinf), and their readiness waits for the longer of the longest finite entry andhalf_life. The CUSUM underemit_breaksreads the intercept’s entry as the memory at which a level in the target is absorbed, andinfthere leaves the CUSUM a plain sum.qThe process noise given outright,
q_iper coefficient, in place of the derivation fromcoef_half_life, added asq_i * D ** 2on each row that observes the target. One value per coefficient, the intercept first where there is one, each finite and at least 0. Exactly one ofqandcoef_half_lifeis given. Its units are a coefficient’s squared per clock unit squared. Understandardizea slope is in the target’s units per standard deviation of its feature, soq_iis in the target’s squared units per clock unit squared. Without it, a slope’sq_iis in the target’s units over the feature’s, squared, per clock unit squared. The intercept’s is the target’s squared units per clock unit squared either way.qis measured against the noise estimate,q_i / R_j, which is how the estimate reaches the gain underq(The noise in Notes).obs_varA fixed observation noise in place of the estimated one: the variance of the target about its prediction, in the target’s squared units, finite and above 0. Default none, which estimates it as the exponentially weighted (EW) variance of the target’s out-of-sample residuals. It scales
se_coef. Undercoef_half_lifethe gain does not depend on its value, and underqit is theR_jthatqis measured against.Pis then absolute, and starts atp0 * obs_varon the intercept, and on each slope too wherestandardize=False. Understandardizeeach slope’s prior waits for its feature’s scale (The prior in Notes).p0The prior variance of each slope, in units of the noise: a ratio, with no units under
standardize. Withoutstandardizea slope’s priorp0 * Rcarries its feature’s units, sop0is in one over the feature’s squared units there. Default 1.0, a prior as uncertain as one observation. Finite and above 0. Keep it well below 1e10, where the covariance form loses digits (The prior in Notes).share_pKeep one
Pfor every target, where by default each target has its own. Targets observed on the same rows would each carry the sameP, so one update of then x nmatrix a row then serves every target,nthe number of coefficients. Every prediction is then the per-target filter’s, to the bit, except underq, which the sharedPmeasures against the targets’ mean noise. DefaultFalse, so that each target’s memory follows its own rows: where a target is null on rows another is present on, the sharedPtakes those rows too (A shared P in Notes).revert_half_lifeA reversion half-life
kappa_iper coefficient, in clock units, above 0: between observations the coefficient shrinks toward zero by2 ** (-d / kappa_i), so the filter forgets a coefficient no row has supported for a while, where a random walk would carry it unchanged. Defaultinf, the random walk, which adds nothing. A scalar applies to every coefficient, the intercept included. A list gives one per coefficient, intercept first, and[inf, h, h]leaves the intercept a random walk. Understandardizethe pull is toward zero in the standardized coordinates: a slope toward “no effect”, the intercept toward “the target averages zero”. A reverting coefficient’s uncertainty stays bounded across a run of rows that observe nothing (Reversion in Notes).standardizeRun the filter on standardized features, so
coef_half_lifeandp0mean the same thing whatever the columns’ scale. DefaultTrue. Each row is standardized against the EW meansm_iand standard deviationss_iof the rows before it,z_i = (x_i - m_i) / s_i. Without an intercept the features are scaled by their root mean square and not centered, as forewridge(). The reported coefficients are in the original units either way, and the moments’ changes move no prediction (Standardizing in Notes). Withstandardize=False,qall zeros, norevert_half_lifeand a fixedobs_var, the filter is exactly Bayesian linear regression. For a coefficient per current standard deviation, which moves with the scale, z-score the column in the query before the bank and give it withstandardize = False. Scale a feature by its spread builds the column withpolars_online.ewm_meanandpolars_online.ewm_std.
Output
One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#kalman 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. It reads a reason of the shared gates (
polars_online.spec), such asbelow_min_weighton the first rows under the defaultmin_weight. It readsbelow_warm_rowswhile no coefficient of the target has its prior set yet (The prior in Notes), as without an intercept before a feature’s scale is usable. A target’s first row has no prediction, since the model has learned nothing to predict from: withmin_weight=0,pred_<t>andwithheld_reasonboth read null there.coefPer target, the intercept (unless
fit_intercept=False) then one entry per feature, in the original units, after the row is learned (coef_index()).
plus the fields of the diagnostics switched on, as
polars_online.specdescribes them.se_coefanderror_inflationread the filter’s own covariance, and are exact only under the model (Standard errors in Notes).Raises
As every builder does (
polars_online.spec), andValueErrornaming the problem for:neither or both of
coef_half_lifeandq;a
coef_half_lifeorrevert_half_lifewhose list is neither one value nor one per coefficient, or with a value not above 0;a
qwhose list is not one value per coefficient, or with a value below 0 or not finite;an
obs_varorp0not finite or not above 0;emit_robust_se: the filter’s covariance is its own posterior, whichemit_se_coefreports.
The update
Per target
j, per row,dis the row’s clock step, the clock’s step since the last row the model did not skip, capped atgap_cap(orsession_gapat a session change).wis the row’s weight,zits standardized features with the intercept in front,y_jthe target,b_jthe coefficients andkappa_itherevert_half_life:b_j <- Phi b_j Phi = diag(2 ** (-d / kappa_i)) the reversion P_j <- Phi P_j Phi every row D_j <- D_j + d the clock since P_j's last observation P_j <- P_j + Q * D_j ** 2, D_j <- 0 the drift, on a row that observes y_j v = z' P_j z + 1 / w the innovation's variance g = P_j z / v the gain b_j <- b_j + g (y_j - z' b_j) P_j <- P_j - g z' P_jP_jis the coefficients’ covariance in units of the observation noiseR_j, so the covariance itself isR_j * P_j.Qis the process noise in the same units,(ln 2 / h_i) ** 2fromcoef_half_lifeorq_i / R_jfromq.R_jis the target’s EW residual variance, orobs_var. Underobs_varthe filter runs on the covariance itself:P_jandQareR_jtimes the above, andvisz' P_j z + R_j / w. A reverting coefficient’s drift over a gapDisQ_i * r_i(D) ** 2in place ofQ_i * D ** 2, withr_i(D) = (1 - 2 ** (-D / kappa_i)) / theta_iandtheta_i = ln 2 / kappa_i.Example
This code fits a slope that steps from 1 to 3 at row 2,000, and prints the slope the filter found just before the step, 10 rows after it and 100 rows after it:
import numpy as np rng = np.random.default_rng(3) x = rng.standard_normal(4_000) slope = np.where(np.arange(4_000) < 2_000, 1.0, 3.0) # the true slope y = slope * x + 0.2 * rng.standard_normal(4_000) pl.DataFrame({"x": x, "y": y}).write_parquet("step.parquet") k = po.spec.kalman( "k", targets=["y"], features=["x"], half_life=200.0, coef_half_life=20.0, # how fast a coefficient may drift, in rows coef_every=0, # write coef on every row ) out = pl.scan_parquet("step.parquet").online.fit_predict([k]).collect() coef = out["k"].struct.field("coef") for row in (1_999, 2_010, 2_100): print(f"row {row}: true slope {slope[row]:.0f}, found {coef[row][1]:.2f}")
row 1999: true slope 1, found 0.96 row 2010: true slope 3, found 1.55 row 2100: true slope 3, found 2.95
See also
ewridge(), for coefficients that hold still over a half-life.rls(), the fit this filter gives with no drift, a fixed noise,standardize=False, norevert_half_lifeandhalf_life=inf, atdelta = 1 / p0.polars_online.ModelBank.predict(), which moves the coefficients byPhiover the clock since the last learned row.
Notes
The noise.
R_jis per target, and its weight ages on every row, a row with no prediction or with weight 0 included. It learns from the filter’s own prediction on every row the filter predicts, whether or notmin_weightlets that prediction out.min_weightwithholds the output alone, so the fit, the variance and aqread against it are the same at anymin_weight. A row with no prediction, before the filter has sized the target’s coefficients, still moves them and adds to the target’s weight. Only the residual variance learns nothing from it. A row of weight 0, or one whose target is null, ages the target’s weight and learns nothing for it.Under
coef_half_lifethe noise is a scale, not a weight: the gain never reads the noise estimate. The model’s noise is one constant per target. The prior (p0times it) and the drift ((ln 2 * D / h) ** 2times it) are multiples of it, so it cancels from the gain. The estimate scales onlyse_coef:error_inflationand its gate readPin units of the noise, and wait only until the target has a residual variance. Underqthe estimate reaches the gain only throughq_i / R_j. A filter with the estimate inside the gain weighs each row by the inverse of the noise as it stood before the row, so a burst of large residuals inflates it and the rows after count for less than the burst did. In a run of that filter with no drift, a fifth of the first 500 rows 50 too high held the slopes at[-25.5, 33.6], where least squares on the same rows gives[4.1, -1.4]. The residual variance starts at the target’s first prediction. Underq, before a target’s first residual the row’s own squared innovation stands in for the noise, and a row whose innovation is exactly 0 adds no drift. Scaling a target bycscales its predictions byc, at anyp0, whenobs_varandq, where given, are scaled byc ** 2.States saved with the estimate in the gain. A state saved by a release that put the noise estimate inside the gain goes on as it was fitted, with the estimate in the gain.
The drift. The drift is charged once, on the row that next observes the target, for the whole clock since the last one (
D_j, or undershare_psince any target’s row), becauseQ * D ** 2is not additive over a split gap. Charged per row, a row of weight 0 inside a gap would shrink the gap’s noise and move every later prediction, by 0.197 in the target’s units atcoef_half_life = 20. And a target seen on one row in 10 would forget 3.6 times slower on the clock than one seen on every row: 270 clock units against 75, measured at the samecoef_half_life. The noise(ln 2 * D / h_i) ** 2matches the steady-state gain of recursive least squares under a half-lifeh_i(rls()) to first order inD / h_i: within 1% for observations closer than half a half-life, and within 4% at one.Correlated features. Under correlated features, a direction of the design’s correlation with eigenvalue
lambdais learned with a memory of abouth / sqrt(lambda)(Ljung and Gunnarsson 1990), where recursive least squares under a half-life forgets every direction ath. At a correlation of 0.9 andh = 50the memories measured 37.5 and 160.5 clock units, against 36.3 and 158.1 predicted. Undercoef_half_lifethe gain reads no noise estimate, so a step in the truth is learned at that memory however much it inflates the residual variance.The prior. Without
obs_varthe intercept’s prior is diffuse. The first row that observes the target fills the intercept with its whole innovation,b_0 = y - z' b, at a variance ofz' P z + 1 / w. That is the limit of a prior that knows nothing of the level. So a level in the target moves every prediction by the level, to the rounding of a number of its size, from the first. It needs neitherp0nor a noise: with no process noise the filter is least squares with the ridge1 / p0on each slope and none on the intercept, the noise’s estimate playing no part. Unstandardized, each slope’s prior isp0from the start. Standardized, it isp0from the first row that observes the target on which its feature’s scale is usable, and until then the slope is 0 and takes no correction. While no coefficient is sized the target is not predicted, and with an intercept every row after the first has one sized. Withobs_vargiven, unstandardized and with no process noise, the filter is the ridge regression with penalty1 / p0. A covariance whose diagonal goes below 0 is sized again atp0. The covariance form loses digits at a huge prior: as a stand-in for least squares it was 4.2e-6 off atp0=1e12, against 3.4e-10 at 1e8.Standardizing. The filter’s state is held in the coordinates of an anchor, the moments at its last re-map, and maps the process noise and the priors, defined in the moments as they stand, into them exactly. When the moments drift from the anchor (a scale by more than twice or less than half, a mean by more than the anchor’s scale), the state follows them to their new coordinates,
b <- A bandP <- A P A':A_00 = 1, A_0i = (m_i - m^a_i) / s^a_i, A_ii = s_i / s^a_i
with
m^a,s^athe anchor andm,sthe moments after the row. So a change in the moments moves no prediction, no predictive variance and no coefficient in the original units, from the first row. A feature reaches the filter only through its standardized valuez, so features scaled by a power of two predict the same to the bit. A filter read through the moments as they stand, the alternative, lets a finite half-life’s own wander in the moments move every prediction. It was measured ony = 2 x + ewith one featurex ~ N(0, 1), R² 0.99998, 30,000 rows and both half-lives 50. Over rows 10,000 to 30,000 its out-of-sample error stood 223 noise variances above the noise (the median of seeds 0 to 4, which ranged from 212 to 244). This filter stands 0.014 above it there, as the unstandardized one does. The anchor gives the same filter, to rounding, as a re-map on every row, and is a fifth cheaper a row at ten features (221 against 277 nanoseconds). A re-map past what a stretch of data makes (a scale by more than 1024 times either way, or a mean by more than 1024 of the anchor’s scale) is not followed, and the state is read in the new coordinates.Reversion. A reverting coefficient’s drift
Q_i * r_i(D) ** 2isQ_i * D ** 2for a gap well underkappa_i, and never more thanQ_i / theta_i ** 2. At observations one clock unit apart it is short ofQ_iby aboutln 2 / kappa_iof it. At observationsDapart, a reverting coefficient reaches the stationary prior varianceQ_i * r_i(D) ** 2 / (1 - phi_i ** 2)withphi_i = 2 ** (-D / kappa_i), a stationary AR(1) instead of an unbounded walk. The reversion runs on every row, a row that observes nothing included, being the same over a gap however it is cut. A prediction propagates the state by the samePhiover the row’s clock gap.polars_online.ModelBank.predict()moves the coefficients byPhiover the clock distance from the last learned row, capped bygap_cap. So however far past the data, a coefficient has shrunk by2 ** (-gap_cap / kappa_i)at most, and the prediction is the intercept alone only wheregap_capspans several of the slopes’ reversion half-lives and the intercept’s isinf.A shared P.
P’s recursion reads neither the targets nor the noise, since it is held in units of the noise. Every target observed on a row takes its gain fromPas the row finds it, andPtakes the row once, so the order of the targets moves no prediction. Where a target is null on rows another is present on, that target’s memory follows the others’ rows. A target first seen after the others has its intercept filled by its first innovation, as the diffuse prior fills each target’s. Underqthe sharedPmeasures it against the mean noise over the targets that have one. A target’sse_coefreadsPtimes its own noise.Standard errors.
se_coefreads the filter’s own covarianceR_j * P_j, anderror_inflationissqrt(1 + z' P⁻ z), withP⁻the covariance in units of the noise that the row’s update starts from, after the reversion and the drift. Both are exact under the model, which says the coefficients walk at the noisecoef_half_lifeimplies. On a truth that does not move, that walk is variance the coefficients do not have. The standard errors then come out aboutsqrt(2)too large: a mean squared error overse_coef ** 2of 0.47 to 0.50 atcoef_half_life50 and 200, against 0.95 to 1.06 on a walk of the implied variance. And withRthe EW variance of the out-of-sample residuals, which already carry the estimation error,error_inflationcounts that error twice: the mean squared error overR * error_inflation ** 2is 0.96 atcoef_half_life50.