polars_online.gram.lars_path¶
- polars_online.gram.lars_path(g: Gram, *, target: str | int = 0, features: Sequence[str | int] | None = None, max_iter: int | None = None, max_active: int | None = None, penalty_weights: Sequence[float] | None = None, threads: int | None = None) dict[str, Any][source]¶
Compute the lasso path from its start, knot by knot, by least angle regression.
Use it to find which columns the lasso chooses first, and the exact penalties at which each enters or leaves, without choosing a grid of penalties. For a grid of penalties, a penalty weight of 0 or an elastic net, use
lasso_path(). For many Grams or targets in one call, uselars_paths().Parameters
gThe Gram, as
gram()returns it.target,featuresAs for
solve().max_iterStop after this many knots past the path’s first, each knot one penalty however many columns change at it. Default
None, no limit. Refused unless a whole number of at least 1. The keyword’s older name,max_steps, is still read, with aPolarsOnlineDeprecationWarning.max_activeStop at the first knot with this many columns active or more (more than
max_activewhere columns tie there). DefaultNone, no limit. Refused unless a whole number of at least 1. With neither limit, the path runs tol = 0. A selection reads only the start of a path, and each step costsO(k |A|)operations (Notes), so stop it early.penalty_weightsA scale
w_jon the penalty per feature, as forlasso_path(), but each finite and above 0. A weight of 0 would keep a column in the fit at every penalty, and a path that starts atl_max, where every coefficient is 0, cannot hold such a column. Uselasso_path()for that, and for an elastic net, whose path is not piecewise linear. DefaultNone, every weight 1. Refused at the wrong length.threadsHow many threads the path runs on, as
ModelBanktakes it:None, the default, is the process’s threads, and an integer that many threads. One path is one thread’s work, so it matters only tolars_paths(). The numbers are the same at any count. Refused unless an integer of at least 1, orNone.
Returns
A dict:
penaltiesThe penalty
lat each knot, falling, in the units oflasso_path()and of thelassomodel.coefShape
(n_knots, k): each knot’s coefficients over the Gram’skcolumns, in the features’ original units with the intercept recovered, as a row oflasso_path()gives them (the interceptnanon a Gram pooled within parts).activeThe active set below each knot, by name, in the order its columns entered, those entering at one knot in
featuresorder. A column entering at a knot is in that knot’s set with its coefficient still 0, and grows from there. A column leaving at a knot is out of its set. So the first knot’s set holds the first columns to enter, one unless several tie, and a knot’s nonzero coefficients are the set before it, less any column leaving at it. A tie that turns a slope back as it reaches 0 is the one case apart: that column stays in the set at 0.stopWhy the path stopped:
"max_iter","max_active", or"end", wherelreached 0 or no column can enter.
Raises
WrongTypeErrorA limit that is not a whole number or
None. It is both aTypeErrorand aValueError.ValueErrorA limit below 1;
penalty_weightsof the wrong length, or not finite and above 0;threadsbelow 1; the intercept or a column named twice amongfeatures, as forsolve().TypeErrorthreadsthat is not an integer orNone, such as a bool or a float; ormax_iterand its older namemax_stepsgiven together.KeyError,IndexErrorAs for
solve().
Examples
This code reads
dffrom Example data:spec = po.spec.ewridge( "ridge", targets=["y"], features=["x0", "x1", "x2"], half_life=100.0 ) bank = po.ModelBank([spec]) bank.fit_predict(df) g = bank.gram("ridge")[0] path = po.gram.lars_path(g, target="y") for l, active in zip(path["penalties"], path["active"]): print(f"{l:.3f}", active) # a knot's penalty, and the columns active below it print(path["stop"])
1.766 ['x0'] 0.848 ['x0', 'x1'] 0.016 ['x0', 'x1', 'x2'] 0.000 ['x0', 'x1', 'x2'] end
See also
lars_paths(), the same for many Grams and targets at once.lasso_path(), the lasso at penalties you choose.Choosing columns on the lasso path in docs/GRAM.md, the theory, and Choose columns on the lasso path, a recipe that runs.
Notes
The path is Efron, Hastie, Johnstone and Tibshirani’s LARS (2004) with their lasso modification, on the correlation form
lasso_path()standardizes the Gram to.Ris the features’ correlation matrix anddtheir standardized cross-moments with the target, centered at the target’s own means where there is an intercept. The lasso minimizesf(b) = 0.5 * b' R b - d' b + l * sum_j w_j * |b_j|
and its solution is piecewise linear in the penalty
l. The path starts atl_max = max_j |d_j| / w_j, where every slope is 0. Each knot is where a column enters the active setA, or leaves it as its slope crosses 0. Between knots, each active column’s correlation with the residual,c_j = d_j - (R b)_j, stays atl * w_jin size:delta_A = inv(R_AA) (w_A * s_A) s_j = sign(c_j) b_A += gamma * delta_A l -= gamma
The step
gammais the first at which a column outsideAreaches the active correlation, an active slope reaches 0, orlreaches 0. Atl = 0the fit is least squares onA.A knot’s coefficients are the lasso’s exactly at its penalty, so
lasso_path(g, [l])at a knot’slgives the same row where its descent has converged. That descent’stolbounds a sweep’s largest move, not the distance from the solution: at a condition number of 1e8 a descent attol=1e-14stopped 0.48 from a knot in the intercept, at an objective above the knot’s.Columns that tie change at one knot. Where several columns reach the active correlation at once, as two with equal
|d_j|do on an orthogonal design, they are decided together at that one knot. A tie is read to within rounding: steps within64 * eps * l_maxof the smallest are one knot, sincelis computed to about that. The lasso decides which tied columns enter. A tied column stays out when the direction that includes it would move its slope against its sign, and it can enter further down the path. scikit-learn 1.9.1’slars_path_gramtakes tied columns one at a time and ends off least squares: on an identity Gram withd = [1, 1], at[2, 1], where least squares is[1, 1].Some columns never enter. A column that is constant on the Gram’s rows never enters. A column that would enter collinear with the active set is set aside, since it adds no direction: its pivot in the factor of
R_AAis below1e-12of its variance. It takes no step and makes no knot, so each knot but the last atl = 0is one column or more entering or leaving.A path is fast. A step takes
O(k |A|)operations. Measured on an M4 Pro, the path’s own arithmetic takes 9 microseconds whole at 15 columns, and the call from Python 0.04 ms. At 200 columns, 40 knots take 0.2 ms, and at 2,000 columns 3 ms.