polars_online.eval.window_metrics¶
- polars_online.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, usemetrics().Parameters
dfA 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, asmetrics()reads one.specThe spec’s name, or the spec dict itself, as
metrics()reads it.clockThe column whose values place each row in a window: a number, a
Datetime, aDateor aDuration. 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. ATimeis refused, since it starts again at midnight.everyThe 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
DatetimeorDateclock it is a duration: text such as"1h"or"1mo", atimedelta, or apl.durationexpression. On aDurationclock it is a length of time with no months, quarters or years. Notes say where each kind of window starts.group,targets,min_samples,binarymetrics()’ own. A window with fewer thanmin_samplesrows keeps its row, withnfilled and the scores null.
Returns
metrics()’ columns for each window, withwindow_start, the window’s left edge, after the keys.window_starthas the clock’s own dtype. One row perslot,target,groupkey and window, sorted by them.Raises
Whatever
unpack()raises fordfandspec, and:ValueErroreveryis 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 aDurationclock. Orevery, 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, pastInt8: cast the clock toInt64. Or theclockcolumn is named like a column ofunpack()’s long form (RESERVED) orwindow_start. And whatmetrics()raises forgroup,min_samplesandbinary.WrongTypeErrorThe
clockcolumn is neither numeric nor temporal, or is aTime, which starts again at midnight. It is both aTypeErrorand aValueError, as a bank’s refusal of the same clock is.ColumnNotFoundErrordfdoes not have theclockcolumn or agroupcolumn. It is both Polars’ColumnNotFoundErrorand aValueError.
A query is refused as its result would be, with the same message, before it runs, and also with
ValueErrorwhere 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
dffrom Example data:spec = po.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=100.0) out = po.ModelBank([spec]).fit_predict(df) windows = po.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 = po.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_metricsswitch 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 andgroup), 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.30000000000000004for0.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 withevery=0.01). Give the clock in whole units, as an integer, where the edges must be exact.On a
DatetimeorDateclock,everyis 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. Atimedeltais read as Polars reads it, so its whole days are calendar days. Apl.durationexpression 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
Durationclock,everyis a length of time with no calendar, and a window starts at a whole number ofeveryfrom 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 undermetrics()’ bounded settings, and 236, 416 and 715 MiB under Polars’ defaults. The scores are the frame’s asmetrics()’ are.Polars starts the windows of a time-zoned clock whose
everyis 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 withValueError: sort the query by the clock within each key, or pass the collected frame.