polars_online.spec.huber¶
- polars_online.spec.huber(name: str, *, targets: Sequence[str | Target | FormulaTarget | Expr], features: list[str], huber_delta: float | None = None, huber_scale: Literal['mad', 'rms'] | None = None, huber_scale_half_life: float | timedelta | str | Expr | None = None, ridge: float | None = None, standardize: bool = False, solve_every: float | timedelta | str | Expr | None = None, max_rows_between_solves: int | None = None, feature_sets: dict[str, list[str]] | None = None, ridge_scale: Literal['mean', 'sum'] = 'mean', emit_huber_scale: bool = False, huber_refit_rows: int | None = None, refit_budget: float | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Huber regression on running sums, which down-weights the rows a prediction misses by far.
Use it in place of
ewridge()where a share of the rows are outliers that would pull a least-squares fit. Usequantile()to fit a quantile of the target, andsgd()withloss="huber"where learning a row must take O(k) time forkfeatures: this model takes O(k²).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:huber_deltaThe cut, in units of the residuals’ scale
s, above 0: a residual within it counts at full weight, and one beyond it pulls the fit less the further it misses. Default 1.345, the cut at which Huber’s estimator is 95% as efficient as least squares when the errors are normal (The default cut in Notes). statsmodels’HuberTtakes 1.345 and scikit-learn’sHuberRegressor1.35.infcuts nothing, which is least squares.sgd()’shuber_deltais the same constant in the same unit.huber_scaleThe scale
sthe cut is drawn in:"mad"(the default), the exponentially weighted median of|e|over 0.6745, or"rms", the exponentially weighted root mean square of the residuals about 0. The MAD holds until half the weight is on outliers, where one wild row sets the root mean square (The scale in Notes).huber_scale_half_lifeThe scale’s own memory, a half-life in clock units (a duration on a temporal clock), above 0;
infforgets nothing. Default the spec’shalf_life(orlam). A scale memory shorter than the fit’s follows a level shift sooner, at the price of letting a longer burst of outliers widen the cut (A level shift in Notes).ridge,standardize,solve_every,max_rows_between_solvesAs for
ewridge(): the penalty (default1e-6, finite and at least 0), correlation-form solving, and the solve schedule.ridgeis on the mean-form Gram, in the features’ squared units, and dimensionless understandardize, which solves in correlation form.feature_setsNamed subsets of
features, each a fit of its own from the same sums, reported aspred_<t>__<set>, asewridge()’s are. The full set is fitted only when it is one of them, and a single set is no grid: its fields take no suffix. A row’s Huber weight comes from the largest set’s residual, the set with the most features, the first of them where two tie. So a smaller set’s fit is the weighted least squares fit at the weights the largest set’s residuals chose, not a Huber fit of its own (Feature sets in Notes). Refused when it names no set, names a set twice, holds an empty set, or names a column not infeaturesor one twice in a set.ridge_scaleWhat the ridge is scaled against, as for
ewridge()."mean"(the default) is a fixed penalty on the mean-form sums, whose pull is permanent."sum"isrls()’s prior on the decaying sum scale,(W * S + p * ridge * I) b = W * eta, which fades as the rows arrive and penalizes the intercept too. ThereSandetaare the target’s running means ofz z'andz * y,zbeing the features with the intercept in front.Wis the weight its sums hold, the Huber weights applied,pthe product of every decay the stream has applied, andbthe coefficients. Withhuber_delta=infand"sum", the fit isrls()’s withdelta=ridge, solved on the schedule rather than on every row, sohuber(ridge_scale="sum")is the Huber form ofrls()asewridge(ridge_scale="sum")is its least-squares form."sum"is refused besidestandardizeand beside two or morefeature_sets.emit_huber_scaleEmit
huber_scale_<t>, each target’s residual scalesas the row’s cut reads it: after the row’s decay and before the row’s own residual enters it. So the field is out-of-sample by construction, and can serve as a weight or to standardize the residuals robustly. Null until the target has ansabove 0, and on a skipped row. Under anembargoit is read where the row is predicted, aspred_<t>is. DefaultFalse.huber_refit_rowsThe learned rows (each of positive weight, with its target) after which each target’s first rows are refit to convergence, once, as a batch fit does (The refit of the first rows in Notes). Default
max(500, 10 * features)up to 100 features, and off above 100, where a refit of10 * featuresrows would run for seconds a target. A count given is taken at any number of features. It is at most2 ** 20, since each target’s buffer is allocated at its full size at its first learned row.0turns the refit off. A group shorter than the count never refits, and holds its rows to the end. Off by default, and a count above 0 is refused, besideridge_scale = "sum", whose prior has faded over the rows the refit would fit again, and beside an infinitehuber_delta, least squares.refit_budgetA bound in MiB on the refit buffers of all the spec’s groups together, above 0, or
inffor none. Default 320. Each new group reserves the most its targets’ buffers can hold when it first appears, and keeps it for the life of the bank, so which groups refit depends neither on the chunking nor on the order the groups run in. The group that would cross the bound, and every new group after it, gives its refit up and keeps its one-pass fit. A readiness warning says so once, andbank.summary()’srefit_given_upcounts the targets of each instance, the part of the model that fits one half-life (The refit’s memory in Notes).
min_weightcounts the rows the target was present on, at their weights, decayed. The reweighted sum, which an outlier lowers, is not what it reads, so a stream whose warm-up meets outliers reports its first prediction when the rows say to. It withholds the output alone: the fit learns from the prediction it made on a row the gate withholds (the scale takes its residual, and the row its Huber weight), so it is the same fit at anymin_weight. A target’s first prediction, reported or learned from, waits for its own first row per coefficient of the largest feature set, the model’s floor, since a fit of fewer rows than unknowns is the ridge’s alone. Amin_weightbelow that withholds nothing more.Output
One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#huber 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. Under two or morefeature_sets, one pair per set,pred_<t>__<set>.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.
huber_scale_<t>Under
emit_huber_scale: the scale the row’s cut is drawn in, an f64, null until the target has ansabove 0 and on a skipped row.coefPer target, the intercept (unless
fit_intercept=False) then one entry per feature (coef_index()). Underfeature_sets, one per target and set, 0 for a feature outside the set.support_coefOn
coef’s rows, each coefficient’s data share, laid out likecoef: how much of the fit after the row the data, as the loss weighs the rows, determined rather than the ridge (polars_online.spec). Underfeature_sets, null for a feature outside the set.
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:a
huber_deltanot above 0, ahuber_scaleother than"mad"or"rms", and ahuber_scale_half_lifenot above 0;a
ridgebelow 0 or not finite, asolve_everybelow 0, and amax_rows_between_solvesof 0;a
feature_setsthat names no set, names one twice, holds an empty set, or names a column not infeaturesor one twice in a set;a
ridge_scaleother than"mean"or"sum", and"sum"besidestandardizeor two or more feature sets;a
huber_refit_rowsbelow 0 or above2 ** 20, or above 0 besideridge_scale = "sum"or an infinitehuber_delta;a
refit_budgetnot above 0.
The update
Per row,
eis the target’s residual (the prediction made before the row is learned, subtracted from the target),d = huber_delta,sthe target’s residual scale as the row arrives, andwthe row’s weight:w_robust = 1 if |e| <= d * s = d * s / |e| otherwise the ewridge update, at weight w * w_robustThe weights are per target, so the running sums are per target here, where
ewridge()shares one set across targets. Until a target has ansabove 0, no row is down-weighted (The scale in Notes).Example
This code fits a slope of 2 on rows of which 5% miss by +50, all where
x > 0, so they tilt a least-squares slope. It prints the slope this model finds besideewridge()’s:import numpy as np rng = np.random.default_rng(3) x = rng.standard_normal(5_000) y = 1.0 + 2.0 * x + 0.5 * rng.standard_normal(5_000) y[(x > 0) & (rng.random(5_000) < 0.1)] += 50.0 # the outliers, all on one side pl.DataFrame({"x": x, "y": y}).write_parquet("outliers.parquet") common = dict(targets=["y"], features=["x"], half_life=float("inf")) bank = po.ModelBank([ po.spec.huber("hub", **common), # the default cut, 1.345 of the scale po.spec.ewridge("ls", **common), # least squares, for comparison ]) bank.fit(pl.scan_parquet("outliers.parquet")) # learn every row, keep no output print("the true slope: 2.00") for r in bank.coef().filter(pl.col("term") == "x").iter_rows(named=True): print(f"{r['spec']}: slope {r['coef']:.2f}")
the true slope: 2.00 hub: slope 2.05 ls: slope 4.10
See also
ewridge(), the least-squares fit on the same sums.quantile(), a fit of a quantile of the target, on the same sums and refit.sgd()withloss="huber", the same loss with a step per row in O(k) time.
Notes
Out-of-sample weights. Each row’s weight is scaled by the Huber weight of its residual against the prediction made before the row is learned, so the reweighting stays out-of-sample.
The default cut. With
Zstandard normal andψthe residual clipped at±k, the efficiency of Huber’s estimator against least squares is(2Φ(k) − 1)² / E[ψ(Z)²], which is 0.95 atk = 1.345(Huber 1981).The scale.
sis the part of the estimator that makes it robust, so it is a robust scale by default. Withhuber_scale = "mad"it is the exponentially weighted median of|e|divided byΦ⁻¹(3/4) = 0.6745, which makes it the standard deviation when the errors are normal. A wild row moves a median by its weight, whatever its size, so the outliers cannot widen the cut that is meant to catch them: the scale holds until half the weight is outliers. The median is read from a quantile sketch per target, within 0.78% of the exact weighted median. The sketch’s buckets span at most 16 octaves around the median, a factor of 65,536, and a residual beyond them is folded into the outermost bucket on its side, its weight kept. So the sketch holds at most about 9 KB of state per target, whatever the residuals, and takes 14 to 17 ns per target per row. While half the weight or more is on residuals of exactly 0 the median is 0, and the 16 octaves reach up from the smallest residual instead. Nothing is folded while the residuals span less, and the median reads what an unbounded sketch would unless it later moves past a bucket a residual was folded into, at least a factor of 256 from where it stood then. That happens when a fit’s first residuals, at the target’s level, are more than 65,536 times the noise’s, and the median reads too high until the later residuals outweigh them. The sketch’s buckets are fixed at a unit of 1 until the refit of the first rows sets their unit at the median of its converged residuals. From then a target rescaled by any factor, grams for kilograms, rescales the scale and the fit to rounding. With the refit off, a factor other than a power of two can move the median by up to a bucket, 1.6%, and moved the predictions by up to 0.4% of the target’s spread where measured.With
huber_scale = "rms"the scale is the exponentially weighted root mean square of the residuals about 0, in which every row counts by its size. One wild row sets it, and a fit’s first residuals, the target’s whole level while the intercept is still near 0, widen it for as long as the decay keeps them.Both scales age on every row the model sees, a row with no prediction or with weight 0 included, so they forget across a gap as the clock says, and each learns a residual at the row’s own weight, not at its Huber weight. Until a target has an
sabove 0, no row is down-weighted. That is before its first residual, or while every residual so far is exactly zero (under"mad", while half the weight is on such residuals), and there is then nothing to judge an outlier against. Anstaken as 1 there would be a cut in the target’s own units, which would down-weight the first predicted rows of a target in millions and none of one in millionths.Measured on
y = 1000 + 2x + 0.5εover 20,000 rows with no decay, an outlier of +50 on a share of the rows withx > 0(so they tilt the slope), the median slope over five seeds:outliers
least squares
"mad""rms"statsmodels
RLM, MAD scale, converged1% of rows
2.415
2.008
2.057
2.008
5%
4.050
2.040
2.675
2.039
12.5%
6.975
2.124
4.882
2.124
A level shift. In a series a run of large residuals is either a burst of outliers or a new level, and no rule on one row tells the two apart. A robust scale treats every row after a level shift as an outlier until the median itself has moved, so it holds the fit back for longer than least squares does. Measured with a fit half-life of 500 rows and a shift of +20 (40 noise standard deviations), the mean absolute error over the 200 rows from 200 rows after the shift was:
the fit
mean absolute error
least squares
13.3
"rms"15.1
"mad", at the fit’s half-life19.5
"mad", at ahuber_scale_half_lifeof 10014.6
Feature sets. The sets share the target’s sums, and a sum holds each row at one weight, so the weight is one number per row and target. Weighting each set by its own residual would need a set of sums per set. The residual scale
sis the largest set’s too. The largest set is the fit of ahuberon its features alone, to the bit. The defaultmin_weightcounts every feature of the spec, so a largest set short of them is reported later, the fit unchanged.The refit of the first rows. One pass weighs each row by the fit before it. Over the first rows that fit is close to least squares, so a share of outliers pulls it, and
slearns the pulled fit’s residuals. The cutd * sis then wide, the outliers keep entering at nearly full weight, and without decay the fit stays where they pulled it. A median over a few streams hides this: on the stream above, 20,000 rows at 12.5% outliers, the median stream was within 0.002 of statsmodels’RLM, while 13 of 40 streams ended more than 0.05 from it, the worst by 0.43. So on the row a target’s count of learned rows reacheshuber_refit_rows, those rows are refit by iteratively reweighted least squares, as a batch fit does:v_i = w_i * (the decay factors of the rows after i) v_i' the same by the scale's clock (huber_scale_half_life) r_i = y_i - z_i'b against the last pass's fit s = weighted median of |r_i| at v_i', over 0.6745 (root mean square under "rms") u_i = min(1, d * s / |r_i|) b = the ridge solve of the rows at v_i * u_i repeated until no row's fit z_i'b moves by over 1e-10 of s, or 200 passesThe target’s sums are then rebuilt from the rows at their converged weights, and
sfrom the converged fit’s residuals, and the stream goes on online. It runs after the row’s own prediction, and moves its own target’s fit alone. Over 20,000 rows with the refit no stream of the 40 was more than 0.05 fromRLMat 5% to 15% outliers, and 4 at 20%, where 25 were without it. Over 2,000 rows the tail is longer: at 20%, 10 of 40 streams stayed more than 0.05 away with the default, 1 of them more than 0.25 (by 0.32), where 29 were without it.huber_refit_rows=200left 18, 5 of them more than 0.25 (the worst by 5.8), andhuber_refit_rows=1000left 3, none more than 0.25. Over 20,000 rows at 20% one-sided outliers, 50 rows left 14 of 40 streams more than 0.05 fromRLM, 200 and 500 left 4 and 1,000 left 2. Over 2,000 rows, 200 left 18, 500 left 10 and 1,000 left 3.Under the MAD, while a target’s refit waits, its scale is read exactly, as the weighted median of the residuals its buffer holds (The scale in Notes gives the sketch it builds after). A saved state keeps the scale rule it was saved under, and continues to the bit.
The refit’s memory. A target’s rows are held until its refit:
(features + 10) * 8bytes a learned row under the MAD ((features + 4) * 8under"rms"). A run of rows that only aged it (its value null or its weight 0) takes 32 bytes, and consecutive such rows at the same clock step are one run. Once its runs number more than 4 for each row of the count, as on a target present on fewer than about one row in five under an irregular clock, the target gives its refit up and keeps its one-pass fit. The refit takes 0.06 to 7.2 ms once, for 1 to 50 features and 200 to 1,000 rows (an Apple M4 Pro under other load, best of 9). Underrefit_budgetand the MAD, each new group reserves(features + 26) * 8bytes a target of each instance for each row of the count: the row, its residual, its node in the tree the MAD is read from, and its 4 runs. Under"rms"it reserves(features + 20) * 8, the row and its 4 runs. A half-life grid reserves once per value. A group’s reservation is not handed back when its refit frees its buffer, so once the bound is reached no later group refits. At 20 features and 500 rows a target reserves 184 KB, and 320 MiB refits the first 1,823 targets.Against a band. The cut stays in the residual’s scale where the insensitivity bands of
pa()andsgd()are in the target’s own. A row beyond the cut still moves the fit, at a weight that shrinks with its miss, so a cut that early residuals widen does not stop the fit learning. A row inside a band moves nothing, so a band that early residuals widen does: a fit from zero coefficients has the target’s whole level for its first residuals.A target that arrives late. A row’s Huber weight is read when it is learned. Under an
embargo, or with a formula target, a row is predicted where it arrives and learned once its target is known, the held rows in the order they arrived. Its Huber weight is read then, from its residual against the fit at that moment: the fit of every row before it and of none after it, which is the fit it would be weighed by without the delay. So the delay moves the predictions, which come from an older fit. It leaves the fit, the weights and the scale as they are without it:coefunder an embargo ofErows is the undelayed run’scoefofErows earlier, to the bit. The weight is out-of-sample either way, since the row’s own target is in neither fit.