polars_online.gram.solve¶
- polars_online.gram.solve(g: Gram, *, ridge: float | Sequence[float] = 0.0, target: str | int = 0, features: Sequence[str | int] | None = None, standardize: bool = False) Any[source]¶
Compute ridge coefficients from a Gram, in the features’ original units.
Use it to fit a ridge, or least squares at
ridge=0, on a Gram after the pass: the spec’s own fit, a grid of penalties, or a fit on some of its columns. For the lasso or the elastic net, uselasso_path()orlars_path(). To fit many merged subsets of Grams at once, usesolve_subsets().Parameters
gThe Gram, as
gram()returns it, or asmerge(),subset()orfrom_row()return one.ridgeThe penalty, added to the co-moments, which are weighted means. It is a spec’s
ridgeunder its defaultridge_scale="mean", in the features’ squared units unlessstandardize. A sequence gives one row of coefficients per value. Default 0, least squares. Refused unless finite and at least 0, as a spec’sridgeis.targetThe target, by name or by position among the Gram’s
targets. Default 0, the first.featuresThe columns to fit on, by name or position: the fit on a
subset()of these columns and the intercept, returned over all the Gram’s columns with 0 for each column left out. DefaultNone, every column. The intercept is refused here, since the solve handles it itself, and so is a column named twice.standardizeTruescales the system to correlation form, addsridgethere and scales back, soridgemeans the same thing whatever the features’ units. A column with no variance (no raw second moment, without an intercept) is then dropped with a coefficient of 0, where it would make the system singular. Pass thestandardizethe spec used, or the numbers will not match itscoef(). DefaultFalse.
Returns
A float array over the Gram’s columns, the intercept first when there is one, in
polars_online.spec.coef_index()order. With a sequence of ridges, a 2-d array, one row per value. On a Gram pooled within parts (merge(within=True)) the slopes are the within estimator’s and the intercept isnan: each part had an intercept of its own, and the pooled Gram holds none of them.Raises
KeyErrorA target or column name the Gram does not have, or a target named for a Gram with no targets.
IndexErrorA target or column position outside the Gram’s, or any target position, the default
0included, on a Gram with no targets.ValueErrorThe intercept among
features, or a column named twice in them (one column solved twice is a singular system, and only one of its two coefficients could be reported); aridgethat is not finite and at least 0.
Examples
This code reads
dffrom Example data:spec = po.spec.ewridge( "ridge", targets=["y"], features=["x0", "x1"], half_life=100.0, ridge=0.1, standardize=True, ) bank = po.ModelBank([spec]) bank.fit_predict(df) g = bank.gram("ridge")[0] coef = po.gram.solve(g, target="y", ridge=0.1, standardize=True) # the spec's own fit grid = po.gram.solve(g, target="y", ridge=[1e-6, 0.01, 0.1, 1.0]) # one row per ridge print(coef.round(3), grid.shape)
[ 0.986 1.773 -0.884] (4, 3)
See also
coef_stats(), the standard errors andtof the fit.lasso_path()andlars_path(), the lasso’s fits.A ridge and its t in docs/GRAM.md, the theory, and Fit a ridge from a Gram, a recipe that runs.
Notes
The arithmetic is the model’s own: the
ewridgemodel’s solve, so the result is the fit that spec would report on the same Gram. Two penalties are not taken here, and a spec with either reports a fit this does not reproduce:ridge_scale="sum", a decaying prior on the sum scale that reaches the intercept, andcoef_prior, a prior centered on values other than 0.With an intercept among the columns, it is eliminated, and the slopes
bsolve the centered system:(C + ridge * I) b = c b_0 = ybar - m . b
Cis the features’ centeredcomoments.c = cross_centered[t]is targett’s cross-moments centered at its own column meansm(means_by_target) and its meanybar, as the model holds them. That is the raw normal equations with the intercept unpenalized, exactly, where the target was present on every row the Gram holds, and it is whattarget_gaps="pairwise"solves where it was not. A mapping withoutcross_centeredformscross_moments[t] - m * ybarinstead, which at a levelLcarries a rounding error of aboutL**2 * eps, withepsthe float64 rounding unit. Without an intercept nothing is centered:(E[z z'] + ridge * I) b = E[z y], and every column is penalized.A grid of ridges shares one eigendecomposition where the system’s diagonal is even, under
standardizeor on columns of like scale. WithV d V'in hand, every ridgerisV diag(1/(d + r)) V' c, so a grid of fifty takes one factorization and fifty matrix products.The solve is accurate to the condition of the system with each column scaled by the root of its diagonal, as the model’s Cholesky is. So the features’ units do not enter: columns from
1e-10to1e10are solved as well as columns of unit scale.numpy.linalg.eighis accurate only relative to the largest eigenvalue, so the system is scaled that way before it is decomposed, and the answer scaled back. A uniform ridge is not uniform once the columns are scaled. So where the diagonal ofC + ridge * Ispreads by more than a factor of 4, largest over smallest, each ridge takes a solve of its own: an LU solve of the scaled system for a ridge above 0, its eigendecomposition at 0. On columns from1e-3to1e3in scale, a grid of fifty ridges took 1.4 ms at 50 columns and 8.4 ms at 200, three times the single decomposition’s time (measured on an Apple M4 Pro under load).