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
|
|
DataFrame
|
Regression also gets |
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:
|
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 (fromlabels, orRun_0,Run_1, …).Metric: short metric name used forScore_Mean(e.g."AUC","R2").Best_Model: winning model class name.Best_Stage:"default","reduced"or"optimized".Y_Transform: winning y-transform, orNone.Score_Mean: withmetric, the winning stage's<metric>_Test_Mean; without it, each result'sbest_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 fromMETRIC_MINIMIZE). Stable models are preferred over high-variance ones.Brier_Mean:Brier_Test_Meanfrom the winning stage (classification only; NaN otherwise).OOF_Brier: Brier score on the assembled OOF predictions, more robust thanBrier_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 |
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: