polars_online.eval.grid_search¶
- polars_online.eval.grid_search(source: LazyFrame | DataFrame, specs: dict[str, Any] | Sequence[dict[str, Any]] | Callable[[...], dict[str, Any]], param_grid: Mapping[str, Sequence[Any]] | None = None, *, n_splits: int = 5, gap: int = 0, scoring: Literal['mse', 'loglik'] = 'mse', chunk_size: int | None = None, threads: int | None = None) DataFrame[source]¶
Score every grid point in one pass over a stream, and choose one from the rows before each test span.
Use it to choose a spec’s settings, such as its half-life, ridge or learning rate, from the stream’s own out-of-sample residuals, and to learn what that choice is worth on rows it did not see. To compare a few specs you have already run, use
compare_specs().Parameters
sourceThe stream: a
LazyFrameor aDataFrame. It is read once,chunk_sizerows at a time, through one bank of every spec. A query is counted first, to place the spans: for a query that reads parquet files, Polars reads the count from their footers, and any other query runs once more without the bank.specsA spec, a list of specs, or a spec builder called as
specs(name, **point)for each point ofparam_grid, such asfunctools.partial(po.spec.sgd, targets=["y"], features=["x"]). The name a builder is given is the point written out, such as"learning_rate=0.01", and the spec it returns must take that name.param_gridA dict of each builder keyword’s values to try, as scikit-learn’s
ParameterGridtakes one: its keys sorted, the last varying fastest, as{"learning_rate": [0.001, 0.01]}.None, the default, whenspecsare built already. A key may not be one of the result’s own columns.n_splitsThe number of test spans, 5 by default. For 2 or more, the rows are cut as scikit-learn’s
TimeSeriesSplit(n_splits, gap=gap)cuts them: thenrows inton_splits + 1spans, the lastn_splitsofn // (n_splits + 1)rows each. 1, which scikit-learn refuses, gives one test span of the lastn // 2rows. Fewer spans make the first span, the rows the first choice is made from, longer.gapThe rows left out between the rows a choice is made from and the span it is scored on, 0 by default. Give it the number of rows of the stream a target looks ahead, so a choice never reads a row whose target was not yet known when its span started. It counts rows of the stream, as scikit-learn’s
gapcounts samples, not steps of one series: withGseries interleaved, as under a spec’sgroup, a targethsteps ahead in its series looks abouth * Grows ahead, andgapshould be that.scoring"mse", the default, the mean of(y - pred)**2, lower better; or"loglik", the mean log predictive density of a row, higher better, read from theloglikfield thatbocpd,hmmanddecowrite.chunk_sizeThe rows read at a time, as
fit_predict_batches()takes it.None, the default, reads a query 100,000 rows at a time and takes aDataFramewhole, as that method does.threadsThe bank’s threads, as
ModelBanktakes them.None, the default, runs on the threads banks share, one per core unlessPOLARS_ONLINE_MAX_THREADSis set.
Returns
A
DataFramethat holds, for each target, one row per slot (one target at one grid point of a spec’s own grid, or a spec’semit_selectedoremit_averagedprediction) in grid order, then the row of the choice:kindWhat the row is:
"candidate", a slot to choose among;"selected"or"averaged", a spec’semit_selectedoremit_averagedprediction, scored beside the others and never chosen;"choice", what choosing from the rows before each span scored on that span. Select it withpl.col("kind") == "choice".specThe spec’s name. Null on the choice’s row, which runs whichever slot each span chose, from any spec.
- the keys of
param_grid, thenhalf_life,ridge,feature_setandpenalty The slot’s grid point: the point of
param_grid, and each setting of the specs’ own grids that varies among the slots. Null on the choice’s row.slot,targetThe output field scored, and its target (null under
scoring="loglik").slotis null on the choice’s row, andtargetnames the target the choice is for.nThe rows scored, over the test spans.
mseorloglikThe score over those rows.
rank1 for the slot with the best score over the test spans, ties sharing the lower rank: the grid point to run. Since it is chosen on the rows it reports, its score is optimistic. Null on every row but a
"candidate".folds_chosenHow many test spans the choice ran the slot on. A tie goes to the first in grid order. Null on every row but a
"candidate".
The choice’s row is the out-of-sample score of a rule: run the slot best over the rows read before each span (see Notes), and score it on the span. How far it falls short of the rank-1 score is the rule’s regret against the best grid point in hindsight. With no
gapit cannot be negative, since following the leader never beats the best fixed choice over the same spans; it is an upper bound on how much the rank-1 score overstates, and it holds as well what the rule lost by choosing from fewer rows, and the first choice from the first span’s rows, where every model starts up.Raises
TypeErrorsourceis not aLazyFrameor aDataFrame;specsis not a spec, a list of specs or a builder;param_gridis not a dict; a key is not a str; or a value is not a list.RefusedValueErrorparam_gridis given beside specs already built, or is empty, or one of its lists is empty. It is both aValueErrorand aTypeError.WrongTypeErrorn_splits,gaporchunk_sizeis not a whole number. It is both aTypeErrorand aValueError.ColumnNotFoundErrorA spec’s target has no column in the stream. A formula target never has one, since the bank computes it as it learns and does not write it out, so such a spec cannot be scored here. It is both a
ValueErrorand Polars’ColumnNotFoundError.ValueErrorWhen:
scoringis neither word;n_splitsis below 1,gapbelow 0, orchunk_sizebelow 1;a builder returns a spec not named by its first argument;
a
param_gridkey is one of the result’s columns;a spec has nothing to score: no prediction of a target under
"mse", or nologlikunder"loglik";the slots score different data, which no rank can compare: under
"loglik", specs that model different columns (score each set in a call of its own); under"mse", a target name that two specs read from different columns (name each target after what it reads, withpolars_online.target());a query gives a number of rows other than its count when run;
the first choice has no row to read. The error names the rows and the remedy. The stream is too short for its spans,
gapis as long as the first span, or no row of the first span has every slot’s prediction, as when a warm-up (min_weight,warm_rows) outlasts it.
- Whatever the bank raises
For the specs or
threads, or for a chunk.
Examples
This code reads
ticks.parquetfrom Example data:import functools sgd = functools.partial(po.spec.sgd, targets=["y"], features=["x0", "x1"], half_life=1000.0) table = po.eval.grid_search( pl.scan_parquet("ticks.parquet"), sgd, {"learning_rate": [0.001, 0.01, 0.1]}, n_splits=4 ) points = table.filter(pl.col("kind") == "candidate") # one row per grid point for rate, mse, rank in points.select("learning_rate", "mse", "rank").iter_rows(): print(f"learning_rate={rate}: mse {mse:.3f}, rank {rank}") choice = table.filter(pl.col("kind") == "choice") # the score of choosing print(f"choosing from earlier rows: mse {choice['mse'][0]:.3f}")
learning_rate=0.001: mse 3.136, rank 3 learning_rate=0.01: mse 0.386, rank 2 learning_rate=0.1: mse 0.304, rank 1 choosing from earlier rows: mse 0.304
See also
compare_specs(), the scores of specs already run, side by side.Choose a model’s settings from the stream’s own errors, the pattern this follows, for every setting.
Notes
Why the choice is scored apart. Each row’s prediction is made before the row is learned, so the stream’s own residuals are out-of-sample, and every grid point is scored on the same rows. But choosing the grid point whose error is lowest over those rows, and reporting that error, is optimistic: each error is the grid point’s true error plus noise, and the minimum picks the grid point whose noise happened to run lowest. So the choice is scored too. Before each test span, the slot with the best score over the rows read before it (
gaprows short of it) is chosen, and scored on the span. The first choice reads the first span, the only rows before it. Each later choice reads the test spans’ rows before it, the rows the rank reads, and not the first span’s: there every model starts up, and a model whose first errors were large, as one with more coefficients to learn, would weigh them on every choice and be passed over on spans it was best on. Where the gap leaves no test row before a span, or no row there that every slot predicts, its choice reads from row 0:size = n // (n_splits + 1) start_k = n - (n_splits - k) * size k = 0 .. n_splits - 1 from_k = start_0 where start_k - gap > start_0, else 0 chosen_k = argbest over candidate slots s of score(s, rows [from_k, start_k - gap)) choice = score(chosen_k on rows [start_k, start_k + size), pooled over k)
What is scored. The slots are every prediction a spec writes, one per target and grid point of its own grid (
half_life,ridge,feature_setsorpenaltiesas lists), across all the specs. A row counts for a target only where every slot of that target has a value and the target is present. So the grid points are compared on the same rows, and the rows any slot withholds while it warms up count for none. Every row weighs alike: a spec’sweightcolumn is not read here, so a row of weight 0 is scored like any other. To leave such rows out of the score, score the specs chosen withsums()’weight. Underscoring="loglik", the sum of a stream’s log densities, each read before its row is learned, is its log marginal likelihood (the prequential score). It is the criterion that comparesbocpd’s hazards and priors. Forhmm’s number of states, see the table under What this cannot choose.Memory and rounding. Only three numbers per slot are kept (its summed score, the rows it is scored on and the rows it predicts) for each run of rows between the places a test span starts or its choice stops, with each target’s count of rows. So memory is the bank’s state and one chunk, however long the stream. These sums are added a chunk at a time, so the scores are the same to rounding whatever
chunk_sizeis, and the choices are the same unless two grid points tie to rounding.What this cannot choose. Three settings have no out-of-sample score this function can choose them by. One model writes no score, one writes a score that was measured not to find the setting, and for one the squared error would push it toward the loss it exists to replace:
setting
why this does not choose it
what to do
kmeans’n_clustersIts only score is
dist, the distance to the nearest center, and that falls as clusters are added even on rows not yet learned: on three planted clusters, its mean square on the second half went 1.18, 0.45, 0.38, 0.32 and 0.26 at two to six clusters. It writes no likelihood.Choose it by what the clusters are for, or from a Gram or a sample with a criterion of your own.
hmm’sn_componentshmmwritesloglik, but on a stream planted with three Gaussian states of spread 1 at means −2, 0 and 2, four states scored −1.60 a row on the second half and three scored −1.67, so the score is not shown to find the number of states.Read
n_componentsfrom what the states mean.huber_deltaIt is the cut, in units of the residuals’ spread, past which a row’s residual counts linearly. The default 1.345 keeps 95% of least squares’ efficiency when the noise is normal, and choosing it by squared error would push it toward least squares.
Keep 1.345, or choose it by a robust loss of your own over
unpack()’s residuals.