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. Use quantile() to fit a quantile of the target, and sgd() with loss="huber" where learning a row must take O(k) time for k features: this model takes O(k²).

Parameters

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

huber_delta

The 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’ HuberT takes 1.345 and scikit-learn’s HuberRegressor 1.35. inf cuts nothing, which is least squares. sgd()’s huber_delta is the same constant in the same unit.

huber_scale

The scale s the 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_life

The scale’s own memory, a half-life in clock units (a duration on a temporal clock), above 0; inf forgets nothing. Default the spec’s half_life (or lam). 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_solves

As for ewridge(): the penalty (default 1e-6, finite and at least 0), correlation-form solving, and the solve schedule. ridge is on the mean-form Gram, in the features’ squared units, and dimensionless under standardize, which solves in correlation form.

feature_sets

Named subsets of features, each a fit of its own from the same sums, reported as pred_<t>__<set>, as ewridge()’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 in features or one twice in a set.

ridge_scale

What 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" is rls()’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. There S and eta are the target’s running means of z z' and z * y, z being the features with the intercept in front. W is the weight its sums hold, the Huber weights applied, p the product of every decay the stream has applied, and b the coefficients. With huber_delta=inf and "sum", the fit is rls()’s with delta=ridge, solved on the schedule rather than on every row, so huber(ridge_scale="sum") is the Huber form of rls() as ewridge(ridge_scale="sum") is its least-squares form. "sum" is refused beside standardize and beside two or more feature_sets.

emit_huber_scale

Emit huber_scale_<t>, each target’s residual scale s as 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 an s above 0, and on a skipped row. Under an embargo it is read where the row is predicted, as pred_<t> is. Default False.

huber_refit_rows

The 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 of 10 * features rows would run for seconds a target. A count given is taken at any number of features. It is at most 2 ** 20, since each target’s buffer is allocated at its full size at its first learned row. 0 turns 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, beside ridge_scale = "sum", whose prior has faded over the rows the refit would fit again, and beside an infinite huber_delta, least squares.

refit_budget

A bound in MiB on the refit buffers of all the spec’s groups together, above 0, or inf for 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, and bank.summary()’s refit_given_up counts the targets of each instance, the part of the model that fits one half-life (The refit’s memory in Notes).

min_weight counts 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 any min_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. A min_weight below 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 - pred where the target is not null. Under two or more feature_sets, one pair per set, pred_<t>__<set>.

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.

huber_scale_<t>

Under emit_huber_scale: the scale the row’s cut is drawn in, an f64, null until the target has an s above 0 and on a skipped row.

coef

Per target, the intercept (unless fit_intercept=False) then one entry per feature (coef_index()). Under feature_sets, one per target and set, 0 for a feature outside the set.

support_coef

On coef’s rows, each coefficient’s data share, laid out like coef: how much of the fit after the row the data, as the loss weighs the rows, determined rather than the ridge (polars_online.spec). Under feature_sets, null for a feature outside the set.

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

Raises

As every builder does (polars_online.spec), and ValueError naming the problem for:

  • a huber_delta not above 0, a huber_scale other than "mad" or "rms", and a huber_scale_half_life not above 0;

  • a ridge below 0 or not finite, a solve_every below 0, and a max_rows_between_solves of 0;

  • a feature_sets that names no set, names one twice, holds an empty set, or names a column not in features or one twice in a set;

  • a ridge_scale other than "mean" or "sum", and "sum" beside standardize or two or more feature sets;

  • a huber_refit_rows below 0 or above 2 ** 20, or above 0 beside ridge_scale = "sum" or an infinite huber_delta;

  • a refit_budget not above 0.

The update

Per row, e is the target’s residual (the prediction made before the row is learned, subtracted from the target), d = huber_delta, s the target’s residual scale as the row arrives, and w the row’s weight:

w_robust = 1              if |e| <= d * s
         = d * s / |e|    otherwise
the ewridge update, at weight w * w_robust

The weights are per target, so the running sums are per target here, where ewridge() shares one set across targets. Until a target has an s above 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 beside ewridge()’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() with loss="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 Z standard 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 at k = 1.345 (Huber 1981).

The scale. s is the part of the estimator that makes it robust, so it is a robust scale by default. With huber_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 s above 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. An s taken 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 with x > 0 (so they tilt the slope), the median slope over five seeds:

outliers

least squares

"mad"

"rms"

statsmodels RLM, MAD scale, converged

1% 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-life

19.5

"mad", at a huber_scale_half_life of 100

14.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 s is the largest set’s too. The largest set is the fit of a huber on its features alone, to the bit. The default min_weight counts 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 s learns the pulled fit’s residuals. The cut d * s is 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 reaches huber_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 passes

The target’s sums are then rebuilt from the rows at their converged weights, and s from 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 from RLM at 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=200 left 18, 5 of them more than 0.25 (the worst by 5.8), and huber_refit_rows=1000 left 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 from RLM, 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) * 8 bytes a learned row under the MAD ((features + 4) * 8 under "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). Under refit_budget and the MAD, each new group reserves (features + 26) * 8 bytes 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() and sgd() 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: coef under an embargo of E rows is the undelayed run’s coef of E rows earlier, to the bit. The weight is out-of-sample either way, since the row’s own target is in neither fit.