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, use lasso_path() or lars_path(). To fit many merged subsets of Grams at once, use solve_subsets().

Parameters

g

The Gram, as gram() returns it, or as merge(), subset() or from_row() return one.

ridge

The penalty, added to the co-moments, which are weighted means. It is a spec’s ridge under its default ridge_scale="mean", in the features’ squared units unless standardize. A sequence gives one row of coefficients per value. Default 0, least squares. Refused unless finite and at least 0, as a spec’s ridge is.

target

The target, by name or by position among the Gram’s targets. Default 0, the first.

features

The 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. Default None, every column. The intercept is refused here, since the solve handles it itself, and so is a column named twice.

standardize

True scales the system to correlation form, adds ridge there and scales back, so ridge means 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 the standardize the spec used, or the numbers will not match its coef(). Default False.

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 is nan: each part had an intercept of its own, and the pooled Gram holds none of them.

Raises

KeyError

A target or column name the Gram does not have, or a target named for a Gram with no targets.

IndexError

A target or column position outside the Gram’s, or any target position, the default 0 included, on a Gram with no targets.

ValueError

The 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); a ridge that is not finite and at least 0.

Examples

This code reads df from 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

Notes

The arithmetic is the model’s own: the ewridge model’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, and coef_prior, a prior centered on values other than 0.

With an intercept among the columns, it is eliminated, and the slopes b solve the centered system:

(C + ridge * I) b = c
b_0 = ybar - m . b

C is the features’ centered comoments. c = cross_centered[t] is target t’s cross-moments centered at its own column means m (means_by_target) and its mean ybar, 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 what target_gaps="pairwise" solves where it was not. A mapping without cross_centered forms cross_moments[t] - m * ybar instead, which at a level L carries a rounding error of about L**2 * eps, with eps the 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 standardize or on columns of like scale. With V d V' in hand, every ridge r is V 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-10 to 1e10 are solved as well as columns of unit scale. numpy.linalg.eigh is 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 of C + ridge * I spreads 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 from 1e-3 to 1e3 in 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).