Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
rheon 2.0.0
rheon 2.0.0
  • rheon
    • rheon.polars.ModelBank
      • rheon.polars.ModelBank.specs
      • rheon.polars.ModelBank.threads
      • rheon.polars.ModelBank.rows_fed
      • rheon.polars.ModelBank.groups
      • rheon.polars.ModelBank.drop_groups
      • rheon.polars.ModelBank.skip_learned
      • rheon.polars.ModelBank.fit_predict
      • rheon.polars.ModelBank.predict
      • rheon.polars.ModelBank.fit_predict_arrow
      • rheon.polars.ModelBank.predict_arrow
      • rheon.polars.ModelBank.fit_predict_batches
      • rheon.polars.ModelBank.fit
      • rheon.polars.ModelBank.coef
      • rheon.polars.ModelBank.last_row
      • rheon.polars.ModelBank.summary
      • rheon.polars.ModelBank.describe
      • rheon.polars.ModelBank.gram
      • rheon.polars.ModelBank.marginal
      • rheon.polars.ModelBank.audit
      • rheon.polars.ModelBank.closed_groups
      • rheon.polars.ModelBank.check
      • rheon.polars.ModelBank.solve_failures
      • rheon.polars.ModelBank.output_fields
      • rheon.polars.ModelBank.save
      • rheon.polars.ModelBank.save_bytes
      • rheon.polars.ModelBank.write_json
      • rheon.polars.ModelBank.load
      • rheon.polars.ModelBank.load_bytes
    • rheon.polars.fit_predict
    • rheon.polars.predict
    • rheon.polars.unnest
    • rheon.target
    • rheon.Target
    • rheon.FormulaTarget
    • rheon.ArrowStruct
    • rheon.thread_pool_size
    • rheon.native_version
    • rheon.schema_version
    • rheon.ColumnNotFoundError
    • rheon.OutputColumnNotFoundError
    • rheon.WrongTypeError
    • rheon.RefusedValueError
    • rheon.RheonWarning
    • rheon.ReadinessWarning
    • rheon.polars.OrderNotGuaranteedWarning
    • rheon.polars.ConsumedSourceWarning
    • rheon.RheonDeprecationWarning
    • rheon.UnstableWarning
  • rheon.spec
    • rheon.spec.ewridge
    • rheon.spec.rls
    • rheon.spec.lasso
    • rheon.spec.kalman
    • rheon.spec.sgd
    • rheon.spec.pa
    • rheon.spec.ftrl
    • rheon.spec.glm
    • rheon.spec.holt
    • rheon.spec.huber
    • rheon.spec.quantile
    • rheon.spec.expectile
    • rheon.spec.ew_cov
    • rheon.spec.marginal
    • rheon.spec.deco
    • rheon.spec.rcov
    • rheon.spec.audit
    • rheon.spec.hmm
    • rheon.spec.garch
    • rheon.spec.seqtest
    • rheon.spec.corrchange
    • rheon.spec.bocpd
    • rheon.spec.hawkes
    • rheon.spec.kmeans
    • rheon.spec.micro
    • rheon.spec.ew_class
    • rheon.spec.output_fields
    • rheon.spec.output_index
    • rheon.spec.coef_fields
    • rheon.spec.coef_index
  • The rheon namespaces
    • LazyFrame.rheon
      • LazyFrame.rheon.fit_predict
      • LazyFrame.rheon.predict
      • LazyFrame.rheon.unnest
      • LazyFrame.rheon.with_windows
    • DataFrame.rheon
      • DataFrame.rheon.fit_predict
      • DataFrame.rheon.predict
      • DataFrame.rheon.unnest
      • DataFrame.rheon.with_windows
  • rheon.polars.stream
    • rheon.polars.stream.with_windows
    • rheon.polars.stream.embargo
    • rheon.polars.stream.refresh_time
    • rheon.polars.stream.merge
    • rheon.polars.stream.save_checkpoint
    • rheon.polars.stream.load_checkpoint
  • rheon.polars.ops
    • rheon.polars.ops.ewm_mean
    • rheon.polars.ops.ewm_sum
    • rheon.polars.ops.ewm_var
    • rheon.polars.ops.ewm_std
    • rheon.polars.ops.ewm_quantile
    • rheon.polars.ops.ewm_rate
    • rheon.polars.ops.increment
  • rheon.polars.eval
    • rheon.polars.eval.unpack
    • rheon.polars.eval.metrics
    • rheon.polars.eval.window_metrics
    • rheon.polars.eval.sums
    • rheon.polars.eval.merge_sums
    • rheon.polars.eval.from_sums
    • rheon.polars.eval.compare_specs
    • rheon.polars.eval.grid_search
    • rheon.polars.eval.diebold_mariano
    • rheon.polars.eval.clark_west
    • rheon.polars.eval.seqtest
  • rheon.gram
    • rheon.gram.Gram
    • rheon.gram.merge
    • rheon.gram.from_row
    • rheon.gram.subset
    • rheon.gram.correlation
    • rheon.gram.solve
    • rheon.gram.lasso_path
    • rheon.gram.lars_path
    • rheon.gram.lars_paths
    • rheon.gram.solve_subsets
    • rheon.gram.coef_stats
    • rheon.gram.vif
    • rheon.gram.condition
  • rheon.corr
    • rheon.corr.nearest
    • rheon.corr.shrink
    • rheon.corr.to_z
    • rheon.corr.from_z
    • rheon.corr.fisher_se
    • rheon.corr.equicorr
    • rheon.corr.equicorr_row
    • rheon.corr.equicorr_loglik
    • rheon.corr.absorption
    • rheon.corr.absorption_shift
    • rheon.corr.spectral
    • rheon.corr.from_spectral
    • rheon.corr.block_means
    • rheon.corr.from_blocks
    • rheon.corr.mp_edge
    • rheon.corr.mp_density
    • rheon.corr.signal_share
    • rheon.corr.loss
    • rheon.corr.epps_invert
  • rheon.polars.sim
    • rheon.polars.sim.regimes
Back to top
View this page

rheon.polars.eval.grid_search¶

rheon.polars.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

source

The stream: a LazyFrame or a DataFrame. It is read once, chunk_size rows 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.

specs

A spec, a list of specs, or a spec builder called as specs(name, **point) for each point of param_grid, such as functools.partial(rp.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_grid

A dict of each builder keyword’s values to try, as scikit-learn’s ParameterGrid takes one: its keys sorted, the last varying fastest, as {"learning_rate": [0.001, 0.01]}. None, the default, when specs are built already. A key may not be one of the result’s own columns.

n_splits

The 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: the n rows into n_splits + 1 spans, the last n_splits of n // (n_splits + 1) rows each. 1, which scikit-learn refuses, gives one test span of the last n // 2 rows. Fewer spans make the first span, the rows the first choice is made from, longer.

gap

The 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 gap counts samples, not steps of one series: with G series interleaved, as under a spec’s group, a target h steps ahead in its series looks about h * G rows ahead, and gap should 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 the loglik field that bocpd, hmm and deco write.

chunk_size

The 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 a DataFrame whole, as that method does.

threads

The bank’s threads, as ModelBank takes them. None, the default, runs on the threads banks share, one per core unless RHEON_MAX_THREADS is set.

Returns

A DataFrame that holds, for each target, one row per slot (one target at one grid point of a spec’s own grid, or a spec’s emit_selected or emit_averaged prediction) in grid order, then the row of the choice:

kind

What the row is: "candidate", a slot to choose among; "selected" or "averaged", a spec’s emit_selected or emit_averaged prediction, scored beside the others and never chosen; "choice", what choosing from the rows before each span scored on that span. Select it with pl.col("kind") == "choice".

spec

The spec’s name. Null on the choice’s row, which runs whichever slot each span chose, from any spec.

the keys of param_grid, then half_life, ridge, feature_set and penalty

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, target

The output field scored, and its target (null under scoring="loglik"). slot is null on the choice’s row, and target names the target the choice is for.

n

The rows scored, over the test spans.

mse or loglik

The score over those rows.

rank

1 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_chosen

How 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 gap it 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

TypeError

source is not a LazyFrame or a DataFrame; specs is not a spec, a list of specs or a builder; param_grid is not a dict; a key is not a str; or a value is not a list.

RefusedValueError

param_grid is given beside specs already built, or is empty, or one of its lists is empty. It is both a ValueError and a TypeError.

WrongTypeError

n_splits, gap or chunk_size is not a whole number. It is both a TypeError and a ValueError.

ColumnNotFoundError

A 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 ValueError and Polars’ ColumnNotFoundError.

ValueError

When:

  • scoring is neither word;

  • n_splits is below 1, gap below 0, or chunk_size below 1;

  • a builder returns a spec not named by its first argument;

  • a param_grid key is one of the result’s columns;

  • a spec has nothing to score: no prediction of a target under "mse", or no loglik under "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, with rheon.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, gap is 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.parquet from Example data:

import functools

sgd = functools.partial(rp.spec.sgd, targets=["y"], features=["x0", "x1"], half_life=1000.0)
table = rp.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 (gap rows 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_sets or penalties as 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’s weight column 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 with sums()’ weight. Under scoring="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 compares bocpd’s hazards and priors. For hmm’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_size is, 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_clusters

Its 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’s n_components

hmm writes loglik, 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_components from what the states mean.

huber_delta

It 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.

Next
rheon.polars.eval.diebold_mariano
Previous
rheon.polars.eval.compare_specs
Copyright © Hans Gilde
Made with Sphinx and @pradyunsg's Furo
On this page
  • rheon.polars.eval.grid_search
    • grid_search()