polars_online.eval.compare_specs

polars_online.eval.compare_specs(df: DataFrame | LazyFrame, specs: Iterable[str | dict], *, group: str | Iterable[str] | None = None, targets: Sequence[str] | None = None, min_samples: int = 30, binary: bool | None = None) → DataFrame[source]

Score several specs’ out-of-sample predictions in one table.

Use it to read side by side how well each of several specs predicted, over a whole frame. To test whether one spec’s residuals are smaller than another’s, use diebold_mariano(), clark_west() or seqtest(); to choose among the grid points of one spec, use grid_search().

Parameters

df

A frame a bank returned, holding each spec’s output column, or a query of one, a LazyFrame, which this runs once for every spec and reads one chunk at a time, as metrics() reads one.

specs

The specs that wrote the columns, each its name or its dict, read as metrics() reads its spec.

group, targets, min_samples

metrics()’ own, applied to every spec alike.

binary

metrics()’ own, applied to every spec alike. None, the default, reads it from the spec dicts’ losses, and refuses specs whose losses read it both ways, since a classifier’s scores and a regression’s are different columns.

Returns

metrics()’ table for each spec, one under another, with a spec column first holding the spec’s name. No specs give an empty frame.

Raises

Whatever metrics() raises for each spec, in this function’s name, and ValueError when binary is None and some specs are fits with loss="logistic" and others are not (pass the two sets in two calls, or set binary), or when a group column is named spec, as the result’s first column is.

Examples

This code reads df from Example data:

ridge = po.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=100.0)
x0_only = po.spec.ewridge("x0_only", targets=["y"], features=["x0"], half_life=100.0)
out = po.ModelBank([ridge, x0_only]).fit_predict(df)
table = po.eval.compare_specs(out, [ridge, x0_only])   # one row per spec and slot
for name, n, r2, mse in table.select("spec", "n", "r2", "mse").iter_rows():
    print(f"{name}: {n} rows, r2 {r2:.3f}, mse {mse:.3f}")
ridge: 396 rows, r2 0.944, mse 0.273
x0_only: 397 rows, r2 0.728, mse 1.330

See also

Notes

Each spec is scored on its own rows, so two specs whose warm-ups differ in length are scored on different rows, as the 396 and 397 rows in the example are. Diebold and Mariano’s test and Clark and West’s read only the rows where both specs have a residual. Given a query, every spec’s sums are read in the one run of it, beside what Polars reads ahead of the call, which Cut what Polars reads ahead bounds: scoring two specs of a scan by a key of four values held 91 MiB at a million rows, 106 MiB at four million and 108 MiB at sixteen million under metrics()’ bounded settings, and 242, 450 and 871 MiB under Polars’ defaults.

Diebold and Mariano’s (1995) test asks whether two specs’ squared errors differ on average. Its statistic is the mean of the loss differential d = resid_b² − resid_a² over Newey and West’s standard error, and is about N(0, 1) when the two predict equally well. diebold_mariano() computes it. Its lags, 0 by default, are right at 0 only where the differentials are uncorrelated from row to row: two specs that each leave out something persistent make one-step errors that run, and then lags=0 found two equally accurate specs to differ at 5% on 24% to 32% of simulated streams. For a target that looks h rows ahead, give about 2 h; its lags entry gives the sizes measured.

Between two nested specs, Diebold and Mariano’s test leans toward the smaller one, and Clark and West’s (2007) correction removes the lean. When the larger spec’s extra coefficients are truly zero, it still estimates them, and their noise adds (pred_small − pred_big)² to its squared error on average. So under the null the differential favors the smaller spec, and the test rarely finds the larger one better even when it is (Clark and McCracken, 2001). Clark and West add the term back:

f  = resid_small² − resid_big² + (resid_big − resid_small)²
cw = f̄ · n / sqrt(S)            one-sided: cw > 1.645 rejects at 5%

Here f̄ is the mean of f over the n rows, and S is Newey and West’s long-run variance of f times n, as diebold_mariano() gives it for d. clark_west() computes it. With half_life, each of the two functions gives its statistic on every row instead, exponentially weighted.

seqtest(), and the seqtest model a bank runs, give evidence that one spec predicts closer on more rows, by betting on the sign of |resid_b| − |resid_a|. That is not the question the two tests above ask: a spec with rare large errors can be closer on most rows and have the larger mean squared error. The evidence can be read at every row, as often as you like, without increasing the false-alarm rate: reject at the 5% level the first time log_e_a_<t> reaches ln 20. The 5% holds where, at every row and whatever came before, the next sign is no more likely positive than negative, which is more than the two being equally close on average: equally accurate specs whose errors run from row to row give signs that run, and both bets grow (seqtest()’s Notes give the rates measured).