rheon.polars.ModelBank.gram¶
- ModelBank.gram(spec: str | int, group: str | Iterable[str | None] | None = None, *, dtype: Any = 'float64', layout: Literal['full', 'packed'] = 'full') list[Gram][source]¶
Return the Gram behind a spec’s fit, per group and instance, as numpy arrays.
Use it to do with a fit’s Gram what the model does not: a custom penalty, an information criterion, a condition number, standard errors, or a fit pooled over groups, with the functions of
rheon.gram. For the coefficients alone usecoef(), and for the sums of a group that has closed,closed_groups().Parameters
specThe spec to read, by name or by position. Only
ewridge,lassoandew_covreport. Every other model gives an empty list, which is not an error:huberandquantilekeep a reweighted Gram per target that is not exported,rlskeeps a Cholesky factor,kalmana covariance, and the gradient models no second moment.groupThe group to read: one group key, as
groups()reports it, or a list of keys, withNonein the list for the null group. The default,None, reads every group, ingroups()’ order. A key the bank has never seen gives an empty list.dtypeThe dtype of
comomentsandlag_comoments:"float64", the default, or"float32", which halves their bytes (see Notes). A numpy or Polars dtype of either is taken too. Every other array stays float64.layout"full", the default, forcomomentsas a(k, k)matrix, or"packed"for its upper triangle with the diagonal, row by row, a 1-D array ofk * (k + 1) // 2: about half the bytes (see Notes).lag_comomentsis never packed, since a lagged matrix is not symmetric.
Returns
A list of dicts, one per (group, instance), an instance being the part of the model that fits one half-life, and one per Gram where a spec reads several. Under
target_gaps = "own_rows", the default, targets missing on different rows are fitted from Grams of their own, one per set of targets present on the same rows, and each dict names itstargets.kis the number of columns, and the arrays are exponentially weighted (EW) and decayed on the model’s own clock. Each dict has:group,instanceThe group key as
groups()reports it (""for a spec without agroupcolumn,Nonefor a null key), and the instance’s field suffix ("@h500", or""for a single instance).columns,targetsWhat the axes mean.
columnsis the spec’s features, with"intercept"first when the spec has one: thetermnames ofrheon.spec.coef_index().targetsis the target names the per-target arrays are indexed by: the spec’s, or the ones this Gram’s rows belong to. It is empty forew_cov, which learns from none. The names make the dict self-describing, sorheon.gramtakes a column or a target by name.weight_sumThe accumulated weight behind these moments.
n_kishKish’s effective sample size,
weight_sum**2 / sum(w**2): the number of equally weighted rows these moments are worth, which a standard error divides by (see Notes).Nonebefore the first row, and under a hard window where subtracting the rows that leave keeps no digit of the sum of squared weights.meansThe EW column means, shape
(k,).comomentsThe centered co-moments, the EW analogue of a centered
X'X / n, shape(k, k), or packed underlayout="packed". Centering is what keeps them accurate at a large offset.cross_momentsPer target, the uncentered cross-moments
E[z*y], withza row’s columns andythe target, over the rows the target was present on, shape(n_targets, k). Empty forew_cov.means_by_targetPer target, the column means over the rows it was present on, shape
(n_targets, k): what its cross-moments are centered at, and its intercept is recovered from. They equalmeans, to rounding, for a target present on every row the Gram learned, which every target is undertarget_gaps = "own_rows". Under"pairwise"a target with gaps has its own.rheon.gram.solve()reads them. Empty forew_cov.cross_centeredPer target, the cross-moments centered at its column means and its own mean,
E[(z - m_t) * (y - ybar_t)], shape(n_targets, k): what the model solves from, and whatrheon.gram.solve()reads. Empty forew_cov.target_weightsPer target, the accumulated weight, shape
(n_targets,). It differs fromweight_sumwhen targets have different null patterns.target_means,target_varsPer target, the EW mean and centered variance of the target itself, shape
(n_targets,), in the same arithmetic ascomoments: a target’s variance here is, to the bit, the one anew_covover that column would report. Empty forew_cov.target_n_kishPer target, Kish’s effective sample size over that target’s rows,
target_weights**2 / sum(w**2).nanfor a target that has not seen a weighted row, and under a hard window where the squared weights keep no digit, as forn_kish. Empty forew_cov.lags,lag_comomentsThe lags an
ew_cov(lags=[...])accumulates at, in the order given, and their cross-moments as an(L, k, k)array,Lthe number of lags.lag_comoments[l][a][b]isE_w[d_a(t) * d_b(t - lags[l])], both deviations taken against the mean before the row. The matrix is not symmetric for a lag above 0, sincealeadingbis notbleadinga, and at lag 0 it would becomomentsexactly. Both areNonefor a spec withoutlags.
Values are in the features’ original units. The intercept, when the spec has one, is column 0: a constant 1, so it has zero variance in
comoments. Under awindow_sizeevery array is the hard window’s, the target moments included, since the window’s snapshots carry them too. Sorheon.gram.solve()on it fits the hard window as it stood after the last row.Raises
KeyErrorspecis a name the bank does not have.IndexErrorspecis a position the bank does not have.TypeErrorgroupis not a str, a list of them withNoneallowed, orNone.ValueErrordtypeis not float64 or float32, orlayoutis not"full"or"packed". Underdtype="float32", an entry float32 cannot hold to its precision, which the message names by its column (see Notes).ModuleNotFoundErrornumpy is not installed. It is not a dependency of this package, as it is not of Polars:
pip install rheon[numpy]adds it.
Examples
This code reads
dffrom Example data:spec = rp.spec.ewridge( "ridge", targets=["y"], features=["x0", "x1"], half_life=100.0, ridge=1e-6 ) bank = rp.ModelBank([spec]) bank.fit(df) g = bank.gram("ridge")[0] # one dict: one group, one instance coef = rp.gram.solve(g, target="y", ridge=1e-6) # solved again from the Gram print(g["columns"], coef.round(2)) print(bank.coef()["coef"].round(2).to_list()) # the model's own fit var_y = g["target_vars"][0] # the target's moments give its R² r2 = 1 - (var_y - coef[1:] @ g["comoments"][1:, 1:] @ coef[1:]) / var_y print(f"R² {r2:.2f}")
['intercept', 'x0', 'x1'] [ 0.99 1.97 -1. ] [0.99, 1.97, -1.0] R² 0.94
See also
rheon.gram, the functions that pool, narrow and solve these dicts.closed_groups(), the same sums for each group that has closed.coef(), the fit the model solved.
Notes
Why the Gram is exported. The Gram is the expensive part of a fit, and it is already exact, centered, decayed on the model’s own clock with its session and
gap_caphandling, and resumable. Without it, anything other than the model’s own solve (a custom penalty, an information criterion,cond(G), a scree plot, forward stepwise, orthogonal matching pursuit, or a fit checked by hand) would recomputeX'Xfrom the raw data in a second pass. It comes from one pass over data that is never materialized, at every point in the stream rather than one, and it holds the matrices the deployed model solves against. It is not a speed claim: for one Gram computed at once over materialized data, BLASdgemmis blocked, vectorized, and comfortably faster. The target moments make the export a complete sufficient statistic. With the cross-moments alone a saved Gram gives no residual variance, no R², no information criterion and no standard error, since each of them needsVar[y].Kish’s size.
weight_sumcounts weight, not rows, so it is not a sample size.(1 + lam**d) / (1 - lam**d)is the Kish size of an EW window of unit rowsdclock units apart, withlam = 0.5 ** (1 / half_life). It is scale-free: decay scalesweight_sum**2andsum(w**2)by the same factor, so it does not shrink when a stream goes quiet. It says how many rows these moments average, not how old they are, whichweight_sumandtarget_weightssay. Under a hard window it isNonewhere the window’s sum of squared weights is no more than64 epstimes the history’s: a window of rows far lighter than the history, where the ratio would be rounding.The centered cross-moments.
cross_centered[t]equalscross_moments[t] - means_by_target[t] * ybar_tin exact arithmetic. Formed in floating point at a levelL, that difference carries a rounding error of aboutL**2 * eps, so the model keeps the centered form itself.The two moment forms. Mixing the raw and the centered forms gives a wrong answer, not an error, so the identities between them are stated here, with
coef[t]targett’s coefficients, intercept first. For a target present on every row the Gram holds, which is every target undertarget_gaps = "own_rows":raw = comoments + outer(means, means) raw @ coef[t] == cross_moments[t] (up to the ridge term)
and, for a spec with an intercept, every target’s centered form the model solves, up to the ridge term, with
m = means_by_target[t]andybar = cross_moments[t][0]:comoments[1:, 1:] @ coef[t][1:] == cross_centered[t][1:] coef[t][0] == ybar - m[1:] @ coef[t][1:]
With an intercept,
raw[0] == means.A compact Gram.
comoments, andlag_comomentsunderlags, are the arrays that grow ask²:comomentsis 800 MB a Gram in float64 at 10,000 columns. Together, the two options makecomomentsa quarter of its bytes andlag_comomentshalf, since it is never packed. Every function ofrheon.gramtakes either, merging and solving in float64 whatever it is given. The state itself stays float64 and whole: the options shape only what is handed back.Under
dtype="float32"each entry is the float64 rounded to nearest, so it is within2**-24of it, relative, about 6e-8, and a solve read from it carries that error times the system’s condition number. The other arrays stay float64: they areklong, and the means are what a merge’s spread term is made of. An entry is refused when float32 cannot hold it to that precision: past float32’s largest number, about 3.4e38, which would readinf, or nonzero and below its smallest normal number, about 1.2e-38, which would read 0 or keep fewer digits. A column spread 1e20 wide, or 1e-20, gets there, since its variance squares the scale. Rescale it with Polars before the bank, or read the Gram in float64.Under
layout="packed"entry(i, j)withi <= jis ati * (2 * k - i + 1) // 2 + (j - i), the order ofnumpy.triu_indices(k), and(j, i)is the same entry. Laid back into ak x karraymbym[np.triu_indices(k)] = packedand mirrored, it is the full layout’s matrix, bit for bit, since the model keeps the matrix symmetric. A closed row’scomomentsis packed the same way.