polars_online.spec.lasso

polars_online.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. Use ewridge() for a dense fit, and ftrl() 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, group and the diagnostics, are in polars_online.spec. This model’s own:

penalties

The 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 as pred_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_ratio

The share of the penalty that is L1, in [0, 1]. Default 1, the lasso. Below 1 the fit is an elastic net.

select_half_life

The 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. inf ranks 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 in penalties order.

solve_every, max_rows_between_solves

The solve schedule, as for ewridge(). A target’s first solve falls on the row it reaches a row of positive weight per coefficient, k + 1 rows for k features with an intercept and k without, whatever min_weight says, where the schedule has not solved it sooner.

window_size, closed

A hard window on the rows the path is fitted from, in clock units, as for ewridge(): a row window_size old or older is not in the running sums, and closed="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, sigma and zscore are the hard window’s too.

snapshot_every, max_rows_between_snapshots, window_budget

As for ewridge(): snapshot_every spaces the hard window’s snapshots on the clock, in clock units, max_rows_between_snapshots caps the rows between them, whichever comes first, and window_budget bounds each ring in MiB and thins or refuses past the bound. Each is refused without window_size.

max_iter, tol

Within a solve, the descent stops after max_iter sweeps (default 100, at least 1), or after a sweep that moved no coefficient b_i of The update by tol times the larger of s_y and the largest |c_i|, or moved none at all. tol defaults to 1e-10, and is finite and above 0. s_y is 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 in polars_online.ModelBank.solve_failures(), one per target and grid point, unless the rows behind its Gram are too few for the features to settle in max_iter sweeps on any data (The descent in Notes).

target_gaps

Which rows a target’s feature correlations are taken over where the target is null on some: "own_rows", the default, or "pairwise", as for ewridge(). 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 - pred where the target is not null. Under two or more penalties, one per grid point, suffixed as pred_<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_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.

coef

Per 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 polars_online.spec describes them. weight_sum, coef and penalty_selected_<t> take no suffix for the grid point. polars_online.ModelBank.gram() returns the sums behind the path, as for ewridge().

Raises

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

  • a penalties that is empty, not strictly decreasing, or holds a value below 0 or not finite;

  • an l1_ratio outside [0, 1];

  • a select_half_life not above 0, and a tol not finite or not above 0;

  • a max_iter below 1, a solve_every below 0, and a max_rows_between_solves or max_rows_between_snapshots below 1;

  • a target_gaps other than "own_rows" or "pairwise";

  • a window_size not finite or not above 0; a closed of "left" or "none"; a snapshot_every below 0 or not finite; a window_budget that is not one key, "thin" or "refuse", or whose MiB is not above 0; and closed="both", snapshot_every, max_rows_between_snapshots or window_budget without window_size;

  • emit_error_inflation, emit_influence, emit_se_coef or emit_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 penalty l in penalties, 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). C is the features’ correlation matrix, s_i feature i’s standard deviation, c_i = cov(x_i, y) / s_i its covariance with the target over its standard deviation, and b_i = beta_i * s_i its coefficient in standardized units. Each sweep sets, for every i:

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 as ybar - m . beta, ybar the target’s mean and m the 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 x0 and x1 play 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 = po.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 = po.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

Notes

Units. The target is centered but not scaled, so the threshold l * l1_ratio is in the target’s units, while the ridge part l * (1 - l1_ratio) is added to a correlation and has none. So for a pure lasso, y and l scaled 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, y and penalties scaled 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 + 1 rows of positive weight with an intercept, k without, inside the hard window under one. They count whatever min_weight says, 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 any min_weight, and one target’s choice does not depend on another’s threshold.

The descent. polars_online.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 at 0.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 correlation rho by rho**2 a sweep. That is about 1 - 4 / kappa, with kappa = (1 + rho) / (1 - rho) their correlation matrix’s condition number, so each e-fold takes about kappa / 4 sweeps. Where columns nearly repeat each other most descents can run out: on 800 rows of two columns 0.1 apart (kappa near 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, lmin the smallest eigenvalue of the correlation matrix (with the penalty’s ridge share added to its diagonal), so settling to tol takes about ln(1/tol) / (2 * lmin) sweeps. n independent rows of k features give at best lmin = (1 - sqrt(k / dof)) ** 2, with dof the Kish size n less one for an intercept, and correlated features only less. Where that best case would not settle in max_iter sweeps, 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 for lam the decay a row): no more rows would lift it, so the stream is never out of its warm-up. A max_iter below ln(1/tol) / 2, about 12 sweeps, is counted always, since no number of rows would settle it.