Skip to content

Feature Selection API

Step 2's selector and filters. See Feature selection for how they appear on a result.

FeatureSelector

h2ml.features.selector.FeatureSelector

Bases: BasePreprocessor

Pipeline step that reduces features using SHAP importance + correlation filtering.

Fit phase
  1. Computes out-of-fold (OOF) SHAP values — each sample's importance is derived from the fold where it was held out, so no training sample leaks into its own SHAP computation. Set use_oof=False to revert to full-dataset SHAP.
  2. Ranks features by mean absolute SHAP importance.
  3. Removes features correlated above corr_threshold with higher-ranked features.
  4. Optionally (max_vif) removes multicollinear features, lowest-ranked first.
  5. Stores selected_features_ for use in transform.
Transform phase

Returns a reduced PipelineData containing only the selected features.

Parameters:

Name Type Description Default
step Any

A ModelWrapper whose class and params seed each fold's model. The selector handles fitting internally.

required
task_type TaskType

TaskType.CLASSIFICATION or TaskType.REGRESSION.

required
corr_threshold float

Correlation threshold for feature removal (default 0.7).

0.7
min_features int

Minimum number of features to retain. If correlation filtering would drop below this, the top SHAP-ranked removed features are restored until the minimum is met (default 1 — no guard).

1
use_oof bool

If True (default), compute SHAP via out-of-fold CV to avoid information leakage into feature selection. If False, fit on the full training set (faster, mildly optimistic step 3 scores).

True
n_splits int

Folds for the OOF CV pass (used only when use_oof=True).

5
random_state int

Seed for OOF fold shuffle and the PermutationExplainer.

42
shap_save_path Optional[Path]

Optional path to save SHAP array as .npy.

None
max_background int

Max background samples for the model-agnostic explainer (affects non-tree, non-linear models such as SVC/SVR with rbf kernel). Larger training folds are summarised with shap.kmeans to this size. Default 100 — increase for more accurate SHAP at cost of speed.

100
verbose bool

Log selected/removed feature counts.

False
train_target_fn Optional[Callable]

Step fitted on and applied to the targets each SHAP model is trained on (e.g. winsorize clipping) — per training fold in OOF mode, so its statistics never see held-out rows.

None
n_jobs int

Worker processes for the model-agnostic explainer (row chunks are explained in parallel; results do not depend on n_jobs). Default 1.

1
max_vif Optional[float]

When set, after the correlation filter drop the lowest-ranked feature with a variance inflation factor above this value until none is — catches features that are linear combinations of several retained ones. None (default) skips the check.

None
keep_all bool

Skip SHAP and keep every feature, for a model whose predictions don't vary: it gives no ranking, so any reduction would follow column order. feature_importance_ is then all zeros and shap_values_ stays empty. Default False.

False
_splitter Any

Internal — a pre-built spatial splitter reused for the OOF SHAP pass so it matches the pipeline's CV folds. Leave None for non-spatial use; the pipeline injects it when relevant.

None

Examples:

>>> selector = FeatureSelector(best_step, TaskType.CLASSIFICATION, corr_threshold=0.7)
>>> store_reduced = selector.fit_transform(store, store.y)
>>> store_reduced.feature_names   # reduced feature list

n_selected property

Number of features retained after the correlation filter.

removed_features property

Features that were dropped during fit.

fit(store, y=None)

Compute SHAP importance and determine selected features.

Parameters:

Name Type Description Default
store PipelineData

PipelineData containing the training data.

required
y Optional[ndarray]

Unused — kept for API compatibility with BasePreprocessor.

None

Returns:

Type Description
'FeatureSelector'

self, with shap_values_, feature_importance_ and selected_features_ set.

fit_transform(store, y=None)

Fit and transform in one call.

Parameters:

Name Type Description Default
store PipelineData

PipelineData to fit the selector on and then reduce.

required
y Optional[ndarray]

Unused — kept for API compatibility with BasePreprocessor.

None

Returns:

Type Description
PipelineData

Reduced PipelineData containing only the selected features.

importance_summary()

Returns a DataFrame of all features with their SHAP importance and whether they were selected or removed.

transform(store)

Return a new PipelineData with only the selected features.

Parameters:

Name Type Description Default
store PipelineData

PipelineData to reduce (can be train or test set).

required

Returns:

Type Description
PipelineData

Reduced PipelineData preserving feature names and y.

remove_correlated_features

h2ml.features.correlation.remove_correlated_features(X, feature_importance, corr_threshold=0.7, methods=None)

Return a list of selected (uncorrelated) features ranked by SHAP importance.

Features are evaluated in descending SHAP importance order. A feature is removed if its absolute correlation with any already-selected higher-ranked feature exceeds corr_threshold in ANY of the specified methods.

Parameters:

Name Type Description Default
X DataFrame

DataFrame of features (unscaled — correlation is computed on raw values).

required
feature_importance Series

pd.Series indexed by feature name, sorted descending. Typically the output of get_shap_values().

required
corr_threshold float

Absolute correlation threshold (default 0.7).

0.7
methods Optional[list[CorrelationMethod]]

Correlation methods to apply. A feature is removed if it exceeds the threshold in any one of them.

None

Returns:

Type Description
list[str]

List of selected feature names in importance order.

Raises:

Type Description
ValueError

If corr_threshold is not in the half-open interval (0, 1].

variance_inflation_factors

h2ml.features.correlation.variance_inflation_factors(X)

Variance inflation factor of each column: 1 / (1 − R²) of regressing it (with an intercept) on all other columns. inf when a column is an exact linear combination of the others.

Parameters:

Name Type Description Default
X DataFrame

DataFrame of at least two features.

required

Returns:

Type Description
Series

pd.Series of VIF indexed by column name.

remove_high_vif_features

h2ml.features.correlation.remove_high_vif_features(X, features, max_vif)

Drop multicollinear features until every remaining VIF is at most max_vif.

The pairwise filter (remove_correlated_features) cannot see a feature that is a linear combination of several retained ones while being only moderately correlated with each. Here, while any VIF exceeds max_vif, the lowest-ranked feature among those above it is dropped and VIFs are recomputed — so importance still decides which member of a collinear group survives. VIF is a linear (Pearson-type) measure.

Parameters:

Name Type Description Default
X DataFrame

DataFrame holding at least the columns in features.

required
features list[str]

Candidate features in descending importance order.

required
max_vif float

Largest acceptable VIF (> 1; 5 and 10 are common choices).

required

Returns:

Type Description
list[str]

Retained features in the original importance order.

Raises:

Type Description
ValueError

If max_vif <= 1.

final_feature_names

h2ml.pipeline.nested.final_feature_names(result)

Features the result's final configuration uses (reduced set when that stage won).