Skip to content

Metrics API

RunMetadata

h2ml.evaluation.metrics.RunMetadata dataclass

Domain-specific context attached to results after CV. Keeps metadata out of the CV engine.

Attributes:

Name Type Description
schema Optional[str]

Top-level folder / feature schema / experiment name.

target Optional[str]

Target column name.

stage str

Pipeline stage that produced the row, set automatically: - "default": step 1 (all features, default params) - "reduced": step 3 (reduced features, default params) - "optimized": step 4 (reduced or full features, optimized params)

batch Optional[str]

Optional batch/run identifier (run ID, date, or any grouping label).

y_transform Optional[str]

Winning y-transform name, set by the transform sweep. None otherwise.

notes Optional[str]

Free text — useful for an experiments log.

to_dict()

Non-None fields as a dict with capitalised keys, for DataFrame columns.

compute_metrics_all

h2ml.evaluation.metrics.compute_metrics_all(cv_results, metadata=None)

Compute per-fold metrics for a list of CVResults (all models).

Models with failed folds are left out when another model completed every fold, because means over different fold sets can't be ranked against each other: a model that fails on the hard folds would look better than one scored on all of them.

Parameters:

Name Type Description Default
cv_results list[CVResult]

Output of CrossValidator.run_all().

required
metadata Optional[RunMetadata]

Optional RunMetadata to attach to every row.

None

Returns:

Type Description
DataFrame

DataFrame with one row per fold per model.

Raises:

Type Description
RuntimeError

If every model has empty folds (all CV runs failed).

aggregate_metrics

h2ml.evaluation.metrics.aggregate_metrics(fold_df, group_by_stage=True)

Aggregate per-fold results into mean ± std per model.

Parameters:

Name Type Description Default
fold_df DataFrame

Output of compute_metrics() or compute_metrics_all().

required
group_by_stage bool

If True (default), group by Stage alongside Model and other metadata columns so each (model, stage) pair gets its own row. Set False to collapse all stages per model — used in step 4 when the optimized run's folds should be averaged without a Stage breakdown.

True

Returns:

Type Description
DataFrame

DataFrame with one row per model, columns suffixed _Mean and _Std.

DataFrame

<metric>_Test_Mean is the mean of the per-fold held-out scores.

DataFrame

Regression also gets <metric>_Test_Pooled, one score over all held-out

DataFrame

rows of the completed folds. Is_Flat marks models with no prediction spread

DataFrame

in any fold.

select_best

h2ml.evaluation.metrics.select_best(agg_df, metric='AUC_Test_Mean', minimize=False, n_folds=None, fold_df=None)

Select the best model from an aggregated metrics DataFrame.

When n_folds is provided, ranking uses a lower/upper confidence bound (LCB for maximize metrics, UCB for minimize metrics):

maximize:  score = mean - std / sqrt(n_folds)   → idxmax
minimize:  score = mean + std / sqrt(n_folds)   → idxmin

This prefers models whose conservative-bound performance is highest, penalising fold variance in proportion to 1/sqrt(n_folds). When n_folds is None the raw mean is used (original behaviour).

With fold_df, std is the fold-centred std: each fold's scores minus that fold's median across candidates. Fold difficulty shared by every model (e.g. Brier's floor moving with fold prevalence) then neither penalises the model that tracks the data nor rewards one that hedges every prediction towards the middle.

Pooled columns rank by the score itself. Candidates flagged Is_Flat are excluded unless every candidate is flat.

Parameters:

Name Type Description Default
agg_df DataFrame

Output of aggregate_metrics().

required
metric str

Column name to rank by: a _Mean column (e.g. AUC_Test_Mean) or a _Pooled one (e.g. RMSE_Test_Pooled).

'AUC_Test_Mean'
minimize bool

If True, select the row with the lowest value (e.g. RMSE, MAE).

False
n_folds Optional[int]

Number of CV folds used to produce agg_df. When provided, selection uses confidence-bound scoring instead of raw mean.

None
fold_df Optional[DataFrame]

Per-fold metrics behind agg_df (same candidates). With n_folds, the bound uses the fold-centred std instead of agg_df's std.

None

Returns:

Type Description
dict

Dict with keys model_name, metric, value, row.

Raises:

Type Description
ValueError

If metric is not a column of agg_df.

RuntimeError

If all values in the metric column are NaN (every model failed all CV folds).

ranking_robustness

h2ml.evaluation.ranking.ranking_robustness(fold_df, metric, n_folds=None, selection_scoring='fold_mean')

Paired-fold and cross-metric robustness of the selection made on fold_df.

The winner is re-derived with select_best() exactly as the pipeline selects it (the pooled score, or the confidence-bound score with the fold-centred std). Each other candidate is compared with it on the folds both completed (a NaN score, e.g. AUC on a single-class fold, drops that fold from that pair only). A pooled winner can lag on the unweighted paired folds, so Winner_Gap may be negative.

Parameters:

Name Type Description Default
fold_df DataFrame

Per-fold metrics (step1_fold_df, or step 1 + step 3 concatenated).

required
metric str

Short selection metric name, e.g. "AUC" or "RMSE".

required
n_folds Optional[int]

CV folds behind fold_df; inferred from the "Fold" column when None.

None
selection_scoring str

The rule the selection used, as in PipelineConfig.

'fold_mean'

Returns:

Type Description
DataFrame

One row per candidate (key columns Model/Y_transform/Stage as present), sorted

DataFrame

by rank under metric, with columns: Test_Mean — mean held-out score Winner_Gap — mean paired difference, oriented so positive = winner better Gap_SE — Nadeau–Bengio corrected SE of Winner_Gap Folds_Won — folds where the winner scored strictly better Paired_Folds — folds both completed Indistinguishable — Winner_Gap ≤ Gap_SE (a heuristic tie, not a formal test) Is_Winner — the select_best winner, i.e. before any prefer_reduced_on_tie switch in the pipeline Is_Flat — no prediction spread in any fold; only selectable when every candidate is flat Rank — rank (1 = best) under each metric present, by the same score select_best uses

ranking_warnings

h2ml.evaluation.ranking.ranking_warnings(robust_df, metric)

Turn a ranking_robustness() table into at most two warnings: - candidates indistinguishable from the winner on paired folds - the winner ranking below 1st on the counterpart-family metric

compare_results

h2ml.evaluation.compare.compare_results(results, labels=None, metric=None, n_folds=None)

Summarise multiple PipelineResult objects as a single comparison DataFrame.

One row per result, with columns:

  • Run: label (from labels, or Run_0, Run_1, …).
  • Metric: short metric name used for Score_Mean (e.g. "AUC", "R2").
  • Best_Model: winning model class name.
  • Best_Stage: "default", "reduced" or "optimized".
  • Y_Transform: winning y-transform, or None.
  • Score_Mean: with metric, the winning stage's <metric>_Test_Mean; without it, each result's best_model_value (the pooled score for regression by default).
  • Score_Std: fold std for that metric.
  • Conservative_Bound: variance-penalised score used for ranking — Score_Mean - Score_Std / sqrt(n_folds) when higher is better, Score_Mean + Score_Std / sqrt(n_folds) when lower is better (direction from METRIC_MINIMIZE). Stable models are preferred over high-variance ones.
  • Brier_Mean: Brier_Test_Mean from the winning stage (classification only; NaN otherwise).
  • OOF_Brier: Brier score on the assembled OOF predictions, more robust than Brier_Mean (classification only; NaN otherwise).
  • N_Features: feature count in the winning feature stage.
  • Completed_Steps: pipeline steps that finished.

Parameters:

Name Type Description Default
results list['PipelineResult']

List of PipelineResult objects to compare.

required
labels Optional[list[str]]

Optional run labels (same length as results). Defaults to "Run_0", "Run_1", …

None
metric Optional[str]

Short metric name to use as the common comparison column (e.g. "AUC", "R2", "RMSE"). When provided, Score_Mean and Score_Std are read from the <metric>_Test_Mean/Std columns of each result's winning-stage agg DataFrame, making cross-run scores directly comparable even when runs were optimised on different metrics. When omitted, Score_Mean falls back to each result's best_model_value. Minimisation direction and sort order are derived automatically from METRIC_MINIMIZE — no need to pass ascending manually.

None
n_folds Optional[int]

Number of CV folds used in all runs. When provided it overrides automatic inference from the fold DataFrames, which can fail if results were loaded from disk or the fold DataFrames are absent. Conservative_Bound cannot be computed without a fold count and will fall back to Score_Mean if both this argument and inference fail.

None

Returns:

Type Description
DataFrame

DataFrame sorted by Conservative_Bound (falls back to Score_Mean when

DataFrame

fold count cannot be inferred), one row per result.

Raises:

Type Description
ValueError

If labels length does not match results, or if metric is None while the results were scored on more than one metric.

Examples:

>>> r1 = pipeline_a.run(store)
>>> r2 = pipeline_b.run(store)
>>> compare_results([r1, r2], labels=["baseline", "spatial_cv"], metric="AUC")