polars_online.gram.merge

polars_online.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, use solve_subsets().

Parameters

grams

The parts, each as gram() returns it, all with the same columns and targets. Merging one Gram without within returns it unchanged. Parts in a compact form (ModelBank.gram(dtype="float32") or layout="packed") merge in float64. Under target_gaps="own_rows" a spec may have a Gram per set of targets: merge the entries with the same targets across the shards.

within

False, the default, pools the parts into the Gram of their union. True pools 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 back None:

  • lags and lag_comoments: a lagged cross-moment pairs a row with the row l back within its own part, and no part holds the pairs across a part boundary.

  • group and instance: 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 no n_kish and adds nothing to the sum.

  • the target moments, where a part has none, such as a mapping built by hand without them.

  • means_by_target and cross_centered, where a part has none. solve() then forms them from cross_moments.

With within=True it has two keys more: within_parts counts the parts with weight, and target_within_parts counts, 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() and solve_subsets() give the slopes and nan for the intercept, and coef_stats() takes one degree of freedom per part in place of the intercept’s one.

Raises

ValueError

When grams is empty, when the parts differ in columns or targets, or when, without within, 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. With within=True, also when a part has no cross_centered and neither an intercept column nor target_means to center its cross-moments at.

KeyError

When a part has no columns key, such as a mapping built by hand.

Examples

This code reads df from Example data:

spec = po.spec.ewridge(
    "ridge", targets=["y"], features=["x0", "x1"], half_life=100.0, group="stock_id"
)
bank = po.ModelBank([spec])
bank.fit_predict(df)
parts = bank.gram("ridge")                      # one Gram per stock
pooled = po.gram.merge(parts)                   # the Gram of every stock's rows together
within = po.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_a and W_b, means m_a and m_b, co-moments C_a and C_b, squared-weight sums Q_a and Q_b, and the gap between the means d = 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_target pools over its own rows, by its target_weights, and its cross_centered as 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 i with weights W_i, co-moments C_i, and for each target its weights T_i, centered cross-moments c_i and variances V_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 means and means_by_target are 0, the intercept’s 1 aside, its cross_moments are its cross_centered, and its target_means are 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 to C and 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’s weight_sum and target_weights by 0.5 ** (dt / half_life), with dt the clock from its last row to the later half’s last row, each step capped at gap_cap as the bank caps it. Leave every other key as it is. The means and co-moments are weighted means, and n_kish and target_n_kish do 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 reads df from Example data:

halves = po.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 = po.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 = po.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