rheon.polars.eval.window_metrics

rheon.polars.eval.window_metrics(df: DataFrame | LazyFrame, spec: str | dict, *, clock: str, every: float | timedelta | str | _Expr, group: str | Iterable[str] | None = None, targets: Sequence[str] | None = None, min_samples: int = 30, binary: bool | None = None) → DataFrame[source]

Score a spec’s out-of-sample predictions in windows of the clock.

Use it to see how a spec’s scores move over the stream, such as R² per hour or per day. The windows do not overlap: each row falls in one, as in Polars’ group_by_dynamic. For one score over the whole frame, use metrics().

Parameters

df

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

spec

The spec’s name, or the spec dict itself, as metrics() reads it.

clock

The column whose values place each row in a window: a number, a Datetime, a Date or a Duration. A row whose clock is null is in no window and is not scored, as Polars leaves a null key out of a group, and so is a row whose float clock is NaN or infinite, which no window holds. A Time is refused, since it starts again at midnight.

every

The length of each window, in the clock’s units. On a numeric clock it is a number, finite and above 0, and a whole number on an integer clock, so a window’s edges are values of the column. On a Datetime or Date clock it is a duration: text such as "1h" or "1mo", a timedelta, or a pl.duration expression. On a Duration clock it is a length of time with no months, quarters or years. Notes say where each kind of window starts.

group, targets, min_samples, binary

metrics()’ own. A window with fewer than min_samples rows keeps its row, with n filled and the scores null.

Returns

metrics()’ columns for each window, with window_start, the window’s left edge, after the keys. window_start has the clock’s own dtype. One row per slot, target, group key and window, sorted by them.

Raises

Whatever unpack() raises for df and spec, and:

ValueError

every is not finite and above 0, is of the wrong kind for the clock, is not a whole number on an integer clock, or is a month, a quarter or a year on a Duration clock. Or every, or the left edge of a window, is past what an integer clock’s dtype holds, as a window of 100 that holds -120 starts at -200, past Int8: cast the clock to Int64. Or the clock column is named like a column of unpack()’s long form (RESERVED) or window_start. And what metrics() raises for group, min_samples and binary.

WrongTypeError

The clock column is neither numeric nor temporal, or is a Time, which starts again at midnight. It is both a TypeError and a ValueError, as a bank’s refusal of the same clock is.

ColumnNotFoundError

df does not have the clock column or a group column. It is both Polars’ ColumnNotFoundError and a ValueError.

A query is refused as its result would be, with the same message, before it runs, and also with ValueError where a key’s clock steps back, in a later chunk, before the windows an earlier chunk started for it would place it (see Notes).

Examples

This code reads df from Example data:

spec = rp.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=100.0)
out = rp.ModelBank([spec]).fit_predict(df)
windows = rp.eval.window_metrics(out, spec, clock="t", every=100.0)   # 100 units of t each
for start, n, r2 in windows.select("window_start", "n", "r2").iter_rows():
    print(f"from t = {start:.0f}: {n} rows, r2 {r2:.3f}")
by_hour = rp.eval.window_metrics(out, spec, clock="ts", every="1h")    # a Datetime clock
print(by_hour.height, "windows of an hour")
from t = 0: 96 rows, r2 0.940
from t = 100: 100 rows, r2 0.941
from t = 200: 100 rows, r2 0.956
from t = 300: 100 rows, r2 0.926
8 windows of an hour

See also

  • metrics(), the same scores over the whole frame.

  • The emit_metrics switch of a spec, the same scores kept by the model as it learns, exponentially weighted.

Notes

The windows are those of Polars’ group_by_dynamic(clock, every=every, closed="left", label="left") over each key (slot, target and group), so a window here is the window Polars would make of the same rows:

  • On a numeric clock, a window starts at floor(clock / every) * every, as Polars’ integer index does. A float clock, which Polars does not window, is windowed the same way, in doubles: a label can read a little above the decimal edge it stands for, 0.30000000000000004 for 0.3, and a clock on a decimal edge can, rarely, fall in the window before it (7 of 2,000 rows on a grid of 0.001 with every=0.01). Give the clock in whole units, as an integer, where the edges must be exact.

  • On a Datetime or Date clock, every is read as Polars reads a duration. Nanoseconds to hours ("ns" to "h") are elapsed time: across a change of a time zone’s offset, a "5h" window still holds five hours, and "24h" holds 24 of them. Days, weeks, months, quarters and years ("d", "w", "mo", "q", "y") follow the wall calendar: "1d" runs from midnight to midnight, 23 or 25 hours on the day of a change, and "1mo" is a calendar month. A timedelta is read as Polars reads it, so its whole days are calendar days. A pl.duration expression is the length of time it evaluates to. A month has no fixed length, so a spec’s clock parameters refuse one, but a window takes it.

  • On a Duration clock, every is a length of time with no calendar, and a window starts at a whole number of every from 0.

Given a query, this holds one chunk of it and the sums of each window it has seen, ten numbers per slot, key and window, read as metrics() reads a query, and Polars holds what it has read ahead of them, which Cut what Polars reads ahead bounds. Scoring a scan of a two-spec output by the day and by a key of four values held 102 MiB at a million rows, 108 MiB at four million and 110 MiB at sixteen million under metrics()’ bounded settings, and 236, 416 and 715 MiB under Polars’ defaults. The scores are the frame’s as metrics()’ are.

Polars starts the windows of a time-zoned clock whose every is a fixed length that does not divide a day, such as "90m", from a key’s first clock rather than from midnight. So each chunk of a query is windowed from the first clock of the key in the chunks before it, and its windows are the frame’s. A key whose clock steps back, in a later chunk, to before that first clock would be windowed from the new one in the frame, so where that moves its windows the query is refused with ValueError: sort the query by the clock within each key, or pass the collected frame.