polars_online.gram.subset

polars_online.gram.subset(g: Gram, columns: Sequence[str | int]) → Gram[source]

Keep some of a Gram’s columns, in the order given.

Use it to fit or diagnose a narrower design from a Gram that holds more columns: forward stepwise selection, an information criterion over feature sets, or an r-column fit read off a k-column stream, all from one pass. To narrow one fit, solve(), lasso_path(), lars_path() and coef_stats() take features instead.

Parameters

g

The Gram, as gram() returns it.

columns

The columns to keep, by name or by position, as the Gram’s own columns key names them. A negative position counts from the end. The intercept may be kept like any other column. Leave the intercept out, and every fit on the subset goes through the origin, as a spec with fit_intercept=False does: solve() and the paths then read the raw moments, E[z z'] and E[z y], and center nothing. Keep it for a fit with an intercept. The keyword’s older name, cols, is still read, with a PolarsOnlineDeprecationWarning.

Returns

A Gram of the columns kept: its columns, means, comoments, cross_moments, means_by_target, cross_centered and lag_comoments narrowed to them, its comoments in float64, packed if g’s is. The targets are untouched, since they index a different axis.

Raises

KeyError

A name the Gram does not have.

IndexError

A position outside the Gram’s columns.

TypeError

columns and its older name cols are given together.

ValueError

A column named twice, by name or by position, since two copies of one column make the subset’s matrix singular.

Examples

This code reads df from 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]
narrow = po.gram.subset(g, ["intercept", "x0"])     # the fit on x0 alone
print(narrow["columns"], po.gram.solve(narrow).round(2))
['intercept', 'x0'] [1.03 1.81]

See also

  • solve(), whose features narrows one fit without a new Gram.

  • Every least-squares fit is a function of the Gram in docs/GRAM.md, the theory and a recipe that runs.

Notes

The subset is exact. The moments of some of the columns are a sub-block of the moments of all of them, so this selects that block, and a regression on the subset is the regression the whole Gram implies for those columns.