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 use coef(), and for the sums of a group that has closed, closed_groups().

Parameters

spec

The spec to read, by name or by position. Only ewridge, lasso and ew_cov report. Every other model gives an empty list, which is not an error: huber and quantile keep a reweighted Gram per target that is not exported, rls keeps a Cholesky factor, kalman a covariance, and the gradient models no second moment.

group

The group to read: one group key, as groups() reports it, or a list of keys, with None in the list for the null group. The default, None, reads every group, in groups()’ order. A key the bank has never seen gives an empty list.

dtype

The dtype of comoments and lag_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, for comoments as a (k, k) matrix, or "packed" for its upper triangle with the diagonal, row by row, a 1-D array of k * (k + 1) // 2: about half the bytes (see Notes). lag_comoments is 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 its targets. k is the number of columns, and the arrays are exponentially weighted (EW) and decayed on the model’s own clock. Each dict has:

group, instance

The group key as groups() reports it ("" for a spec without a group column, None for a null key), and the instance’s field suffix ("@h500", or "" for a single instance).

columns, targets

What the axes mean. columns is the spec’s features, with "intercept" first when the spec has one: the term names of rheon.spec.coef_index(). targets is 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 for ew_cov, which learns from none. The names make the dict self-describing, so rheon.gram takes a column or a target by name.

weight_sum

The accumulated weight behind these moments.

n_kish

Kish’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). None before the first row, and under a hard window where subtracting the rows that leave keeps no digit of the sum of squared weights.

means

The EW column means, shape (k,).

comoments

The centered co-moments, the EW analogue of a centered X'X / n, shape (k, k), or packed under layout="packed". Centering is what keeps them accurate at a large offset.

cross_moments

Per target, the uncentered cross-moments E[z*y], with z a row’s columns and y the target, over the rows the target was present on, shape (n_targets, k). Empty for ew_cov.

means_by_target

Per 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 equal means, to rounding, for a target present on every row the Gram learned, which every target is under target_gaps = "own_rows". Under "pairwise" a target with gaps has its own. rheon.gram.solve() reads them. Empty for ew_cov.

cross_centered

Per 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 what rheon.gram.solve() reads. Empty for ew_cov.

target_weights

Per target, the accumulated weight, shape (n_targets,). It differs from weight_sum when targets have different null patterns.

target_means, target_vars

Per target, the EW mean and centered variance of the target itself, shape (n_targets,), in the same arithmetic as comoments: a target’s variance here is, to the bit, the one an ew_cov over that column would report. Empty for ew_cov.

target_n_kish

Per target, Kish’s effective sample size over that target’s rows, target_weights**2 / sum(w**2). nan for a target that has not seen a weighted row, and under a hard window where the squared weights keep no digit, as for n_kish. Empty for ew_cov.

lags, lag_comoments

The lags an ew_cov(lags=[...]) accumulates at, in the order given, and their cross-moments as an (L, k, k) array, L the number of lags. lag_comoments[l][a][b] is E_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, since a leading b is not b leading a, and at lag 0 it would be comoments exactly. Both are None for a spec without lags.

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 a window_size every array is the hard window’s, the target moments included, since the window’s snapshots carry them too. So rheon.gram.solve() on it fits the hard window as it stood after the last row.

Raises

KeyError

spec is a name the bank does not have.

IndexError

spec is a position the bank does not have.

TypeError

group is not a str, a list of them with None allowed, or None.

ValueError

dtype is not float64 or float32, or layout is not "full" or "packed". Under dtype="float32", an entry float32 cannot hold to its precision, which the message names by its column (see Notes).

ModuleNotFoundError

numpy 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 df from 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

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_cap handling, 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 recompute X'X from 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, BLAS dgemm is 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 needs Var[y].

Kish’s size. weight_sum counts 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 rows d clock units apart, with lam = 0.5 ** (1 / half_life). It is scale-free: decay scales weight_sum**2 and sum(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, which weight_sum and target_weights say. Under a hard window it is None where the window’s sum of squared weights is no more than 64 eps times 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] equals cross_moments[t] - means_by_target[t] * ybar_t in exact arithmetic. Formed in floating point at a level L, that difference carries a rounding error of about L**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] target t’s coefficients, intercept first. For a target present on every row the Gram holds, which is every target under target_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] and ybar = 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, and lag_comoments under lags, are the arrays that grow as k²: comoments is 800 MB a Gram in float64 at 10,000 columns. Together, the two options make comoments a quarter of its bytes and lag_comoments half, since it is never packed. Every function of rheon.gram takes 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 within 2**-24 of 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 are k long, 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 read inf, 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) with i <= j is at i * (2 * k - i + 1) // 2 + (j - i), the order of numpy.triu_indices(k), and (j, i) is the same entry. Laid back into a k x k array m by m[np.triu_indices(k)] = packed and mirrored, it is the full layout’s matrix, bit for bit, since the model keeps the matrix symmetric. A closed row’s comoments is packed the same way.