rheon.spec.lasso¶
- rheon.spec.lasso(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], features: list[str], penalties: list[float], l1_ratio: float | None = None, select_half_life: float | timedelta | str | _Expr | None = None, solve_every: float | timedelta | str | _Expr | None = None, max_rows_between_solves: int | None = None, window_size: float | timedelta | str | _Expr | None = None, closed: Literal['right', 'both'] = 'right', snapshot_every: float | timedelta | str | _Expr | None = None, max_rows_between_snapshots: int | None = None, window_budget: dict[Literal['thin', 'refuse'], float] | None = None, max_iter: int | None = None, tol: float | None = None, target_gaps: Literal['own_rows', 'pairwise'] = 'own_rows', **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
A lasso or elastic-net path on running sums, with the penalty chosen as the stream runs.
Use it for a sparse fit, where some features should get a coefficient of exactly zero: every penalty of the path is predicted, and
penalty_selected_<t>names the one with the lowest exponentially weighted out-of-sample squared error so far, at no extra solve. Useewridge()for a dense fit, andftrl()for a sparse logistic fit of a 0/1 target.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weight,groupand the diagnostics, are inrheon.spec. This model’s own:penaltiesThe penalties of the path, strictly decreasing, each finite and at least 0. Required, and not empty. Each penalty is a grid point, with a prediction of its own, reported as
pred_<t>__p<penalty>, such aspred_y__p0.1. A list of one value is no grid, and its fields take no suffix. The L1 part of a penalty is in the target’s units, and the ridge part has none (Units in Notes).l1_ratioThe share of the penalty that is L1, in
[0, 1]. Default 1, the lasso. Below 1 the fit is an elastic net.select_half_lifeThe half-life of the exponentially weighted squared out-of-sample error each grid point is ranked by, in clock units, above 0. Default: the model’s half-life, so the choice forgets at the pace the fit does.
infranks on the weighted mean of every error counted so far (inside the hard window under one).penalty_selected_<t>is reported as it stood before the row: the grid point the errors of the rows before it chose, not the one its own error then chose. Before the first row a target’s errors count on (The selection in Notes),penalty_selected_<t>is the last grid point, and a tie between grid points keeps the first inpenaltiesorder.solve_every,max_rows_between_solvesThe solve schedule, as for
ewridge(). A target’s first solve falls on the row it reaches a row of positive weight per coefficient,k + 1rows forkfeatures with an intercept andkwithout, whatevermin_weightsays, where the schedule has not solved it sooner.window_size,closedA hard window on the rows the path is fitted from, in clock units, as for
ewridge(): a rowwindow_sizeold or older is not in the running sums, andclosed="both"keeps the one exactly that old. The selection’s errors are cut at the hard window with the sums, so the penalty chosen is the one that fits the hard window, not rows the fit has dropped. So a hard window can change which coefficients are zero, not only their values: a feature with no evidence inside it goes to exactly zero.weight_sum,sigmaandzscoreare the hard window’s too.snapshot_every,max_rows_between_snapshots,window_budgetAs for
ewridge():snapshot_everyspaces the hard window’s snapshots on the clock, in clock units,max_rows_between_snapshotscaps the rows between them, whichever comes first, andwindow_budgetbounds each ring in MiB and thins or refuses past the bound. Each is refused withoutwindow_size.max_iter,tolWithin a solve, the descent stops after
max_itersweeps (default 100, at least 1), or after a sweep that moved no coefficientb_iof The update bytoltimes the larger ofs_yand the largest|c_i|, or moved none at all.toldefaults to1e-10, and is finite and above 0.s_yis the target’s spread over the rows the fit reads: its standard deviation, or its root mean square without an intercept, where the fit is not centered. A descent that runs out of sweeps first is counted inrheon.polars.ModelBank.solve_failures(), one per target and grid point, unless the rows behind its Gram are too few for the features to settle inmax_itersweeps on any data (The descent in Notes).target_gapsWhich rows a target’s feature correlations are taken over where the target is null on some:
"own_rows", the default, or"pairwise", as forewridge(). The cross-correlations are centered at the target’s own means either way.
Output
One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#lasso 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 morepenalties, one per grid point, suffixed aspred_<t>__p<penalty>.penalty_selected_<t>Per target, the penalty of the grid point in force before the row, such as
0.01: the one with the lowest exponentially weighted out-of-sample error.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 and grid point, the intercept (unless
fit_intercept=False) then one entry per feature (coef_index()).
plus the fields of the diagnostics switched on, as
rheon.specdescribes them.weight_sum,coefandpenalty_selected_<t>take no suffix for the grid point.rheon.polars.ModelBank.gram()returns the sums behind the path, as forewridge().Raises
As every builder does (
rheon.spec), andValueErrornaming the problem for:a
penaltiesthat is empty, not strictly decreasing, or holds a value below 0 or not finite;an
l1_ratiooutside[0, 1];a
select_half_lifenot above 0, and atolnot finite or not above 0;a
max_iterbelow 1, asolve_everybelow 0, and amax_rows_between_solvesormax_rows_between_snapshotsbelow 1;a
target_gapsother than"own_rows"or"pairwise";a
window_sizenot finite or not above 0; aclosedof"left"or"none"; asnapshot_everybelow 0 or not finite; awindow_budgetthat is not one key,"thin"or"refuse", or whose MiB is not above 0; andclosed="both",snapshot_every,max_rows_between_snapshotsorwindow_budgetwithoutwindow_size;emit_error_inflation,emit_influence,emit_se_coeforemit_robust_se, which need a leverage, a covariance or a least-squares fit that the lasso’s chosen coefficients do not have.
The update
The running sums are
ewridge()’s. On the schedule, for each penaltylinpenalties, the model solves by coordinate descent on the standardized, centered sums (without an intercept, on the raw moments, each feature scaled by its root mean square, and no intercept is recovered).Cis the features’ correlation matrix,s_ifeaturei’s standard deviation,c_i = cov(x_i, y) / s_iits covariance with the target over its standard deviation, andb_i = beta_i * s_iits coefficient in standardized units. Each sweep sets, for everyi:rho_i = c_i - sum_{j != i} C_ij b_j b_i = soft(rho_i, l * l1_ratio) / (C_ii + l * (1 - l1_ratio)) soft(v, t) = sign(v) * max(|v| - t, 0)then the coefficients are unscaled,
beta_i = b_i / s_i, with the intercept recovered asybar - m . beta,ybarthe target’s mean andmthe features’. The descent starts the first grid point from the last solve’s fit, and each later grid point from the one before it.Example
This code fits a target on four features, of which only
x0andx1play a part, and prints the slopes at each penalty:import numpy as np rng = np.random.default_rng(6) x = rng.standard_normal((5_000, 4)) y = 2.0 * x[:, 0] - 1.0 * x[:, 1] + rng.standard_normal(5_000) frame = pl.DataFrame({f"x{i}": x[:, i] for i in range(4)} | {"y": y}) frame.write_parquet("sparse.parquet") las = rp.spec.lasso( "las", targets=["y"], features=["x0", "x1", "x2", "x3"], half_life=float("inf"), penalties=[0.1, 0.01], # decreasing; every point is predicted ) bank = rp.ModelBank([las]) bank.fit(pl.scan_parquet("sparse.parquet")) # learn every row, keep no output print("planted: x0 2, x1 -1, x2 0, x3 0") slopes = bank.coef().filter(pl.col("term") != "intercept") wide = slopes.pivot(on="term", index="penalty", values="coef") for r in wide.iter_rows(named=True): found = ", ".join(f"{t} {r[t]:.2f}" for t in ["x0", "x1", "x2", "x3"]) print(f"penalty {r['penalty']:g}: {found}")
planted: x0 2, x1 -1, x2 0, x3 0 penalty 0.1: x0 1.87, x1 -0.90, x2 0.00, x3 0.00 penalty 0.01: x0 1.96, x1 -0.99, x2 -0.01, x3 -0.00
See also
ewridge(), the running sums this model solves, under a ridge.rheon.gram.lasso_path(), the same descent run offline on a Gram.ftrl(), a sparse fit of a 0/1 target.
Notes
Units. The target is centered but not scaled, so the threshold
l * l1_ratiois in the target’s units, while the ridge partl * (1 - l1_ratio)is added to a correlation and has none. So for a pure lasso,yandlscaled by 10 scale the predictions by 10 and zero the same coefficients. For an elastic net they do not. The standardized coefficients are in the target’s units, so the stopping rule has none: for a pure lasso,yandpenaltiesscaled by a power of two give the same fit scaled, to the bit, stopped on the same sweeps.The selection. A row of weight 0 adds no error: the errors keep their values and only their weight decays, so without a hard window the choice does not move, and under one it moves only as the hard window drops rows. A target’s errors count once the fit holds a row of it per coefficient:
k + 1rows of positive weight with an intercept,kwithout, inside the hard window under one. They count whatevermin_weightsays, which withholds the output alone: the selection scores the prediction on a row the gate withholds, so the penalty chosen, as the fit, is the same at anymin_weight, and one target’s choice does not depend on another’s threshold.The descent.
rheon.gram.lasso_path()runs the same descent with ten times the sweeps by default, 1,000, because it starts its path from zero. A solve here starts its first grid point from the last solve’s fit, which the rows since then have moved only a little once the moments stop moving much, and each later point from the one before it. On 15 features correlated at0.8 ** |i - j|, solved on every row of 20,000 at seven penalties, 798 of the 140,000 descents ran out of their 100 sweeps; 1,000 sweeps left 44, at 1% more sweeps in all. A cyclic descent contracts the error along two columns of correlationrhobyrho**2a sweep. That is about1 - 4 / kappa, withkappa = (1 + rho) / (1 - rho)their correlation matrix’s condition number, so each e-fold takes aboutkappa / 4sweeps. Where columns nearly repeat each other most descents can run out: on 800 rows of two columns 0.1 apart (kappanear 400) at a penalty of 0.001, 798 of 799.A descent that runs out of sweeps while the rows are too few for the features is the fit’s warm-up, and is not counted. A sweep shrinks the error by about
1 - 2 * lmin,lminthe smallest eigenvalue of the correlation matrix (with the penalty’s ridge share added to its diagonal), so settling totoltakes aboutln(1/tol) / (2 * lmin)sweeps.nindependent rows ofkfeatures give at bestlmin = (1 - sqrt(k / dof)) ** 2, withdofthe Kish sizenless one for an intercept, and correlated features only less. Where that best case would not settle inmax_itersweeps, about 2.3 rows a feature at 100 sweeps and 1.25 at 1,000, the cap hit comes from the rows and says nothing about the data, so it is not counted; the fit is still where the descent stopped. Past it every cap hit is counted, as is every one under a decay whose Kish size stays below that bound (about(1 + lam) / (1 - lam)rows forlamthe decay a row), or under awindow_sizewhose window holds fewer rows than that bound once rows have aged out of it: no more rows would lift it, so the stream is never out of its warm-up. Amax_iterbelowln(1/tol) / 2, about 12 sweeps, is counted always, since no number of rows would settle it.