polars_online.spec.quantile¶
- polars_online.spec.quantile(name: str, *, targets: Sequence[str | Target | FormulaTarget | Expr], features: list[str], quantile: float, ridge: float | None = None, standardize: bool = False, solve_every: float | timedelta | str | Expr | None = None, max_rows_between_solves: int | None = None, quantile_eps: float | None = None, quantile_refit_rows: int | None = None, refit_budget: float | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Quantile regression on running sums, the fit that a share
tauof the targets fall below.Use it for a conditional median, which outliers cannot pull, or for a tail, such as the 0.9 quantile of a return, where a mean says nothing. Use
huber()for a mean that outliers should not pull, andsgd()withloss="quantile"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:quantileThe level
tau, in(0, 1); required. 0.5 is a median regression.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.quantile_epsThe band’s half-width in units of the residuals’ scale
s, finite and above 0. Default 0.2, at which the band holds about a sixth of the rows of normal noise at the median and a seventh at the 0.9 quantile. A much narrower band converges more slowly, and a much wider one smooths the quantile toward the mean (The band in Notes).quantile_refit_rowsThe learned rows (each of positive weight, with its target) after which each target’s first rows are refit to convergence, once (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 up to2 ** 20, since each target’s buffer is allocated at its full size at its first learned row, but one below three rows a coefficient, the rows the warm-up takes as least squares, is refused.0turns the refit off. A group shorter than the count never refits and holds its rows to the end.refit_budgetA bound in MiB on the refit buffers of all the spec’s groups together, above 0, or
inffor none. Default 320. As forhuber(): each new group reserves the most its targets’ buffers can hold when it first appears, and keeps it for the life of the bank. The group that would cross the bound, and every new group after it, 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 band’s weight, which a half-life caps at the band’s share of the sample, is not what it reads. It withholds the output alone: the fit learns from the prediction it made on a row the gate withholds, 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, 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#quantile gives each field’s type and when it is null:
pred_<t>,resid_<t>Per target: the prediction, the conditional quantile, and
y - predwhere the target is not null. A residual is signed against the quantile, so once the fit has converged a sharetauof them are negative, and1 - taupositive.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 then one entry per feature (
coef_index()).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).
plus the fields of the diagnostics switched on, as
polars_online.specdescribes them.Raises
As every builder does (
polars_online.spec),TypeErrorwithoutquantile, andValueErrornaming the problem for:a
quantilenot strictly between 0 and 1;a
quantile_epsnot finite or not above 0;a
quantile_refit_rowsother than 0 below three rows a coefficient, or above2 ** 20, and arefit_budgetnot above 0;a
ridgebelow 0 or not finite, asolve_everybelow 0, and amax_rows_between_solvesof 0.
The update
One Newton step per row on the check loss smoothed by a uniform kernel, linearized at the fit the row was predicted with, so it stays out-of-sample. Per row,
eis the target’s residual,psi(e) = tau - 1{e < 0},sthe target’s residual scale andwthe row’s weight.h = quantile_eps * sis the band’s half-width (never below the floor of The band in Notes),Athe band’s system,uthe row’s deviation from the means, andzthe features with the intercept in front:|e| < h: a least-squares row, with target y + 2h (tau - 1/2) |e| >= h: no weight in the sums; w * 2h * psi(e) * z into the cross-moment, over the band's weight, capped at |e| / (1 + u' A^-1 u)The cap reads the row’s full leverage against
A: a nudge brings the row’s own prediction at most to its target, and never past it. Under three rows per coefficient, and until a target has ansabove 0, the fit is ordinary least squares (Warm-up and rebuilding in Notes).Example
This code fits the 0.9 quantile of a line with normal noise of spread 1, whose intercept is
1 + 1.28, and prints the line found:import numpy as np rng = np.random.default_rng(4) x = rng.standard_normal(20_000) y = 1.0 + 2.0 * x + rng.standard_normal(20_000) # the 0.9 quantile is 2.28 + 2x pl.DataFrame({"x": x, "y": y}).write_parquet("tail.parquet") q90 = po.spec.quantile( "q90", targets=["y"], features=["x"], half_life=float("inf"), quantile=0.9, # the level to fit ) bank = po.ModelBank([q90]) bank.fit(pl.scan_parquet("tail.parquet")) # learn every row, keep no output print("the true line: intercept 2.28, slope 2.00") c = {r["term"]: r["coef"] for r in bank.coef().iter_rows(named=True)} print(f"found: intercept {c['intercept']:.2f}, slope {c['x']:.2f}")
the true line: intercept 2.28, slope 2.00 found: intercept 2.31, slope 1.99
See also
huber(), the robust fit of the mean, whose scale sketch this model reads.ewridge(), the least-squares fit on the same sums.sgd()withloss="quantile", a step per row in O(k) time.
Notes
Why a Newton step. The smoothed loss has the same curvature on either side of the fit, so the rows’ own history cancels and the fit converges to the quantile regression. Reweighting the rows by the check loss’s iteratively reweighted least squares (IRLS) weight,
psi(e) / e, does not converge to it. That weight is the secant of this step where the step is its tangent, and it is unbounded asegoes to zero. A row whose residual against the fit before it happened to be near zero then holds the fit near the fit it was predicted by. Measured at the median of a skewed noise after 20 000 rows againststatsmodels’QuantReg, the step is 0.005 away, insideQuantReg’s own standard error of 0.007, where the weights ended 0.164 short.The scale.
sis the MAD of the target’s residuals: their exponentially weighted median of|e|overPhi^-1(3/4) = 0.6745, which is the standard deviation for normal residuals, aged on the model’s clock. A wild row moves a median by its weight, not by its size, so the rows the band is there to bound cannot widen it. In their root mean square they did: at 5% of the rows lifted by a hundred noise deviations, all on one side, the root mean square stood near 11 against a noise of 0.5. The band held every clean row as a least-squares row and gave every wild row a pull of the band’s width. Every one of 50 streams of 20,000 rows ended more than 0.05 fromstatsmodels’QuantRegon the same rows, the worst 0.098 at 5% and 0.98 at 20%. In the MAD none did, the worst 0.006 at 5% and 0.026 at 20%, with or without a half-life of 5,000. The median is read fromhuber()’s sketch, whose 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 rescaled target rescales the band and the fit to rounding. With the refit off, a decimal factor can move the scale by up to a bucket of the sketch, about 1.6%, and moved the fit by up to 0.044 of the target’s spread where measured.The band.
hisquantile_eps * s. The rows inside the band are the curvature the step leans on, so a much narrower band converges more slowly and a much wider one smooths the quantile toward the mean. The band is never narrower than(k / n) ** 0.4ofs, the smoothed-quantile bandwidth rate. Herekis the number of coefficients, andnthe target’s present rows counted one each, decayed, whatever their weights. Under a half-life the band’s share of the sample is a few rows, and the floor is what keeps the step fed there. A long stream leaves the floor behind. Coverage atquantile = 0.9on normal noise reads 0.895 athalf_life = 30and 0.900 from 200 up.Warm-up and rebuilding. Under three rows per coefficient of the rows the target was present on, the fit is ordinary least squares: a Newton step needs a Hessian, and a band around a fit built from a handful of rows is not one. The same rule rebuilds the fit after a gap or a reset has aged the weight away. A band holding under one row per coefficient, in rows of the target’s mean weight, takes least-squares rows too, until it holds rows again. That is what rebuilds a fit a row at the input bound leaves behind. Such a row sets the sums at its own scale, and every later row is outside the band. Only nudges arrive, each
w * 2h * psi * zover the band’s weight. They cannot move the fit until that weight has decayed to nothing, and each is then a step that outgrows the band. From one row up an outside row’s step lands inside the band, and the floor keeps a band at its steady state well clear of one row, so the rule does not fire in steady state. Both rules count rows, so a weight’s scale reaches neither. Rules that compared the rows’ weight with a row count would let rows at weight 100 leave the warm-up on their first row, where the fit reached 1e51.Until a target has an
sabove 0, its rows are least squares too. That is before its first residual, or while every residual so far is exactly zero, and the band, a width in units ofs, has nothing to be drawn in. Anstaken as 1 there would draw the band past the warm-up in the target’s own units, and throw a target in millionths far off.The refit of the first rows. One pass takes each row as the fit before it sees it, and without decay a row stays in the sums as it was taken, at full weight. The warm-up’s rows are least-squares rows, and so are the rows inside a band drawn around a fit that wild rows have pulled. So wild targets in the first rows keep pulling, where a batch fit reads them as outliers whose pull the band’s width bounds, and they leave only as the rows after them outweigh them. Over 50 streams of 8,000 rows with no decay, three targets 1e4 off at the start left the worst stream 0.22 from statsmodels’
QuantRegon the same rows, and wild targets on a fifth of the first 500 rows left it 0.038 off. So on the row a target’s count of learned rows reachesquantile_refit_rows, those rows are refit to the minimum of the smoothed check loss at the band the stream would draw:v_i = w_i * (the decay factors of the rows after i) r_i = y_i - z_i'b against the pass's fit s = weighted median of |r_i| at v_i, over 0.6745 h = s * max(quantile_eps, (k / n) ** 0.4) F(b) = sum_i v_i rho_h(r_i) + the ridge's penalty rho_h(r) = r**2 / (4h) + (tau - 1/2) r + h/4 if |r| < h = tau * r or (tau - 1) * r otherwiserho_his the check loss smoothed by the uniform kernel, the loss each row’s step is taken on. Each pass is a Newton step ofF: the rows inside the band are least-squares rows at targety + 2h (tau - 1/2), and each row outside addsw * 2h * psi(r) * z, with no cap. A step that would increaseFis halved until it does not, since the band’s rows measure the curvature at the pass’s fit and not at the next. A band of fewer rows than coefficients has no curvature to step on, and such a pass takes a majorizer’s step instead: it moves every prediction toward its row by at most the band’s width. The passes stop when the step moves no row’s fitz_i'bby more than 1e-10 ofs, beyond the rounding of a fit that size, or when no step along it lowersFpast its rounding, or after 200.The target’s sums are then rebuilt as the stream takes each row predicted by the converged fit at its band. Where that band holds fewer rows than coefficients, they are rebuilt as the majorizer’s step takes each row instead, every row a least-squares row at its weight, so the sums keep a weight and solve to that fit.
sis rebuilt from that fit’s residuals, and the stream goes on online. With the refit, the same streams ended at most 0.0053 and 0.0085 off, beside 0.0052 from a clean start. A shift of every one of the first rows is no outlier among them, so the refit keeps them, and they leave as before: a shift of 20 in the first 500 rows was 0.061 off at 8,000 rows, where it was 0.093. The refit runs after the row’s own prediction and moves its own target’s fit alone.The refit’s memory. A target’s rows are held until its refit, at
(features + 10) * 8bytes a learned row. Each row’s residual is kept beside it for the scale: a quantile fit’s band is drawn in the MAD, which is read exactly from the held residuals while the refit waits. A run of rows that only aged the target (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. A buffer whose rows, counted one each and decayed, are still fewer than the warm-up’s is left as the stream built it. The refit takes 0.09 to 2.3 ms once, for 1 to 50 features and 500 to 1,000 rows (an Apple M4 Pro under other load, best of 9), and the rows after it cost what they did. Underrefit_budget, each new group reserves(features + 26) * 8bytes a target of each model instance (a half-life grid reserves once per value) for each row of the count.