rheon.gram.merge¶
- rheon.gram.merge(grams: Sequence[Gram], *, within: bool = False) Gram[source]¶
Pool the Grams of disjoint sets of rows into the Gram of their union, or within each part.
Use it to combine Grams that share a weighting: one per shard of a pass, one per group, one per worker, or one per week of a stream. To keep some of a Gram’s columns, use
subset(). To merge many subsets and fit each in one call, usesolve_subsets().Parameters
gramsThe parts, each as
gram()returns it, all with the samecolumnsandtargets. Merging one Gram withoutwithinreturns it unchanged. Parts in a compact form (ModelBank.gram(dtype="float32")orlayout="packed") merge in float64. Undertarget_gaps="own_rows"a spec may have a Gram per set of targets: merge the entries with the sametargetsacross the shards.withinFalse, the default, pools the parts into the Gram of their union.Truepools each part’s moments about its own means and leaves out the gaps between the parts’ means: the Gram of the rows demeaned part by part, whose fit has an intercept per part (the within, or fixed-effects, estimator). Notes give the arithmetic of both.
Returns
A mapping of the same shape as each part (
Gram). When every part is packed, the merge is packed too, entry for entry; otherwise it is the whole matrix. Some keys come backNone:lagsandlag_comoments: a lagged cross-moment pairs a row with the rowlback within its own part, and no part holds the pairs across a part boundary.groupandinstance: a pooled Gram belongs to no one group or instance (the part of a model that fits one half-life).n_kish, where a part has none, such as a part under a hard window whose sum of squared weights kept no digit (gram()): the sum behind it is not there to add. A part that learned nothing is the one case apart: it has non_kishand adds nothing to the sum.the target moments, where a part has none, such as a mapping built by hand without them.
means_by_targetandcross_centered, where a part has none.solve()then forms them fromcross_moments.
With
within=Trueit has two keys more:within_partscounts the parts with weight, andtarget_within_partscounts, per target, the parts with weight for it. A part already pooled within adds its own counts. Every fit reads them:solve(),lasso_path(),lars_path()andsolve_subsets()give the slopes andnanfor the intercept, andcoef_stats()takes one degree of freedom per part in place of the intercept’s one.Raises
ValueErrorWhen
gramsis empty, when the parts differ incolumnsortargets, or when, withoutwithin, several parts include one pooled within parts. Such a part’s means are 0, so a union would add the gap from 0 to the other parts’ means, as if its rows had not been demeaned. Withwithin=True, also when a part has nocross_centeredand neither an intercept column nortarget_meansto center its cross-moments at. And when a part has an array not sized to the Gram’s columns and targets, such as ameansof one entry.KeyErrorWhen a part has no
columnskey, such as a mapping built by hand.
Examples
This code reads
dffrom Example data:spec = rp.spec.ewridge( "ridge", targets=["y"], features=["x0", "x1"], half_life=100.0, group="stock_id" ) bank = rp.ModelBank([spec]) bank.fit_predict(df) parts = bank.gram("ridge") # one Gram per stock pooled = rp.gram.merge(parts) # the Gram of every stock's rows together within = rp.gram.merge(parts, within=True) # each stock's level left out print(len(parts), round(pooled["weight_sum"], 2), within["within_parts"])
4 289.54 4
See also
solve_subsets(), which merges many subsets of the Grams and fits each.subset(), which keeps some of a Gram’s columns.Pooling blocks in docs/GRAM.md, the theory, and Pool Grams, a recipe for pooling, for aging a block first, and for pooling within blocks.
Notes
The union follows Chan, Golub and LeVeque: the pooled co-moments are the weighted average of the parts’ plus the spread between their means. With weights
W_aandW_b, meansm_aandm_b, co-momentsC_aandC_b, squared-weight sumsQ_aandQ_b, and the gap between the meansd = m_b - m_a:W = W_a + W_b m = m_a + (W_b / W) * d C = (W_a * C_a + W_b * C_b) / W + (W_a * W_b / W**2) * outer(d, d) Q = Q_a + Q_b
Each target’s
means_by_targetpools over its own rows, by itstarget_weights, and itscross_centeredas the co-moments do, with the gaps between the parts’ column means and target means.Each part enters centered at its own means, never as a raw sum that a mean is subtracted from afterwards, so data far from zero keep their digits. The parts are folded in one at a time, so the rounding grows with their number. It was measured on 100,000 rows of three columns at a level of 1e4 standard deviations, against the exact union in rational arithmetic, relative to the spread:
how the union was formed
the co-moments’ error
this merge of 2 parts, each exact to float64
2.4e-15
this merge of 1,000 parts
3.8e-14
raw sums of 2 parts, centered afterwards
4.0e-08
raw sums of 1,000 parts, centered afterwards
2.5e-07
one bank’s own Gram, learned over all the rows
3.8e-14
Pooling within parts. For parts
iwith weightsW_i, co-momentsC_i, and for each target its weightsT_i, centered cross-momentsc_iand variancesV_i:W = sum W_i C = sum W_i C_i / W T = sum T_i c = sum T_i c_i / T V = sum T_i V_i / T n_kish = W**2 / sum(W_i**2 / n_kish_i), target_n_kish likewise
folded in the parts’ order as the union is, so where the parts’ means are equal the two forms give the same numbers. Each feature is less its part’s mean, over the target’s rows for that target’s moments, and each target less its part’s mean. So the result’s
meansandmeans_by_targetare 0, the intercept’s 1 aside, itscross_momentsare itscross_centered, and itstarget_meansare 0. Wooldridge (2010, chapter 10) calls a regression on it the within, or fixed-effects, estimator. Its slopes say how the columns and the target move together inside each part, and the parts’ levels drop out. A part with no weight for a target (T_i = 0) adds toCand not to that target’s moments.To merge two halves of a decayed stream in time order, decay the earlier half to the later half’s last row first. Halves run under
half_life=float("inf")merge as they are. Under a finite half-life, each half’s weights are relative to its own last row, so the earlier half is over-weighted by exactly the decay between them. Multiply the earlier half’sweight_sumandtarget_weightsby0.5 ** (dt / half_life), withdtthe clock from its last row to the later half’s last row, each step capped atgap_capas the bank caps it. Leave every other key as it is. The means and co-moments are weighted means, andn_kishandtarget_n_kishdo not change when every weight is scaled, so the sums of squared weights the merge recovers from them decay with the weights. For example, this code readsdffrom Example data:halves = rp.spec.ewridge("h", targets=["y"], features=["x0", "x1"], clock="t", gap_cap=10.0, half_life=100.0) def gram_of(rows): # the Gram of a new bank fed these rows fitted = rp.ModelBank([halves]) fitted.fit_predict(rows) return fitted.gram("h")[0] # Each half's Gram, the early one aged to the late one's last row. early, late = gram_of(df.head(200)), gram_of(df.tail(200)) dt = df["t"][399] - df["t"][199] # early half's last row to late half's decay = 0.5 ** (dt / 100.0) early = dict(early, weight_sum=early["weight_sum"] * decay, target_weights=early["target_weights"] * decay) aged = rp.gram.merge([early, late]) # the Gram of one bank over all 400 rows whole = gram_of(df) print(np.allclose(aged["comoments"], whole["comoments"], rtol=1e-12, atol=1e-12), round(float(aged["weight_sum"]), 6), round(float(whole["weight_sum"]), 6))
True 135.721952 135.721952