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 ownemit_metrics.Parameters
dfA 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).specThe 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 havebinaryread from the spec’s loss.groupOne key column, as a spec’s
groupis, or a list of them, to score each key apart.None, the default, scores every row together.targetsunpack()’s: the columns the name-based rule may read as targets.min_samplesThe fewest rows a key is scored on, 30 by default. A key with fewer rows keeps its row, with
nfilled and every score null, as Polars’rolling_*andewm_*give null below theirmin_samples.binaryScore the slots as a classifier’s:
preda probability andya 0/1 target, the output of ansgdorftrlfit withloss="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
DataFramewith one row perslot,targetandgroupkey, 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.nThe rows scored.
r2The out-of-sample R², against the target’s mean over the rows scored. Null where the target never varied.
icThe correlation of the prediction with the target. Null where either never varied.
hit_rateThe share of rows whose sign the prediction got right, over the rows where neither
ynorpredis 0, as the bank’semit_metricscounts them. Null where no row is counted. A Poissonsgdfit (loss="poisson") has no sign to hit, so the bank nulls itshit_rate, and so does this, given the spec dict.mse,rmseThe 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 ofr2The 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 ofhit_rateThe share of rows on the right side of 0.5. Every row is counted.
log_lossThe mean of
-(y*ln(p) + (1-y)*ln(1-p)), withpclipped to[1e-15, 1 - 1e-15], so a confident miss is a large number and not an infinity.
ickeeps its name underbinary: on a 0/1 target it is the point-biserial correlation, the same formula.rmseis then the root of the Brier score.Raises
Whatever
unpack()raises fordfandspec, and:ColumnNotFoundErrordfdoes not have agroupcolumn. It is both Polars’ColumnNotFoundErrorand aValueError.ValueErrorA
groupcolumn is named like a column the scores make, inRESERVEDorSUM_FIELDS, a score’s name, orwindow_start: namedy, it would key the scores by the target’s value. Rename it. Or, underbinary, a scored row’s target is not 0 or 1, which a query raises from the chunk that holds it. Ormin_samplesis below 0.WrongTypeErrorA
groupcolumn is anObject, which a query’s chunks cannot be matched by: cast it toStringorCategorical. Ormin_samplesis not a whole number. It is both aTypeErrorand aValueError.
A query is refused as its result would be, with the same message, before it runs.
Examples
This code reads
dffrom 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
window_metrics(), the same scores in windows of the clock.compare_specs(), the same scores for several specs in one table.sums()andfrom_sums(), the same scores one chunk at a time.Is the model working?, the diagnostics a spec writes beside its predictions.
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 underbinary, and the chunks’ sums are added asmerge_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’sm2_y,m2_predandcov, witheps2.2e-16 andNthe key’s rows, whatever the number or size of the chunks.r2andicthen differ from the frame’s by about that much, not relative to themselves, so a score near 0 keeps it in absolute terms (r2by1 - r2times 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_ratereads 1.0 whatever the fit. Score a return as a difference or a log ratio. Given the name alone, the loss of a Poissonsgdfit cannot be known, and the sign test reads 1.0.