rheon.polars.eval.metrics

rheon.polars.eval.metrics(df: DataFrame | LazyFrame, spec: str | dict, *, 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 over a whole frame.

Use it to read how well a spec predicted, per slot, target and group, over a frame in memory or over a query too long to hold, such as a scan of the file a bank’s output was written to. For scores in windows of the clock, use window_metrics(); for several specs in one table, compare_specs(); for scores kept beside the model as it runs, the spec’s own emit_metrics.

Parameters

df

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

spec

The spec’s name, or the spec dict itself, as unpack() reads it. Pass the dict for a target that is not a plain column, and to have binary read from the spec’s loss.

group

One key column, as a spec’s group is, or a list of them, to score each key apart. None, the default, scores every row together.

targets

unpack()’s: the columns the name-based rule may read as targets.

min_samples

The fewest rows a key is scored on, 30 by default. A key with fewer rows keeps its row, with n filled and every score null, as Polars’ rolling_* and ewm_* give null below their min_samples.

binary

Score the slots as a classifier’s: pred a probability and y a 0/1 target, the output of an sgd or ftrl fit with loss="logistic". None, the default, reads it from the spec dict’s loss, and is off given the name alone, since nothing here reads the target’s values to decide. A target other than 0 or 1 on a scored row is refused under it.

Returns

A DataFrame with one row per slot, target and group key, sorted by them, given a frame or a query alike, and these columns after the keys. A slot or key with no scored row has no row, such as a slot whose predictions were all withheld by a warm-up.

n

The rows scored.

r2

The out-of-sample R², against the target’s mean over the rows scored. Null where the target never varied.

ic

The correlation of the prediction with the target. Null where either never varied.

hit_rate

The share of rows whose sign the prediction got right, over the rows where neither y nor pred is 0, as the bank’s emit_metrics counts them. Null where no row is counted. A Poisson sgd fit (loss="poisson") has no sign to hit, so the bank nulls its hit_rate, and so does this, given the spec dict.

mse, rmse

The mean squared residual, and its square root, in the target’s units.

A score that is undefined is null, not an infinity or a NaN that reads as a number. Under binary, two columns take other names with their meaning, and one is added:

brier_skill, in place of r2

The same formula, which on a 0/1 target is the Brier skill score: the share of the Brier score of always predicting the base rate that the fit removes.

accuracy, in place of hit_rate

The share of rows on the right side of 0.5. Every row is counted.

log_loss

The mean of -(y*ln(p) + (1-y)*ln(1-p)), with p clipped to [1e-15, 1 - 1e-15], so a confident miss is a large number and not an infinity.

ic keeps its name under binary: on a 0/1 target it is the point-biserial correlation, the same formula. rmse is then the root of the Brier score.

Raises

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

ColumnNotFoundError

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

ValueError

A group column is named like a column the scores make, in RESERVED or SUM_FIELDS, a score’s name, or window_start: named y, it would key the scores by the target’s value. Rename it. Or, under binary, a scored row’s target is not 0 or 1, which a query raises from the chunk that holds it. Or min_samples is below 0.

WrongTypeError

A group column is an Object, which a query’s chunks cannot be matched by: cast it to String or Categorical. Or min_samples is not a whole number. It is both a TypeError and a ValueError.

A query is refused as its result would be, with the same message, before it runs.

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)
scores = rp.eval.metrics(out, spec, group="stock_id")  # one row per slot, target and stock
for row in scores.select("stock_id", "n", "r2", "hit_rate").iter_rows():
    print(f"{row[0]}: {row[1]} rows, r2 {row[2]:.3f}, hit rate {row[3]:.3f}")
b0: 99 rows, r2 0.939, hit rate 0.899
b1: 99 rows, r2 0.938, hit rate 0.939
b2: 99 rows, r2 0.947, hit rate 0.949
b3: 99 rows, r2 0.948, hit rate 0.929

See also

Notes

Given a query, this holds one chunk of it and a few sums per key, not its rows, and Polars holds what it has read of the query ahead of them. It runs the query once and reads its result 100,000 rows at a time, the chunk a bank reads by default. Each chunk is reduced to sums()’ ten numbers per slot, target and key, with the sum of the log loss under binary, and the chunks’ sums are added as merge_sums() adds them. A scan of a parquet file reads blocks of it, its row groups, ahead of a slower consumer, as many as Polars’ thread count sizes, and under Polars’ defaults that read-ahead is most of what the process holds: Cut what Polars reads ahead bounds it. Measured on macOS (an M4 Pro, py-polars 2.0.0) as the most memory the process held, 47 MiB of it Python and Polars before the call, scoring a scan of a 20-slot output written in row groups of 100,000 rows, by a key of four values: under Polars’ defaults, 494 MiB at a million rows, 1,012 MiB at four million and 1,020 MiB at sixteen million; with four threads (POLARS_MAX_THREADS=4), the read-ahead cut to one row group (POLARS_ROW_GROUP_PREFETCH_SIZE=1) and the allocator told to return freed pages at once (_RJEM_MALLOC_CONF=dirty_decay_ms:0,muzzy_decay_ms:0), the bounded settings, 205, 208 and 211 MiB. The same scores of the collected frame, read a slot at a time, held 345 MiB at a million rows under the bounded settings, the frame’s 168 MiB among them.

The scores of a query are the frame’s. A frame is scored from the same centered sums as a chunk, so while the query gives one chunk every column is the frame’s to the bit. Over many chunks each score is the frame’s within the rounding of the merge. Each chunk’s mean is rounded to a double, and that rounding enters the moments about the pooled mean at first order: about eps * |mean| / (spread * sqrt(N)) relative in a key’s m2_y, m2_pred and cov, with eps 2.2e-16 and N the key’s rows, whatever the number or size of the chunks. r2 and ic then differ from the frame’s by about that much, not relative to themselves, so a score near 0 keeps it in absolute terms (r2 by 1 - r2 times it). Measured against exact rational sums, keys of unit spread over 1,000 to 100,000 rows read in parts of 25 rows to a tenth of the key were within 1.4 times that figure: 1e-13 at a level of 1e4 over 1,000 rows, 3e-10 at a level of 1e8 over 10,000 rows. Score a target that sits far above its spread, such as a price, as a difference or a return.

A row is scored only where both the prediction and the target are values the bank would learn from: not null, NaN or infinite, and within the bank’s input bound of 1e100 in magnitude. So the rows of a warm-up, whose predictions are withheld, and the rows a model skipped never enter the scores. The bank still predicts a row whose target is null, and that row is left out here too.

A target that sits about 1, such as a plain ratio of two prices, is positive on every row, and so is its prediction, so hit_rate reads 1.0 whatever the fit. Score a return as a difference or a log ratio. Given the name alone, the loss of a Poisson sgd fit cannot be known, and the sign test reads 1.0.