polars_online.gram.solve_subsets¶
- polars_online.gram.solve_subsets(grams: Sequence[Gram], subsets: Sequence[Sequence[int]], *, targets: Sequence[str | int] | None = None, features: Sequence[str | int] | None = None, ridge: float | Sequence[float] = 0.0, standardize: bool = False, path: dict[str, Any] | None = None, within: bool = False, target_signs: Any = None, threads: int | None = None, jobs: Sequence[Mapping[str, Any]] | pl.DataFrame | None = None) list[Any][source]¶
Merge each subset of the Grams and fit it, for many subsets at once.
Use it for many fits over pooled Grams in one call, such as each block’s own fit (the spread of a coefficient’s
tacross the blocks says how stable it is), the halves of a stability selection (each a merge of about half the blocks), and their null runs under random signs. For one merge and one fit, usemerge()and thensolve(),coef_stats()orlars_path(). To walk paths on Grams without merging them, uselars_paths().Parameters
gramsThe Grams, each as
gram()returns it, all with the samecolumnsandtargets, and each withmeans_by_targetandcross_centered.subsetsOne list of positions in
gramsper fit, each naming a Gram at most once, since a Gram twice in one merge counts its rows twice.[[0], [1], ...]fits each Gram alone. A subset’s parts are pooled asmerge()pools them.targetsThe targets to fit, by name or position. Default
None, every target. Refused besidejobs, whose jobs name their own.featuresAs for
solve().ridge,standardizeAs for
solve(). A sequence of ridges fits each value, and givescoef,seandtone row per value andresid_var,sigma2andr2one entry per value, withnonce. Not read underpath, since a path is in correlation form.pathNone, the default, for a ridge fit with its statistics, assolve()and thencoef_stats()give them. Or a dict oflars_path()’smax_iter,max_activeandpenalty_weights({}for none of them) for each target’s lasso path instead. The key’s older name,max_steps, is read asmax_iter, with aPolarsOnlineDeprecationWarning. Any other key is refused.withinTruepools each subset within its parts, asmerge()withwithin=True: each fit’s intercept isnan, and a ridge fit’s degrees of freedom lose one per part. DefaultFalse, the union.target_signsNone, the default, or an array of shape(len(grams), draws), each entry +1 or -1, only withwithin=True. Columndis a draw: a signs_ifor each Gram, which multiplies its targets’ centered cross-moments before each subset is pooled,c = sum T_i s_i c_i / T. That is what negating Grami’s target rows gives, since its co-moments, its target weights and its target variances do not move, so a draw needs no second merge of the co-moments. Every subset is fitted once per draw, so a draw of random signs is a null run of a selection: what it chooses where no column’s effect keeps its sign across the Grams. Under a union a negated Gram’s target mean moves the gaps between the parts’ means too, and the shortcut does not hold, so it is refused there.threadsHow many threads the subsets are fitted on, beside each other:
None, the default, is the process’s threads, and an integer that many threads, asModelBanktakes it. Each fit is one thread’s arithmetic, so the numbers are the same at any count. Refused unless an integer of at least 1, orNone.jobsNone, the default, fits every subset, draw and target onfeatures. Otherwise the fits to run, each on columns of its own: a list of mappings, aspl.DataFrame.to_dicts()gives them, or a PolarsDataFrameof them, one row per job. A job’s keys are"subset", a position insubsets;"target", a name or position, as intargets;"draw", a column oftarget_signs, given with it and only with it;"features", the job’s columns, asfeaturesnames them; missing orNoneisfeatures, and so every feature when that isNonetoo;"penalty_weights", for a path only: one per column of the job. Missing orNoneispath’s, which must then have one per column of the job too, or every weight 1.
A job’s fit is that of its columns merged alone, to the bit (Notes).
Returns
One list per subset, with one dict per target. A ridge fit’s dict has
coef, the coefficients over the Gram’s columns, andcoef_stats()’resid_var,sigma2,r2,n,seandt; under a sequence of ridges each number butnhas one row or entry per ridge. A path’s dict islars_path()’s. Withtarget_signs, one such list per draw. Withjobs, one such dict per job, in their order, over every column of the Grams: 0, ornanforseandt, at a column the job does not read.Raises
ValueErrorWhen:
gramsis empty, or the Grams differ in columns or targets;a subset is empty, or holds a position out of range or twice;
without
within, a subset of several holds a Gram pooled within parts (asmerge());target_signsis given withoutwithin, has another shape, or holds an entry other than +1 or -1;pathhas an unknown key, a limit below 1, orpenalty_weightsof the wrong length or not finite and above 0, as forlars_path();with
jobs:targetsis given; a job has a key it does not take, lacks itssubsetortarget, has asubsetordrawout of range, adrawwithouttarget_signsor none with them,featuresthat are one name, hold the intercept or name a column twice, orpenalty_weightswithoutpath, of another length than its columns, or not finite and above 0;a Gram has no
means_by_targetorcross_centered, whichmerge()forms after pooling and this does not;for a ridge fit,
ridgeis not finite and at least 0, or a Gram has no target moments (ascoef_stats());threadsis below 1.
WrongTypeErrorjobsis neither a list nor aDataFrame, a job is not a mapping, or a limit inpathis not a whole number. It is both aTypeErrorand aValueError.TypeErrorthreadsis not an integer orNone, orpathgives bothmax_iterand its older namemax_steps.KeyError,IndexErrorAs for
solve()andlars_path(): a job’s column or target the Grams do not have is aKeyError, and its position out of range anIndexError, each naming the job.
Examples
This code reads
dffrom Example data:spec = po.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=float("inf"), group="stock_id") bank = po.ModelBank([spec]) bank.fit_predict(df) blocks = bank.gram("ridge") # one Gram per stock # A ridge fit in each block alone, and x0's t in each. each = po.gram.solve_subsets(blocks, [[i] for i in range(len(blocks))], ridge=1e-6) print([round(float(fits[0]["t"][1]), 1) for fits in each])
[38.8, 36.1, 37.8, 41.2]
See also
merge(),solve(),coef_stats()andlars_path(), one merge and one fit at a time.Stability selection over halves of the weeks, Per-block coefficients, A null for the selection, by sign flips and A screen of its own for each path in docs/GRAM.md, the theory, and Select columns that hold across the weeks and Fit per-block coefficients, a recipe of each use.
Pool within blocks to leave their levels out in Pool Grams.
Notes
A path over each pair of blocks, its null runs under random signs, and a screen of its own for each job, on the example’s blocks:
spec = po.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=float("inf"), group="stock_id") bank = po.ModelBank([spec]) bank.fit_predict(df) blocks = bank.gram("ridge") # one Gram per stock halves = po.gram.solve_subsets(blocks, [[0, 1], [2, 3]], path={"max_active": 1}) signs = np.random.default_rng(0).choice([-1.0, 1.0], size=(len(blocks), 20)) null = po.gram.solve_subsets(blocks, [[0, 1], [2, 3]], path={"max_active": 1}, within=True, target_signs=signs) # a list per draw jobs = [{"subset": 0, "draw": 0, "target": "y", "features": ["x0"]}, {"subset": 1, "draw": 3, "target": "y", "features": ["x1", "x0"]}] screened = po.gram.solve_subsets(blocks, [[0, 1], [2, 3]], path={"max_active": 1}, within=True, target_signs=signs, jobs=jobs) print([h[0]["active"][-1] for h in halves], # each half's first column len(null), len(null[0]), # 20 draws of 2 subsets [j["active"][-1] for j in screened]) # each job's first column
[['x0'], ['x0']] 20 2 [['x0'], ['x0']]
The ridge fit is
(A + ridge * I) b = r_t A, r_t as solve() forms them b_0 = ybar_t - m_t . b the intercept, with one resid_var = S_yy - 2 b' r_t + b' A b sigma2 = resid_var * n / (n - p) n = target_n_kish se = sqrt(diag(inv(A)) * sigma2 / n), t = b / se se_0 = sqrt((1 + m_t' inv(A) m_t) * sigma2 / n)
with
pthe columns with variance and the intercept, or underwithinthe columns with variance and the parts the target has rows in. A column of none, such as a constant thatstandardizedrops at 0, has no coefficient to estimate and spends no degree of freedom. With an intercept,Ais the columns’ centered co-moments,r_tthe target’s centered cross-moments,m_tits column means,ybar_tits mean andS_yyits variance. Without one they are the raw moments andE[y**2], ascoef_stats()reads them, and there is nose_0. Underwithinthe intercept has none either. Understandardizethe system is solved in correlation form, assolve()solves it.The ridge fit’s system and the inverse its errors read are both factorized by Cholesky, where
solve()runs numpy’s symmetric eigendecomposition andcoef_stats()its inverse, so the two agree to rounding: the system’s condition number times1e-16, measured within5e-13of each number’s size at 2,000 columns. A system whose factorization fails, such as a constant column under a ridge of 0, givesnanhere, wheresolve()divides by an eigenvalue of 0 or of rounding size. A nearly singular one gives what any solve of it gives, rounding noise. A column of no variance, such as a constant thatstandardizedrops at 0, hasnanfor itsseandt, and the other columns’ are read from the inverse of the columns kept, as a fit without it gives them.The Grams are read once, into memory the call holds while it runs, and every subset is merged and fitted there, on the process’s threads, without a Python copy of a matrix per subset. The copy is the Grams’ size again for the call’s length. A subset’s merge is formed on the columns its fits read and the intercept alone, and dropped when its fits are done. Its targets share one factorization. The merge is
merge()’s arithmetic entry for entry, so it agrees with it to the bit. For 38 Grams and 100 subsets of 19, measured on an M4 Pro on 2026-11-08 under a load near 10, it took 0.015 s at 200 columns and 3.3 s at 2,000, where the loop ofmerge(),solve()andcoef_stats()took 0.51 s and 80 s.Jobs. Each subset is merged once, on the intercept and every column its jobs read, and each draw pools its cross-moments again once per subset. A job’s fit is that of its columns merged alone, to the bit: a path is
lars_path()onsubset(merge(parts, within=within), ["intercept", *features])(without"intercept"on a Gram through the origin) of the subset’s Grams, each with its targets’ cross-moments times its sign in the draw. A ridge fit is this call’s on[subsets[subset]],target_signs[:, [draw]],featuresandtargets=[target]. Jobs that share a subset, draw and columns share that design’s factorization, and the jobs run beside each other on the threads, as the subsets do. A screen per subset, per target and per draw, as complementary-pairs stability selection runs, is then one call. It was measured on an M4 Pro on 2026-11-08 under a load near 5, with 100 subsets of 19 of 38 Grams, 11 draws and 10 targets: 11,000 jobs, each a path to 10 columns on 400 of 1,500 columns. The call took 13 ms a subset. The loop took 700 ms a subset:merge()of the subset’s signed Grams for each draw, thensubset()andlars_path()for each job.