rheon.spec.expectile¶
- rheon.spec.expectile(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], features: list[str], expectile: float, ridge: float | None = None, refit_rows: int | None = None, refit_span: float | timedelta | str | _Expr | None = None, window_rows: int | None = None, window_size: float | timedelta | str | _Expr | None = None, closed: Literal['right', 'both'] = 'right', max_state_bytes: int | None = None, refit_budget: float | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Expectile regression, fitted one row at a time by reweighted least squares.
Use it for a tail of the target that should weigh how far the rows past it lie, not only how many there are: the 0.9 expectile of a loss, a latency or a demand. Rows above the fit weigh
tauin its squared error and rows at or below it1 - tau, soexpectile=0.5is the least-squares fit and a level near 1 an upper envelope that every large row pulls up. Usequantile()for the level a share of the rows fall below, which no single row can move far, andewridge()for the mean with its diagnostics.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weight,groupand the diagnostics, are inrheon.spec. A row’sweightscales its squared error, as a weighted least-squares fit’s weights do. A row of weight 0 counts in no clock: the next row decays as if it were not there, it is in no window and in noweight_sum; it is still predicted.This model’s own parameters:
expectileThe level
tau, above 0 and below 1; required. Several levels are several specs: each level weighs every row by its own sides, so they share no sums, and a spec per level costs what one spec of several would.ridgeThe penalty
ridge * W * |slopes|²beside the loss,Wthe target’s weight: a ridge on the mean-form Gram, in the features’ squared units, asquantile()’s. Default1e-6, which keeps every solve defined from the first row, a constant or duplicated feature included;0is the exact fit, which waits for a row per coefficient. Finite and at least 0.refit_rowsThe learned rows (each of positive weight, with its target) after which each target’s first rows are fitted exactly, once, and the running sums rebuilt with each row on the side the exact fit puts it (One pass and the refit in Notes). Default
max(200, 10 * k),kthe coefficients, up to 100 features, held to whatmax_state_bytesholds beside the sums, and off above 100 features, under a window, or where fewer than2 * krows fit.0turns the refit off. A group’s buffers hold8 * targets * refit_rows * (features + 2)bytes until the refit runs: a count pastmax_state_bytesis refused, naming the bytes.refit_spanThe same refit over a span of the clock in place of a count of rows: each target’s rows from its first learned row through the first row at least
refit_spanafter it, once they hold a row per coefficient. A number of the clock’s units, or of rows where the spec has no clock, or a duration such as"1h"on a temporal clock; finite and above 0. The span is read off the rows’ exact stamps (integer nanoseconds on a temporal clock), and a row of weight 0 is no row of it, so on a clock of one unit a row it holdsrefit_span + 1rows: the refit ofrefit_rows = refit_span + 1, to the bit. How many rows that is the data decides, so they are checked againstmax_state_bytesas they come, as awindow_sizewindow’s are. Refused besiderefit_rowsand beside a window. Default none.window_rowsFit only the last this many rows of positive weight, refit exactly on every row, in place of a decay: set
half_lifetoinfbeside it. At least one row per coefficient. Each row of the window takes8 * (features + targets + 1) + targetsbytes, checked againstmax_state_byteswhen the spec is built. Default none.window_sizeFit only the rows of the last this long on the clock, in clock units, refit exactly on every row, in place of a decay: set
half_lifetoinfbeside it. A number of the clock’s units, or of rows where the spec has no clock, or a duration such as"5m"on a temporal clock; finite and above 0. A row leaves the window when it iswindow_sizeold on the clock (decayed aftergap_cap), before the row that reaches that age is predicted, decided on the rows’ exact stamps (integer nanoseconds on a temporal clock). How many rows that is, the data decides, so its bytes are checked as the rows go in (seemax_state_bytes). Refused besidewindow_rows. Default none.closedWhich edge of
window_sizeholds the row exactly that old, in Polars’ words (rolling_sum_by(closed=))."right", the default, keeps the rows less thanwindow_sizeold;"both"keeps that row too and is refused withoutwindow_size.max_state_bytesThe bytes a group’s state may hold: the sums, a refit buffer and a window’s rows. A refit buffer and
window_rowsfix their size, so a spec past the cap is refused when it is built. Awindow_sizewindow holds the rows the span has, so it is checked as the rows go in: the first row to take a group past half of the cap raises a warning, once for the group, naming the group and the bytes, and the row that would take it past the cap stops the run with an error naming the group and the bytes, the bank having learned part of the chunk. Each row of such a window takes a stamp of 32 bytes beside its numbers. Default 256 KB,262144; at most 64 MiB,67108864.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. The group that would cross the bound, and every new group after it, gives its refit up and keeps its one-pass fit, whichbank.summary()’srefit_given_upcounts.
Output
One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#expectile gives each field’s type and when it is null:
pred_<t>,resid_<t>Per target: the fitted expectile at the row’s features, from the rows before it, and
yless it where the target is not null. Null before the target’s first fit, which needs a row per coefficient.weight_sumThe weight the model has accumulated before the row and before the row’s own decay; under a window, the weight of the rows in it.
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()); null before the first fit.
plus the fields of the diagnostics switched on, as
rheon.specdescribes them.Raises
As every builder does (
rheon.spec), andValueErrornaming the problem for:an
expectilenot above 0 and below 1, and aridgebelow 0 or not finite;a
window_rowsunder one row per coefficient, awindow_sizenot finite and above 0, the two together,closed="both"withoutwindow_size, and a window beside a finitehalf_life, arefit_rowsabove 0 or arefit_span;a
refit_spannot finite and above 0, and one besiderefit_rows;a
max_state_bytesof 0 or above 64 MiB, and a refit buffer or awindow_rowswindow that would hold more than it;a
refit_budgetnot above 0;a
window_sizewindow or arefit_spanrefit that passesmax_state_bytes, as the rows go in.
The update
Per row and target,
x̃is[1, x](xwithout an intercept),wthe row’s weight andλ = 0.5 ** (Δ / half_life)the decay over the clockΔsince the last row that counted:pred = x̃'β the prediction, before the update a = tau if y > pred else 1 - tau (1/2 before the first fit) S = λ S + w a G = G + (w a / S) (x̃x̃' - G) c = c + (w a / S) (x̃ y - c) W = λ W + w β = (G + ridge (W / S) D)⁻¹ c
Gandcare per target, since each target’s rows fall on their own sides;Dis the slopes’ diagonal, the intercept unpenalized. Under a window, and at the refit,βis instead the exact minimiser ofΣ v a(r) r² + ridge V |slopes|²over the rows held,vtheir weights andVtheir sum: each pass solves the weighted least squares at the current sides and judges every side again, until no side changes.Example
This code fits the 0.9 expectile of a target whose noise is skewed, and prints the coefficients this model finds. statsmodels’ batch fit of the same rows,
RLMwithMQuantileNorm(0.9, LeastSquares()), gives the same to two decimals:import numpy as np rng = np.random.default_rng(7) x = rng.standard_normal(20_000) y = 1.0 + 0.5 * x + rng.exponential(1.0, 20_000) pl.DataFrame({"x": x, "y": y}).write_parquet("skewed.parquet") fit = rp.spec.expectile( "upper", targets=["y"], features=["x"], expectile=0.9, half_life=float("inf") ) bank = rp.ModelBank([fit]) bank.fit(pl.scan_parquet("skewed.parquet")) # learn every row, keep no output coef = {r["term"]: r["coef"] for r in bank.coef().iter_rows(named=True)} print(f"intercept {coef['intercept']:.2f}, x {coef['x']:.2f}")
intercept 3.03, x 0.51
See also
quantile(), the level a share of the rows fall below.ewridge(), the least-squares fit, whichexpectile=0.5is.huber(), a mean that outliers cannot pull.
Notes
The loss. The expectile at
tauminimisesΣ v a(r) r²witha(r) = tauabove the fit and1 - tauat or below it. The loss is convex and its curvature lies betweenmin(tau, 1 - tau)andmax(tau, 1 - tau)times least squares’ everywhere, so each step is a weighted least-squares solve, with no band and no residual scale to choose. Its fit is statsmodels’RLMwithMQuantileNorm(tau, LeastSquares()), and at one level of the target alone it isscipy.stats.expectile.One pass and the refit. A row’s side is judged by its residual against the fit before it, and the row’s own update cannot move that residual across zero, so one solve a row is the whole step. What one pass cannot do is judge an earlier row again once the fit has crossed it. At
tau = 0.5it is the decayed least-squares fit to rounding; elsewhere the gap of its fitted values to the exact decayed fit, measured over 10 seeds with decay, was 0.02 to 0.4 times the batch fit’s own sampling error on average and 1.2 times it at worst (500 rows,tau = 0.9). Without decay the rows judged early stay at full weight, and the refit of the firstrefit_rowsrows cut the gap at 500 rows fivefold.The state is
k(k+1)/2 + 2k + 4numbers a target,kthe coefficients, and the shared weight and clock: 0.4 KB at 5 features. A row takes O(k²) time and a solve of O(k³). Until each target’s refit runs,refit_rows (features + 2)more. A window holds its rows instead of the sums, and refits them on every row: aboutpasses * rows * k²work a row, the passes 1 to 2 on average warm-started at the fit before and at most 10 on awkward data.The spans.
half_life,gap_cap,window_sizeandrefit_spantake a number (rows, with no clock) or a clock duration, as every spec’s do.window_rowsandrefit_rowscount rows of positive weight.