Pipeline API¶
H2MLPipeline¶
h2ml.pipeline.pipeline.H2MLPipeline
¶
Orchestrates the full h2ml 4-step workflow.
Step 1 — CV all models (× all y-transforms) on all features → select best (model [, transform]) Step 2 — SHAP importance + correlation-based feature reduction using winning model/transform Step 3 — CV all models on reduced features (winning transform only) → select best stage Step 4 — Hyperparameter optimization + final CV → select overall best
Y-transform sweep
Pass a list of transform names to run() to sweep them in step 1, instead of
running the full pipeline once per transform. Steps 2–4 use the winning one.
Partial runs
run_step1_only()— step 1 only, quick model screeningrun_step1_to_step2()— steps 1–2, inspect SHAP importance / reduced featuresrun_step1_to_step3()— steps 1–3, full selection without HPOrun_from_step3()— resume from a steps 1–2 result (steps 3–4)run_step4_only()— re-run HPO on a steps 1–3 result
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PipelineConfig
|
Pipeline configuration. |
required |
models
|
Optional[list[ModelWrapper]]
|
Override the default model registry list. When None, build_models() constructs a task-appropriate set from the registry. |
None
|
metadata
|
Optional[RunMetadata]
|
Optional experiment labels (schema, target, batch) that appear as columns in fold/agg DataFrames. When None, only stage is set. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the resolved model list is empty or two models share a name. |
Examples:
>>> pipeline = H2MLPipeline(config=PipelineConfig())
>>> result = pipeline.run(store)
>>> result.summary()
run(store, transforms=None)
¶
Execute the full 4-step pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
PipelineData
|
Input features and target. |
required |
transforms
|
Optional[Iterable[str]]
|
Optional sequence of y-transform names to sweep (regression only). When provided, step 1 runs all models × all transforms and selects the best (model, transform). Step 3 re-runs only the winning transform on the reduced feature set. Defaults to None (no transform sweep). |
None
|
Returns:
| Type | Description |
|---|---|
PipelineResult
|
PipelineResult with all four steps completed. |
run_from_step3(result, transform_stores=None)
¶
Resume from step 3 using a PipelineResult from run_step1_to_step2(). Requires result.features, result.features_reduced and result.best_model_name to be set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
PipelineResult
|
PipelineResult carrying steps 1-2 state. |
required |
transform_stores
|
Optional[dict[str, PipelineData]]
|
Pre-built y-transform stores; rebuilt from result.features when None. |
None
|
Returns:
| Type | Description |
|---|---|
PipelineResult
|
PipelineResult with steps 3-4 completed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If features, features_reduced, best_model_name, or selector is missing from result. |
run_step1_only(store, transforms=None)
¶
CV all models on all features and select the best — quick model screening. After: result.best_model_name, result.step1_agg_df.
Returns:
| Type | Description |
|---|---|
PipelineResult
|
PipelineResult with step 1 completed. |
run_step1_to_step2(store, transforms=None)
¶
Run steps 1-2. After: result.selector.importance_summary() / result.features_reduced.feature_names
Returns:
| Type | Description |
|---|---|
PipelineResult
|
PipelineResult with steps 1-2 completed. |
run_step1_to_step3(store, transforms=None)
¶
Run steps 1-3 (model selection on full and reduced features) without HPO. Useful for inspecting best_stage and comparing models before committing to step 4's compute cost. After: result.best_model_name, result.best_stage, result.step3_agg_df
Returns:
| Type | Description |
|---|---|
PipelineResult
|
PipelineResult with steps 1-3 completed (no HPO). |
run_step4_only(result, transform_stores=None)
¶
Run only step 4 (HPO + final CV) on a result that already has steps 1–3 complete.
Typical use: load a saved result, then call this to add or redo optimisation without repeating CV on all models.
The result must have features, features_reduced, selector,
best_model_name, best_stage and best_model_value set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
PipelineResult
|
PipelineResult with steps 1-3 complete. |
required |
transform_stores
|
Optional[dict[str, PipelineData]]
|
Pre-built y-transform stores; rebuilt from result.features when None. |
None
|
Returns:
| Type | Description |
|---|---|
PipelineResult
|
PipelineResult with step 4 completed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any of the required steps 1-3 fields are missing. |
PipelineConfig¶
h2ml.pipeline.pipeline.PipelineConfig
dataclass
¶
Configuration for H2MLPipeline.
Attributes:
| Name | Type | Description |
|---|---|---|
task_type |
TaskType | str
|
Task to run. Accepts the string "classification" or "regression" (case-insensitive) or a TaskType member; normalised to TaskType in post_init. |
metric |
str
|
Short metric name used for model selection (steps 1–3) and HPO (step 4). Minimisation direction and sort order are derived automatically — no need to set a separate flag. Classification: "AUC" (default), "AUCPR", "F1", "LogLoss", "Brier". Regression: "R2" (default), "MAE", "RMSE", "PoissonDev" (non-negative counts or rates such as CPUE). |
n_splits |
int
|
CV folds used in steps 1–3 for model screening and feature selection. More folds = more reliable estimates, higher cost. Default: 5. |
random_state |
int
|
Seed for fold splitting and model initialisation. Default: 42. |
verbose |
bool
|
Log step-by-step progress. Default: False. |
n_jobs |
int
|
Worker processes used to CV models in parallel (steps 1 and 3) and to explain row chunks in step 2's SHAP pass for model-agnostic explainers (SVC/SVR with non-linear kernels, KNN, ...). -1 uses all cores. Lower it when memory is the constraint rather than CPU — each worker holds its own copy of the model being fitted — or to leave headroom on a shared machine. Must not be 0. Default: -1. |
corr_threshold |
float
|
(Step 2) Drop a feature when its correlation with any already-retained feature exceeds this value in Pearson, Spearman, or Kendall. Range (0, 1]. Default: 0.7. |
min_features |
int
|
(Step 2) Hard lower bound on features kept after the correlation filter; prevents the selector from removing everything. Default: 1. |
max_vif |
Optional[float]
|
(Step 2) After the correlation filter, drop the lowest-ranked feature whose variance inflation factor exceeds this value, repeating until none does. Catches features that are linear combinations of several retained ones, which pairwise correlations miss. Must be > 1 (5 or 10 are common). None skips it. Default: None. |
n_trials |
int
|
(Step 4) Total Optuna trials budget. Each trial evaluates one hyperparameter configuration using opt_n_splits-fold CV, so total model fits = n_trials × opt_n_splits (plus a final n_splits-fold CV on the best params). Default: 50. |
opt_n_splits |
int
|
(Step 4) CV folds inside each Optuna trial. Fewer folds make each trial faster at the cost of a noisier score estimate. Should be ≥ n_splits // 2 to avoid unreliable HPO scores; setting it equal to n_splits gives unbiased estimates at higher compute cost. Default: 3. |
n_hpo_repeats |
int
|
(Step 4) Number of independent HPO runs with different fold seeds. The repeat with the highest best_value is kept. Trials are divided evenly across repeats: trials_per_repeat = max(1, n_trials // n_hpo_repeats), so the total fit count stays constant. Default: 1. |
spatial_cv_method |
str
|
Splitting strategy when spatial coordinates are provided (all spatial-CV fields are ignored when store.coords is None). "block" — quantile-grid blocking; fast, no clustering. "spcv" — Agglomerative Hierarchical Clustering + cluster ensemble; more spatially coherent folds, slower. Default: "spcv". |
spatial_cv_metric |
SpatialMetric
|
Distance metric used by both splitters. "euclidean" — projected coordinates (metres). "haversine" — geographic lat/lon in decimal degrees. Default: "euclidean". |
n_blocks_per_fold |
int
|
Number of spatial blocks assigned to the test set per fold in the block splitter. Default: 5. |
time_bin_resolution |
str
|
Temporal granularity for binning dates in local conformal calibration (compound block × time cells); not used by CV. "month" — 12 bins (Jan…Dec). "season" — 4 bins (DJF, MAM, JJA, SON). Default: "month". |
ahc_threshold |
Optional[float]
|
Distance threshold for cutting the AHC dendrogram in SPCVSplitter. Derived automatically from the data when None. Default: None. |
pca_components |
float
|
Variance fraction retained by PCA applied to block covariates in SPCVSplitter stage 2 (after AHC, before the cluster ensemble). Default: 0.95. |
exact_max_samples |
int
|
Sample count below which exact scipy AHC is used; above this an approximate sklearn AHC (k-NN graph) is used instead. Default: 5 000. |
knn_neighbors |
int
|
k for the k-NN connectivity graph in approximate AHC. Default: 15. |
spcv_use_target |
bool
|
Include the target view when SPCVSplitter assigns CV folds. False assigns folds from location and covariates alone, so targets on the same rows and X share folds. Holdouts and nested_cv outer folds never use the target. Default: True. |
handle_imbalance |
bool | Literal['auto']
|
(Classification only) Inject class_weight="balanced" into every model whose registry entry has supports_class_weight=True. True — always; False — never; "auto" — only when the minority-class ratio of the input target is below IMBALANCE_RATIO_THRESHOLD (0.1), decided when a run starts. No effect on regression tasks. Default: False. |
prefer_reduced_on_tie |
bool
|
In step 3, when the winner uses all features ("default" stage) but a reduced-feature candidate is indistinguishable from it on paired folds (within one Nadeau–Bengio corrected SE — the Indistinguishable flag of ranking_robustness), select the best-ranked such reduced candidate instead (1-SE rule favouring the simpler feature set). Skipped when the reduced set kept every feature. Each switch is logged and recorded in cv_warnings. Default: False. |
select_features_in_folds |
bool
|
(Step 3) Re-run the step-2 selector on each CV fold's training rows and score the reduced candidates on those per-fold feature sets, so the default-vs-reduced comparison is not biased by a feature set chosen on every row. Step 4's acceptance CV uses the same per-fold sets when the reduced stage won. The deployed feature set is still step 2's. Costs about n_splits extra step-2 runs. Default: False. |
selection_scoring |
Literal['pooled', 'fold_mean']
|
How regression candidates are scored in steps 1, 3 and 4, including Optuna trials. "pooled" — one score over all out-of-fold rows, so folds count by their size. "fold_mean" — mean of the per-fold scores with a fold-spread penalty. Classification always uses the fold mean. Default: "pooled". |
mean_correction |
Optional[Literal['ratio']]
|
(Regression, log/sqrt transforms) "ratio" — build_final_model rescales predictions so their total matches the observed total on the out-of-fold rows. Totals improve, but rowwise error usually grows. CV scores, selection and holdout_df stay uncorrected. None — no correction. Default: None. |
holdout_frac |
float
|
Fraction of rows set aside before step 1 and scored once on the final selected configuration — an estimate no selection step has seen. Steps 1–4 run on the remaining (dev) rows. With a holdout, conformal calibration uses the holdout residuals and local conformal calibration is skipped. Range [0, 0.5]; 0 disables it. Default: 0.0. |
holdout_strategy |
Literal['auto', 'random', 'time']
|
How holdout rows are chosen. "auto" — whole spatial blocks, drawn at random up to holdout_frac, when store.coords is set, else random (stratified for classification). "random" — random even with coords. "time" — the latest rows by store.times. Default: "auto". |
holdout_refit |
Literal['dev', 'all']
|
Rows build_final_model fits on when a holdout exists. "dev" — the dev rows only, so the holdout score and conformal coverage describe the deployed model exactly. "all" — dev + holdout rows; more data, but both are then approximate. Default: "dev". |
holdout_min_minority |
Optional[int]
|
Drop the holdout, and run as if holdout_frac=0, when it would hold fewer rows than this of its rarest class (classification) or of non-zero rows (regression). Its rows then return to the dev set, conformal calibration uses CV residuals, and a [holdout] warning records it. The count is taken on the actual split, so spatial blocks are counted as drawn. None — always keep the holdout. Default: None. |
PipelineResult¶
h2ml.pipeline.pipeline.PipelineResult
dataclass
¶
Container for all artifacts produced by H2MLPipeline.
Fields are populated progressively as steps complete; check completed_steps to see which steps have run. Use summary() to compare all stages at once and build_final_model() to refit on the full training set.
Attributes:
| Name | Type | Description |
|---|---|---|
features |
Optional[PipelineData]
|
Input PipelineData (full feature set). |
step1_fold_df |
Optional[DataFrame]
|
Per-fold metrics from step 1 (all models × transforms). |
step1_agg_df |
Optional[DataFrame]
|
Aggregated (mean ± std) step-1 metrics per model. |
best_model_name |
Optional[str]
|
Winning model name after step 1. |
best_model_value |
Optional[float]
|
Best model's score on the selection metric, under selection_scoring. |
best_model_std |
Optional[float]
|
Fold std of the best model's selection metric. |
selection_scoring |
str
|
Scoring rule this result selected with ("pooled" or "fold_mean"), kept when resuming. Results saved before the option load as "fold_mean". |
features_reduced |
Optional[PipelineData]
|
PipelineData after step-2 feature reduction. |
selector |
Optional[FeatureSelector]
|
Fitted FeatureSelector (SHAP + correlation filter). |
step3_fold_df |
Optional[DataFrame]
|
Per-fold metrics from step 3 (reduced features). |
step3_agg_df |
Optional[DataFrame]
|
Aggregated step-3 metrics per model. |
best_stage |
Optional[str]
|
Winning stage after step 3: "default" or "reduced". |
best_feature_stage |
Optional[str]
|
Feature stage step 4 is built on — "default" or "reduced", never "optimized". |
step3_reduced_stores |
Optional[dict[str, 'PipelineData']]
|
Cached reduced PipelineDatas keyed by transform name ("" for no transform). Not persisted. |
best_base_estimator |
Any
|
Unfitted clone of the winning model's estimator, exactly as CV ran it (constructor args and injected class_weight included). build_final_model refits clone(this) with best_params set on top. |
best_requires_scaling |
bool
|
Whether the winning model was scaled in CV. |
best_params |
Optional[dict]
|
Overrides applied to best_base_estimator in step 4 (tuned params plus fixed ones such as class_weight). None when step 4 did not run. Results saved before best_base_estimator existed hold full constructor kwargs. |
step4_fold_df |
Optional[DataFrame]
|
Per-fold metrics from the step-4 final CV. |
step4_agg_df |
Optional[DataFrame]
|
Aggregated step-4 metrics. |
step1_cv_result |
Optional[list[CVResult]]
|
Raw step-1 CVResults — preserved for plots/persistence. |
step3_cv_result |
Optional[list[CVResult]]
|
Raw step-3 CVResults. |
step4_cv_result |
Optional[CVResult]
|
Raw step-4 CVResult. |
y_transform |
Optional[str]
|
Winning y-transform name (set when run() sweeps transforms). |
cv_type |
str
|
"spatial" when store.coords was set, else "random". |
spatial_cv_metric |
str
|
Distance metric forwarded from PipelineConfig; used by build_final_model to build LocalConformalCalibration. |
time_bin_resolution |
str
|
Temporal bin resolution forwarded from PipelineConfig. |
cv_warnings |
list[str]
|
Warnings for models with ≥1 failed CV fold (steps 1 & 3), plus data conditions that make the selection metric unreliable (checked in step 1), ranking-robustness flags (steps 1 & 3), and any prefer_reduced_on_tie switch (step 3). All but the switch are advisory. |
class_weight_balanced |
bool
|
True when CV ran with class_weight="balanced" injected (handle_imbalance resolved active); build_final_model re-applies it when step 4 did not produce best_params. |
metric |
Optional[str]
|
Short selection metric name, e.g. "AUC" or "R2". |
splitter |
Any
|
Splitter built once in step 1 and reused in steps 3-4. |
step3_fold_features |
Optional[list[list[str]]]
|
Feature names selected on each step-3 CV fold's training rows (select_features_in_folds=True), indexed like the splitter's folds; None otherwise. |
holdout_store |
Optional[PipelineData]
|
Raw rows set aside by holdout_frac; None without a holdout. features then holds only the dev rows steps 1–4 ran on. |
holdout_idx |
Optional[ndarray]
|
Row indices of holdout_store in the store passed to run(). |
holdout_strategy |
Optional[str]
|
Resolved holdout strategy: "spatial", "random" or "time". |
holdout_refit |
str
|
"dev" or "all" — rows build_final_model fits on (from PipelineConfig.holdout_refit). |
holdout_cv_result |
Optional[CVResult]
|
One-fold CVResult: the final configuration fitted on the dev rows and scored on the holdout rows. |
holdout_df |
Optional[DataFrame]
|
Holdout metrics, same _Mean columns as the agg DataFrames (_Std is NaN — there is one fold). |
best_cv_result
property
¶
CVResult of the selected configuration: step 4 only when the tuned params were kept, otherwise the winner's step-3 (reduced) or step-1 (default) CVResult.
completed_steps
property
¶
List of completed step numbers, e.g. [1, 2, 3] after run_step1_to_step3().
oof_labels
property
¶
True labels paired with oof_predictions.
oof_predictions
property
¶
Out-of-fold predictions for the best model's CV result. Classification: positive-class probability (binary) or probability matrix (multiclass). Regression: predicted values. None if no CV result is available.
build_final_model()
¶
Fit the best model on the full training dataset and return a FinalModel.
The FinalModel handles inference (predict / predict_proba), scaling, and can be saved independently of this result.
Returns:
| Type | Description |
|---|---|
'FinalModel'
|
FinalModel ready for prediction on new data. |
load(path)
classmethod
¶
Reload a result previously saved with result.save(path).
ranking_robustness(step=None)
¶
Paired-fold and cross-metric robustness of the step-1 or step-3 selection.
See h2ml.evaluation.ranking.ranking_robustness for the columns. Works on loaded results — fold DataFrames and metric are persisted. Is_Winner marks the winner before any prefer_reduced_on_tie switch, which would make it differ from best_stage (the switch is recorded in cv_warnings).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step
|
Optional[int]
|
1 (models × transforms on all features) or 3 (default and reduced candidates together, as step 3 selects among both). None → 3 when step 3 has run, else 1. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per candidate, sorted by rank under result.metric. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If step is not 1/3 or that step has not run. |
save(path)
¶
Persist this result to path. Reload with PipelineResult.load(path).
summary(metric=None, ascending=False)
¶
Combined agg DataFrame across all completed stages, plus a "holdout" row when a holdout was scored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
Optional[str]
|
Column name to sort by (e.g. "AUC_Test_Mean"). When None, rows are returned in stage order (default → reduced → optimized). |
None
|
ascending
|
bool
|
Sort direction; set True for error metrics (RMSE, MAE). |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with a "Stage" column prepended. Empty if no steps have run. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If metric is given but not present in the summary columns. |
Nested CV¶
h2ml.pipeline.nested.nested_cv(pipeline, store, outer_splits=5, transforms=None)
¶
Run the full pipeline inside each outer fold and score its final configuration on the outer test fold.
Outer folds use the pipeline's own splitter rules — spatial blocks when store.coords is set (PipelineConfig spatial-CV settings), else stratified (classification) or plain KFold, seeded by config.random_state. Each inner run builds its own splitter on the outer training rows, so no selection step ever sees the outer test rows. Outer folds run serially; config.n_jobs applies inside each inner run. Cost is about outer_splits × one pipeline.run().
The pipeline's holdout_frac is ignored inside the loop — the outer test fold plays that role. A fold whose inner run raises is logged and skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
H2MLPipeline
|
Configured H2MLPipeline (models, config, metadata are reused). |
required |
store
|
PipelineData
|
Full dataset. |
required |
outer_splits
|
int
|
Number of outer folds (>= 2). |
5
|
transforms
|
Optional[Iterable[str]]
|
y-transform names swept inside each inner run (regression only). |
None
|
Returns:
| Type | Description |
|---|---|
NestedCVResult
|
NestedCVResult. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If outer_splits < 2. |
RuntimeError
|
If every outer fold failed. |
h2ml.pipeline.nested.NestedCVResult
dataclass
¶
Output of nested_cv().
Attributes:
| Name | Type | Description |
|---|---|---|
metric |
str
|
Short selection metric name, e.g. "AUC" or "R2". |
folds_df |
DataFrame
|
One row per completed outer fold: the inner pipeline's choice
(Model, Y_transform, Stage, Feature_Stage, N_features), its
inner CV estimate (Inner_ |
selected_features |
list[list[str]]
|
Feature names the final configuration used, per completed fold. |
results |
list[PipelineResult]
|
Inner PipelineResult per completed fold, with the outer test fold attached as its holdout. |
failed_folds |
list[int]
|
Outer fold ids whose inner run or scoring raised. |
cv_type |
str
|
"spatial" when outer folds were spatial, else "random". |
n_folds
property
¶
Number of completed outer folds.
feature_frequency()
¶
Fraction of completed folds whose final configuration used each feature.
selection_counts()
¶
How often each (Model, Y_transform, Stage) was selected, most frequent first.
summary()
¶
One-row summary of the procedure's generalisation.
Columns
Outer_<metric>_Mean/Outer_<metric>_Std: mean and std of the outer test score — the unbiased estimate of what running the pipeline on new data yields.Inner_<metric>_Mean: mean of the inner CV estimates the pipeline reported.Optimism_Mean: mean of (inner − outer), sign-adjusted so positive always means the inner CV estimate was too optimistic.N_folds,N_distinct_selections: completed folds and distinct (model, transform, stage) choices across them.
Seed stability¶
h2ml.pipeline.stability.seed_stability(pipeline, store, seeds=(0, 1, 2, 3, 4), transforms=None, through_step=3)
¶
Rerun the pipeline with config.random_state set to each seed.
The seed drives the CV fold split (and the spatial partition), SHAP sampling, the Optuna sampler and the holdout split. Seeds fixed inside the model constructors (e.g. a registry RandomForest's random_state) are not changed — the spread therefore isolates the evaluation and selection procedure.
A winner picked by only some seeds, or a score spread comparable to the gaps between candidates, means one run's choice is partly luck: compare candidates with ranking_robustness() and prefer simpler ones among those tied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
H2MLPipeline
|
Configured H2MLPipeline (models, config, metadata are reused). |
required |
store
|
PipelineData
|
Full dataset. |
required |
seeds
|
Iterable[int]
|
random_state values to run (at least two). |
(0, 1, 2, 3, 4)
|
transforms
|
Optional[Iterable[str]]
|
y-transform names swept in each run (regression only). |
None
|
through_step
|
Literal[1, 3, 4]
|
1 — model screening only (run_step1_only); 3 — selection without HPO (run_step1_to_step3, default); 4 — the full run(). |
3
|
Returns:
| Type | Description |
|---|---|
SeedStabilityResult
|
SeedStabilityResult. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than two distinct seeds are given or through_step is invalid. |
RuntimeError
|
If every seed's run failed. |
h2ml.pipeline.stability.SeedStabilityResult
dataclass
¶
Output of seed_stability().
Attributes:
| Name | Type | Description |
|---|---|---|
metric |
str
|
Short selection metric name, e.g. "AUC" or "R2". |
runs_df |
DataFrame
|
One row per completed seed: Seed, Model, Y_transform, Stage,
N_features, the reported CV score ( |
selected_features |
list[list[str]]
|
Feature names each seed's final configuration used. |
results |
list[PipelineResult]
|
PipelineResult per completed seed. |
failed_seeds |
list[int]
|
Seeds whose run raised. |
n_runs
property
¶
Number of completed seeds.
feature_frequency()
¶
Fraction of seeds whose final configuration used each feature.
selection_counts()
¶
How often each (Model, Y_transform, Stage) was selected, most frequent first.
summary()
¶
One-row summary across seeds.
Columns
<metric>_Mean/_Std/_Min/_Max: spread of the reported CV score — how much of a difference between two runs could be the seed alone.Holdout_<metric>_Mean/Holdout_<metric>_Std: the same for the holdout score, when scored.Top_Selection,Top_Selection_Fraction: most frequent (model, transform, stage) and the share of seeds that picked it.N_runs,N_distinct_selections: completed seeds and distinct choices.
Multi-metric comparison¶
h2ml.pipeline.multi_metric.multi_metric(pipeline, store, metrics=None, transforms=None, handle_imbalance=None, reuse_step4='none')
¶
Run the full pipeline under each selection metric, sharing the metric-independent work.
Shared, run once: the holdout split; step 1's CV per class-weighting setting (one for regression); steps 2-3 per (class weighting, step-1 winner, y-transform). Per metric: the step-1 and step-3 selections, step 4 (Optuna optimises the metric) and the holdout score. Each metric runs under a copy of pipeline.config with that metric, so results[m] equals H2MLPipeline(replace(config, metric=m)).run(store) when reuse_step4="none".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
H2MLPipeline
|
Configured H2MLPipeline (models, config, metadata are reused; config.metric is ignored). Its models are copied per metric, so one metric's class weighting cannot leak into another's. |
required |
store
|
PipelineData
|
Full dataset. |
required |
metrics
|
Optional[Iterable[str]]
|
Metrics to compare, in run order. Defaults to every metric of the task in TASK_METRICS order: Brier, LogLoss, AUC, AUCPR, F1 (classification); RMSE, R2, MAE (regression). "PoissonDev" can be added for non-negative regression targets. |
None
|
transforms
|
Optional[Iterable[str]]
|
y-transform names swept in step 1 (regression only). |
None
|
handle_imbalance
|
Optional[Mapping[str, bool | Literal['auto']]]
|
Per-metric override of config.handle_imbalance, e.g. {"Brier": False, "LogLoss": False} to keep probability metrics unweighted. Metrics not listed use the config value. Classification only. |
None
|
reuse_step4
|
Literal['none', 'model']
|
"none" (default) tunes step 4 for every metric. "model" reuses an earlier metric's tuning when the same (class weighting, model, transform, feature stage, feature set) won; whether the tuned params beat step 3 is still decided under each metric. Cheaper, but the params were optimised for the earlier metric. |
'none'
|
Returns:
| Type | Description |
|---|---|
MultiMetricResult
|
MultiMetricResult. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a metric is unknown or not a metric of the task, metrics is empty, handle_imbalance is given for regression or names a metric not compared, transforms are given for classification, or reuse_step4 is invalid. |
RuntimeError
|
If every metric's run failed. |
h2ml.pipeline.multi_metric.MultiMetricResult
dataclass
¶
Output of multi_metric().
Attributes:
| Name | Type | Description |
|---|---|---|
metrics |
list[str]
|
Metrics in the order they ran. |
runs_df |
DataFrame
|
One row per completed metric: Metric, Model, Y_transform, Stage, Feature_stage, N_features, Class_weight, the CV score (CV, CV_Std), Holdout (when scored) — each under that row's metric — and Step4_shared_with (the metric whose tuning was reused, else None). |
selected_features |
dict[str, list[str]]
|
Feature names each metric's final configuration used. |
results |
dict[str, PipelineResult]
|
PipelineResult per completed metric. |
failed_metrics |
list[str]
|
Metrics whose run raised. |
reuse_step4 |
str
|
"none" or "model" (see multi_metric). |
feature_frequency()
¶
Fraction of metrics whose final configuration used each feature.
load(path)
classmethod
¶
Reload a MultiMetricResult saved with save(path).
save(path)
¶
Save runs_df, the run settings and each metric's PipelineResult (under results/
selection_counts()
¶
How many metrics selected each (Model, Y_transform, Stage), most frequent first.
summary()
¶
One-row summary across metrics.
Columns
N_metrics,N_distinct_selections: how many metrics completed and how many different (model, transform, stage) they chose.Top_Selection,Top_Selection_Fraction: most frequent choice and the share of metrics that picked it — 1.0 means the choice does not depend on the metric.N_hpo_runs: step-4 tunings actually run.