mlchem.ml.modelling package¶
Model evaluation utilities keep default execution quiet, and expose optional logging diagnostics where relevant (for example in y_scrambling). SHAP plotting paths also perform explicit shape-layout validation for safer error handling.
Submodules¶
mlchem.ml.modelling.model_evaluation module¶
- class ApplicabilityDomain[source]¶
Bases:
objectA class to calculate the leverage of data points in a dataset for applicability domain analysis.
The leverage is a measure of the influence of a data point in a regression model. It helps identify data points that have a significant impact on the model’s predictions. This class provides a method to calculate the leverage values for a given dataset and determine whether each data point is within the applicability domain based on a threshold.
Methods:¶
- leverage(X: np.ndarray):
Calculates the leverage values for the given dataset and determines whether each data point is within the applicability domain based on a threshold.
- static leverage(X: ndarray) dict[str, list[float] | list[bool] | float][source]¶
Calculate leverage values for a dataset and determine applicability domain.
- Parameters:
X (numpy.ndarray) – Feature matrix of shape (n_samples, n_features).
- Returns:
Dictionary containing:
'leverages'(list of float): leverage values for each data point.'results'(list of bool): boolean flags indicating whether each point is within the domain.'threshold'(float): threshold used to determine domain inclusion.
- Return type:
dict of str to list or float
Examples
Calculate leverage for four rows and two features:
>>> import numpy as np >>> X = np.array([ ... [1.0, 0.0], ... [1.0, 1.0], ... [1.0, 2.0], ... [1.0, 3.0], ... ]) >>> result = ApplicabilityDomain.leverage(X) >>> result["threshold"] 1.5 >>> len(result["leverages"]) 4
- class MajorityVote[source]¶
Bases:
objectMajorityVote ensemble evaluation utility.
evaluate_cv()fits estimators on CV folds and can score individual estimators and ensemble combinations in one call. Alternatively, useindividual_only=Trueto screen individual estimators, then pass the filtered results toevaluate_consensus_cv()to score shortlisted combinations using the same fold predictions without refitting.fit()separately fits the final consensus on full train/test data.- Parameters:
train_set (pandas.DataFrame) – Training feature matrix.
y_train (iterable) – Training labels/targets.
task_type ({'classification', 'regression'}) – Task type used to select voting strategy.
estimator_list (list) – List of scikit-learn compatible estimators. Classification estimators must provide
predict_probafor soft voting.column_list (list[list[str]]) – Per-estimator feature subsets aligned with
estimator_list. Forfit(), each listed column must exist in both the training and hold-out DataFrames.test_set (pandas.DataFrame or None, optional) – Hold-out feature matrix used by
fit().y_test (iterable or None, optional) – Hold-out labels/targets used by
fit().estimator_names (list[str] or None, optional) – Optional user-defined estimator names.
n_jobs (int, optional) – Number of workers used by parallel sections.
log_level (int or str, optional) – Logging threshold.
- __init__(train_set: DataFrame, y_train: Iterable, task_type: Literal['classification', 'regression'], estimator_list: list, column_list: list[list[str]], test_set: DataFrame | None = None, y_test: Iterable | None = None, estimator_names: list[str] | None = None, n_jobs: int = 1, log_level: int | str | Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] = 20) None[source]¶
- evaluate_consensus_cv(estimator_results: DataFrame, n_estimators_max: int = 5) DataFrame[source]¶
Evaluate combinations of shortlisted estimators without refitting.
This is the second stage of
evaluate_cv(individual_only=True). For a one-call evaluation without screening, useevaluate_cvwith its defaultindividual_only=Falseinstead.- Parameters:
estimator_results (pandas.DataFrame) – The DataFrame returned by the latest
evaluate_cvcall withindividual_only=True, optionally filtered to retain desired rows. Each retainedestimatorselects that model once, even when several strategy rows remain. Filtering or editing score and prediction columns does not alter cached predictions. DataFrame attributes must be preserved when filtering or copying.n_estimators_max (int, optional (default=5)) – Positive maximum ensemble size. Classification uses only odd sizes; even-sized combinations are not generated.
- Returns:
Fold metrics for shortlisted combinations, including individual estimators. Metrics, folds, and prediction settings are inherited from the individual evaluation; settings used to generate those folds cannot be overridden in this stage.
- Return type:
pandas.DataFrame
- Raises:
ValueError – If no current individual evaluation exists, the table is empty, contains unknown estimators, or came from a different evaluation.
TypeError – If
estimator_resultsis not a DataFrame.
- evaluate_cv(metric: Callable | Sequence[Callable], metric_name: str | Sequence[str], use_continuous_probabilities: bool | Sequence[bool] = False, cv_iter: int = 5, cv_splitter=None, cv_indices: Iterable | None = None, groups: ndarray | Series | None = None, n_estimators_max: int = 5, logic: Literal['lower', 'greater'] | Sequence[Literal['lower', 'greater']] = 'greater', desired_performance_score: Literal['train', 'cv', 'train_cv_average'] = 'train_cv_average', shuffle: bool = False, random_state: int | None = None, individual_only: bool = False) DataFrame[source]¶
Evaluate ensemble combinations using fold-level cross-validation.
The same explicit fold definitions are reused for every estimator and combination, ensuring fair fold-wise comparison. By default this method fits the estimators and scores both individual estimators and their combinations in one call. For a screening step before choosing combinations, set
individual_only=Trueand pass the filtered results toevaluate_consensus_cv. Callingevaluate_cvagain starts a new fit and replaces the cached screening predictions only if the new evaluation succeeds.- Parameters:
metric (callable or sequence of callable) – Scoring functions accepting
(y_true, y_pred). Multiple metrics share the same fitted estimators and fold predictions.metric_name (str or sequence of str) – Unique labels aligned with
metric. Each label prefixes its result columns, for exampleauc_validation_mean.use_continuous_probabilities (bool or sequence of bool, optional) – For classification soft-vote strategies, use mean predicted probabilities directly instead of rounding them to class labels. Enable this for binary ROC-AUC; the probability for
classes_[1]is used. A sequence supplies one setting per metric; a scalar applies to all. Does not affect regression or hard-vote predictions, which use predicted class labels for classification. Values are still validated.cv_iter (int, optional (default=5)) – Number of folds used when
cv_indicesandcv_splitterare not supplied. Ignored if either is supplied.cv_splitter (object, optional) – Scikit-learn compatible splitter exposing
split(X, y, groups). Ignored whencv_indicesis supplied.cv_indices (iterable of (train_idx, valid_idx), optional) – Explicit precomputed fold manifest. When supplied, all combinations are evaluated on exactly these folds, and
cv_iter,cv_splitter,groups,shuffleandrandom_stateare ignored.groups (array-like, optional) – Group labels forwarded to the splitter unless
cv_indicesis supplied. Default splitters do not use groups; a custom splitter determines whether to use them.n_estimators_max (int, optional (default=5)) – Positive maximum number of estimators in a combination. Classification generates only odd-sized combinations. Ignored when
individual_only=True; otherwise validated before fitting.logic ({'lower', 'greater'} or sequence, optional (default='greater')) – Direction of optimization for reliability computation. A sequence supplies one direction per metric; a scalar applies to all.
desired_performance_score ({'train', 'cv', 'train_cv_average'}, optional) – Performance component used inside
get_reliability_score_components. Also used in individual-only mode and reused byevaluate_consensus_cv. Validated before fitting.shuffle (bool, optional (default=False)) – Whether generated CV folds are shuffled when using
cv_iter. Ignored whencv_splitterorcv_indicesis supplied.random_state (int or None, optional) – Random seed used with generated shuffled folds. Ignored when
shuffle=False, or whencv_splitterorcv_indicesis supplied. Configure a custom splitter’s randomness on the splitter itself.individual_only (bool, optional (default=False)) – Score only individual estimators and retain their fold predictions for
evaluate_consensus_cv. The returned DataFrame includes anestimatorcolumn and per-metric fold prediction arrays. The corresponding row positions are available incv_indices_.
- Returns:
One row per evaluated combination and voting
strategy. Columns includecombinationandstrategy, plus metric-prefixed scores such asaccuracy_train_mean,accuracy_validation_mean, andaccuracy_reliability_mean. Each metric hasmean,se,min,max, andfoldscolumns for train, validation, and reliability. Minima and maxima are calculated across the corresponding fold values. Results are ranked by the first metric’s reliability mean, descending. Sort by another metric’s reliability column to change the ranking. Train/validation columns contain raw metric values. Reliability is computed per fold, then averaged: forlogic='lower'it is the negative of the selected loss plusabs(train - validation); forlogic='greater'the existing performance divided by1 + abs(train - validation)is unchanged. Reliability is always maximized, is not raw RMSE, and is nonpositive for nonnegative losses. In individual-only mode, metric-prefixedtrain_predictions_foldsandvalidation_predictions_foldscolumns contain the predictions used by that metric and strategy, in the order ofcv_indices_.- Return type:
pandas.DataFrame
Examples
Rank classifier combinations by cross-validated ROC-AUC. The continuous probability option keeps soft-vote scores suitable for ROC-AUC:
>>> import pandas as pd >>> from sklearn.datasets import make_classification >>> from sklearn.ensemble import RandomForestClassifier >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.metrics import roc_auc_score >>> raw_X, y = make_classification( ... n_samples=60, n_features=4, n_informative=2, ... n_redundant=0, random_state=0 ... ) >>> X = pd.DataFrame(raw_X, columns=["f1", "f2", "f3", "f4"]) >>> columns = X.columns.tolist() >>> ensemble = MajorityVote( ... train_set=X, ... y_train=y, ... task_type="classification", ... estimator_list=[ ... LogisticRegression(max_iter=1000), ... RandomForestClassifier(n_estimators=20, random_state=0), ... LogisticRegression(C=0.5, max_iter=1000), ... ], ... column_list=[columns, columns, columns], ... estimator_names=["logistic", "forest", "logistic_alt"], ... ) >>> results = ensemble.evaluate_cv( ... metric=roc_auc_score, ... metric_name="AUC", ... cv_iter=3, ... n_estimators_max=2, ... use_continuous_probabilities=True, ... shuffle=True, ... random_state=0, ... ) >>> results_summary = results[["combination", "AUC_validation_mean"]].head()
Multiple metrics can use different optimization directions and prediction types without refitting:
>>> from sklearn.metrics import accuracy_score >>> results = ensemble.evaluate_cv( ... metric=[accuracy_score, roc_auc_score], ... metric_name=["accuracy", "AUC"], ... use_continuous_probabilities=[False, True], ... cv_iter=3, ... n_estimators_max=2, ... )
Shortlist individual models before evaluating ensemble combinations:
>>> individual = ensemble.evaluate_cv( ... metric=accuracy_score, metric_name="accuracy", cv_iter=3, ... individual_only=True, ... ) >>> best = individual.groupby("estimator")["accuracy_validation_mean"].max().nlargest(3).index >>> shortlist = individual.loc[individual["estimator"].isin(best)].copy() >>> consensus = ensemble.evaluate_consensus_cv(shortlist, n_estimators_max=3)
- fit(selected_estimators: Iterable[int | str] | None = None, update_active_estimators: bool = False, build_consensus: bool = True, return_prediction_dataframes: bool = False) dict[str, list[str] | int] | dict[source]¶
Hold-out fitting using train and test sets.
- Parameters:
selected_estimators (iterable of int or str, optional) – Optional subset of estimators to fit, provided as indices and/or resolved estimator names. If None, all estimators are fitted.
update_active_estimators (bool, optional (default=False)) – If True, permanently replace
estimator_list/column_list/estimator_nameswith the selected subset after resolution. This is useful for intentionally narrowing the final consensus fit stage to shortlisted estimators.build_consensus (bool, optional (default=True)) – For classification tasks, build transparent hold-out prediction tables with per-estimator probability/class columns plus
CONSENSUS_hardandCONSENSUS_soft.return_prediction_dataframes (bool, optional (default=False)) – If True, return the generated prediction DataFrames together with the fit report.
- Returns:
Fit report with keys:
requested_count,successful_count,failed_count,successful_estimators,failed_estimators. Whenreturn_prediction_dataframes=True, returns a dictionary containing the fit report and generated prediction DataFrames.- Return type:
dict
Examples
Fit one classifier on the training set and evaluate it on a hold-out set:
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> train_set = pd.DataFrame({"signal": [0, 1, 2, 3]}) >>> test_set = pd.DataFrame({"signal": [4, 5]}) >>> vote = MajorityVote( ... train_set=train_set, ... y_train=[0, 0, 1, 1], ... task_type="classification", ... estimator_list=[LogisticRegression(max_iter=1000)], ... column_list=[["signal"]], ... test_set=test_set, ... y_test=[1, 1], ... estimator_names=["logreg"], ... n_jobs=1, ... ) >>> report = vote.fit(selected_estimators=["logreg"]) >>> report["successful_count"] 1
- crossval(estimator, X: ndarray | DataFrame, y: ndarray | DataFrame, metric: Callable, n_fold: int = 5, task_type: Literal['classification', 'regression'] = 'classification', random_state: int | None = None, shuffle: bool = False, cv_splitter=None, cv_indices: Iterable | None = None, groups: ndarray | Series | None = None, response_method: Literal['predict', 'predict_proba', 'decision_function'] = 'predict') dict[str, ndarray | float][source]¶
Evaluate an estimator using cross-validation.
This function performs K-fold cross-validation on the given dataset using the specified estimator and metric function. It supports both classification and regression tasks.
By default (
cv_splitter=Noneandcv_indices=None), behaviour is unchanged from previous releases:n_foldfolds are generated internally usingStratifiedKFold/KFold. For fully index-driven, realistic validation strategies (GroupKFold,StratifiedGroupKFold,PredefinedSplit, scaffold-based folds, UMAP-cluster folds, or any externally generated fold manifest), passcv_splitterand/orcv_indicesinstead. Internally, all cross-validation execution operates on explicit, validated train/validation index pairs regardless of which input mode is used (seegenerate_cv_indices()).- Parameters:
estimator (object) – A scikit-learn compatible estimator.
X (numpy.ndarray or pandas.DataFrame) – Feature matrix of shape (n_samples, n_features).
y (numpy.ndarray or pandas.DataFrame) – Target vector of shape (n_samples,) or (n_samples, 1).
metric (callable) – A scoring function that accepts (y_true, y_pred) as arguments.
response_method ({'predict', 'predict_proba', 'decision_function'}, optional (default='predict')) – Estimator method used to obtain metric inputs. The estimator must implement the selected method. For binary
predict_proba, sklearn selects the probability forestimator.classes_[1]; for multiclass classification it passes the full score matrix. Usepredict_probaordecision_functionfor ROC-AUC; label-based metrics should usepredict.n_fold (int, optional (default=5)) – Number of folds for cross-validation. If equal to n_samples, performs leave-one-out cross-validation. Ignored when
cv_splitterorcv_indicesis provided.task_type ({'classification', 'regression'}, optional (default='classification')) – Type of task to determine the cross-validation strategy.
random_state (int or None, optional (default=None)) – Random seed for reproducibility.
shuffle (bool, optional (default=False)) – Whether to shuffle samples before splitting into batches.
cv_splitter (object, optional) – A scikit-learn compatible cross-validation splitter (e.g.
GroupKFold(n_splits=5),StratifiedGroupKFold(...), orPredefinedSplit(...)). When provided, it takes precedence overn_fold/task_type-based fold generation. Combine withgroupsfor group-aware splitters.cv_indices (iterable of (array-like, array-like), optional) – Explicit, pre-computed
(train_idx, valid_idx)pairs (e.g. a scaffold-based or UMAP-cluster-based fold manifest generated outside mlchem). Takes precedence over bothcv_splitterandn_foldwhen provided. This is the most generic API.groups (array-like, optional) – Group labels propagated to
cv_splitter.split(e.g. scaffold IDs forGroupKFold). Ignored whencv_indicesis provided.
- Returns:
Dictionary with fold-level arrays and summary statistics:
train_scores,train_mean,train_se,cv_scores,cv_mean,cv_se.- Return type:
dict
Examples
Evaluate binary ROC-AUC using predicted probabilities:
>>> from sklearn.datasets import make_classification >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.metrics import roc_auc_score >>> X, y = make_classification( ... n_samples=40, n_features=4, n_informative=2, ... n_redundant=0, random_state=0 ... ) >>> scores = crossval( ... LogisticRegression(max_iter=1000), ... X, ... y, ... roc_auc_score, ... n_fold=4, ... shuffle=True, ... random_state=0, ... response_method="predict_proba", ... ) >>> cv_mean = scores["cv_mean"]
- generate_cv_indices(X: ndarray | DataFrame, y: ndarray | DataFrame | None = None, cv_iter: int = 5, cv_splitter=None, cv_indices: Iterable | None = None, groups: ndarray | Series | None = None, task_type: Literal['classification', 'regression'] = 'classification', shuffle: bool = False, random_state: int | None = None, strict_coverage: bool = False) list[tuple[ndarray, ndarray]][source]¶
Resolve any supported cross-validation input into explicit fold indices.
This is the single entry point that converts
cv_iter(existing behaviour), a scikit-learncv_splitter(optionally combined withgroups), or a user-suppliedcv_indicesmanifest into the same canonical representation: a validated list of(train_idx, valid_idx)index pairs. Fold-generation logic external to mlchem (scaffold splits, UMAP-cluster splits, etc.) only needs to producecv_indicesin this format.- Parameters:
X (numpy.ndarray or pandas.DataFrame) – Feature matrix of shape (n_samples, n_features). Only its length is used unless a
cv_splitterrequiresXfor splitting.y (numpy.ndarray, pandas.DataFrame, or None, optional) – Target vector, forwarded to
cv_splitter.splitwhen needed (e.g. for stratified splitters). Ignored whencv_indicesis supplied.cv_iter (int, optional (default=5)) – Number of folds to generate when neither
cv_splitternorcv_indicesis supplied. Mirrors the legacy behaviour.cv_splitter (object, optional) – A scikit-learn compatible cross-validation splitter (e.g.
GroupKFold,StratifiedGroupKFold,PredefinedSplit) exposing asplit(X, y, groups)method. Ignored whencv_indicesis supplied.cv_indices (iterable of (array-like, array-like), optional) – Explicit, pre-computed
(train_idx, valid_idx)pairs. Takes precedence over fold generation when provided;cv_iter,cv_splitter,groups,task_type,shuffleandrandom_stateare then ignored. This is the most generic API and is suitable for externally generated fold manifests (scaffold-based folds, UMAP-cluster folds, etc.).groups (array-like, optional) – Group labels forwarded to the splitter when
cv_indicesis not supplied. The default splitters do not use groups; a customcv_splitterdetermines whether to use them.task_type ({'classification', 'regression'}, optional (default='classification')) – Used only to pick the default splitter (
StratifiedKFoldorKFold) when neithercv_splitternorcv_indicesis given.shuffle (bool, optional (default=False)) – Whether to shuffle samples before splitting, for the default
cv_iter-based splitter. Ignored whencv_splitterorcv_indicesis supplied.random_state (int or None, optional (default=None)) – Random seed for the default
cv_iter-based splitter whenshuffle=True. Ignored whenshuffle=False, or whencv_splitterorcv_indicesis supplied.strict_coverage (bool, optional (default=False)) – Forwarded to
validate_cv_indices().
- Returns:
Validated
(train_idx, valid_idx)pairs.- Return type:
list of (numpy.ndarray, numpy.ndarray)
Examples
Generate reproducible stratified folds from a small labeled dataset:
>>> import pandas as pd >>> X = pd.DataFrame({"signal": [0, 1, 2, 3, 4, 5]}) >>> y = [0, 0, 0, 1, 1, 1] >>> folds = generate_cv_indices( ... X, y, cv_iter=3, shuffle=True, random_state=0 ... ) >>> len(folds) 3
- summarise_fold_scores(scores: Iterable[float]) dict[source]¶
Compute mean and standard error from fold scores.
- Parameters:
scores (Iterable[float]) – Iterable of fold scores.
- Returns:
Dictionary containing the fold scores, the mean and standard error of the fold scores.
- Return type:
dict
Examples
Summarise three fold scores:
>>> summary = summarise_fold_scores([0.8, 0.9, 1.0]) >>> summary["mean"] 0.9 >>> round(summary["se"], 3) 0.047
- validate_cv_indices(cv_indices: Iterable, n_samples: int, strict_coverage: bool = False) list[tuple[ndarray, ndarray]][source]¶
Validate an explicit list of (train_idx, valid_idx) cross-validation folds.
- Parameters:
cv_indices (iterable of (array-like, array-like)) – Explicit train/validation index pairs, one per fold.
n_samples (int) – Number of samples the indices are expected to reference.
strict_coverage (bool, optional (default=False)) – If True, raise a
ValueErrorwhen some samples are never used as validation data in any fold. If False (default), only emit aRuntimeWarningin that case, since some valid fold manifests (e.g. aPredefinedSplitexcluding held-out samples) may legitimately not cover every sample.
- Returns:
Normalised, validated (train_idx, valid_idx) pairs.
- Return type:
list of (numpy.ndarray, numpy.ndarray)
- Raises:
ValueError – If folds overlap, contain out-of-range/duplicate indices, are empty, or are otherwise inconsistently defined.
Examples
Validate two disjoint folds whose validation sets cover all samples:
>>> import numpy as np >>> folds = [ ... (np.array([2, 3]), np.array([0, 1])), ... (np.array([0, 1]), np.array([2, 3])), ... ] >>> checked = validate_cv_indices(folds, n_samples=4) >>> len(checked) 2
- y_scrambling(estimator, train_set: ndarray | DataFrame, y_train: Iterable, metric: Callable, n_scrambles: int = 100, n_fold: int = 5, cv_splitter=None, groups=None, cv_indices: Iterable | None = None, logic: Literal['lower', 'greater'] = 'greater', task_type: Literal['classification', 'regression'] = 'classification', plot: bool = True, n_jobs: int = 1, safety_multiplier: float = 2.3, log_level: int | str | Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] = 20, response_method: Literal['predict', 'predict_proba', 'decision_function'] = 'predict') dict[str, float | ndarray][source]¶
Perform y-scrambling to estimate chance-level model performance.
The target vector is shuffled
n_scramblestimes, each shuffled target is cross-validated, and the null-score distribution is compared with the score obtained from the unshuffled labels.- Parameters:
estimator (object) – Scikit-learn compatible estimator.
train_set (numpy.ndarray or pandas.DataFrame) – Training feature matrix.
y_train (iterable) – Target values.
metric (callable) – Scoring function
metric(y_true, y_pred).n_scrambles (int, optional) – Number of shuffled-label iterations. Default is 100.
n_fold (int, optional) – Number of CV folds when explicit folds are not provided.
cv_splitter (object, optional) – CV splitter overriding
n_fold.groups (array-like, optional) – Group labels passed to group-aware splitters.
cv_indices (iterable, optional) – Explicit fold definitions overriding
cv_splitterandn_fold.logic ({'lower', 'greater'}, optional) – Score direction used for comparisons.
task_type ({'classification', 'regression'}, optional) – Task type used by default CV strategy.
plot (bool, optional) – If True, display a histogram of scrambled scores.
n_jobs (int, optional) – Number of parallel workers. Use -1 for all CPUs.
safety_multiplier (float, optional) – Multiplier defining
safety_margin = safety_multiplier * scrambled_std.log_level (int or str, optional) – Logging threshold.
response_method ({'predict', 'predict_proba', 'decision_function'}, optional) – Estimator method used to obtain metric inputs. Defaults to
predict. For ROC-AUC, usepredict_probaordecision_function.
- Returns:
Mapping with keys:
reference_scorescrambled_scoresscrambled_stdbest_random_scoreprobability_betterobtained_marginsafety_marginsafety_margin_ratiosafety_multiplier
- Return type:
dict
Examples
Compare a binary ROC-AUC reference score with a small scrambled-label distribution:
>>> from sklearn.datasets import make_classification >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.metrics import roc_auc_score >>> X, y = make_classification( ... n_samples=40, n_features=4, n_informative=2, ... n_redundant=0, random_state=0 ... ) >>> result = y_scrambling( ... estimator=LogisticRegression(max_iter=1000), ... train_set=X, ... y_train=y, ... metric=roc_auc_score, ... n_scrambles=10, ... n_fold=4, ... plot=False, ... response_method="predict_proba", ... ) >>> reference_score = result["reference_score"]
mlchem.ml.modelling.model_interpretation module¶
- class DescriptorExplainer[source]¶
Bases:
objectA class to perform feature selection and model evaluation using combinatorial selection methods.
This class provides methods to fit and evaluate machine learning models using combinatorial feature selection. It supports both classification and regression tasks, offering tools to identify the best feature subsets and visualise model performance.
- df_train¶
The training dataset.
- Type:
pandas.DataFrame
- df_test¶
The testing dataset.
- Type:
pandas.DataFrame
- target_train¶
The target values for the training dataset.
- Type:
pandas.DataFrame
- target_test¶
The target values for the testing dataset.
- Type:
pandas.DataFrame
- target_name¶
The name of the target variable.
- Type:
str
- estimator¶
The machine learning model to be used for feature selection and evaluation.
- Type:
object
- metric¶
The metric function to evaluate the model performance.
- Type:
callable
- logic¶
The logic to determine whether to minimise or maximise the metric.
- Type:
{‘lower’, ‘greater’}
- task_type¶
The type of task to perform.
- Type:
{‘classification’, ‘regression’}
- __init__(df_train: DataFrame, df_test: DataFrame, target_train: DataFrame, target_test: DataFrame, estimator, metric, logic: Literal['lower', 'greater'] = 'greater', task_type: Literal['classification', 'regression'] = 'regression', n_jobs: int = 1, log_level: int | str | Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] = 20, cv_splitter=None, cv_indices=None, groups=None) None[source]¶
Initialise the DescriptorExplainer with training/testing data, model, and evaluation settings.
- Parameters:
df_train (pandas.DataFrame) – The training dataset.
df_test (pandas.DataFrame) – The testing dataset.
target_train (pandas.DataFrame) – The target values for the training dataset.
target_test (pandas.DataFrame) – The target values for the testing dataset.
estimator (object) – The machine learning model to be used.
metric (callable) – The evaluation metric function.
logic ({'lower', 'greater'}, optional (default='greater')) – Whether to minimise or maximise the metric.
task_type ({'classification', 'regression'}, optional (default='regression')) – The type of task to perform.
n_jobs (int, optional (default=1)) – Number of parallel workers for feature selection stages. -1 uses all available CPUs.
log_level (int or str or Literal, optional (default=logging.INFO)) – Logging level for diagnostics. Can be integer (10, 20, 30, etc.) or string (‘DEBUG’, ‘INFO’, etc.).
cv_splitter (object, optional) – A scikit-learn compatible cross-validation splitter (e.g.
GroupKFold(5),StratifiedGroupKFold(...),PredefinedSplit(...)). Combine withgroupsfor group-aware splitters. Takes precedence over thecv_iterpassed tofit_stage_1/fit_stage_2.cv_indices (iterable of (array-like, array-like), optional) – Explicit, pre-computed
(train_idx, valid_idx)pairs, e.g. a scaffold-based or UMAP-cluster-based fold manifest generated outside mlchem. Takes precedence over bothcv_splitterandcv_iter.groups (array-like, optional) – Group labels (e.g. scaffold IDs) propagated to
cv_splitter. Ignored whencv_indicesis provided.
- display(subset_index: int) None[source]¶
Display the performance of the model using a selected feature subset.
This method visualises model performance using the selected feature subset. For regression tasks, it plots true vs. predicted values and prints model coefficients and adjusted R². For classification, it shows a confusion matrix and prints performance metrics.
- Parameters:
subset_index (int) – The index of the feature subset to use for evaluation.
- Return type:
None
Examples
>>> import numpy as np >>> import pandas as pd >>> from sklearn.linear_model import LinearRegression >>> from mlchem.metrics import get_rmse >>> from mlchem.ml.modelling.model_interpretation import DescriptorExplainer >>> rng = np.random.RandomState(1) >>> X_train = pd.DataFrame(rng.rand(20, 3), columns=["a", "b", "c"]) >>> y_train = pd.DataFrame(rng.rand(20, 1), columns=["target"]) >>> X_test = pd.DataFrame(rng.rand(8, 3), columns=X_train.columns) >>> y_test = pd.DataFrame(rng.rand(8, 1), columns=["target"]) >>> selector = DescriptorExplainer( ... X_train, X_test, y_train, y_test, ... LinearRegression(), get_rmse, logic="lower") >>> selector.fit_stage_1(cv_iter=2) >>> selector.fit_stage_2(top_n_subsets=4, cv_iter=2) >>> selector.display(subset_index=0)
- fit_stage_1(k: int = 2, training_threshold: float = 1.5, cv_train_ratio: float = 0.8, cv_iter: int = 5) None[source]¶
Perform the first stage of combinatorial feature selection.
This method evaluates combinations of features using cross-validation and filters subsets based on a training score threshold. Parallelization is controlled by the n_jobs parameter specified during initialization.
- Parameters:
k (int, optional (default=2)) – The number of features to combine.
training_threshold (float, optional (default=1.5)) – The threshold for the training score to consider a subset.
cv_train_ratio (float, optional (default=0.8)) – The minimum accepted cv score/train score ratio.
cv_iter (int, optional (default=5)) – The number of cross-validation iterations.
- Return type:
None
Examples
>>> import numpy as np >>> import pandas as pd >>> from sklearn.linear_model import LinearRegression >>> from mlchem.metrics import get_rmse >>> from mlchem.ml.modelling.model_interpretation import DescriptorExplainer >>> rng = np.random.RandomState(1) >>> X_train = pd.DataFrame(rng.rand(20, 3), columns=["a", "b", "c"]) >>> y_train = pd.DataFrame(rng.rand(20, 1), columns=["target"]) >>> X_test = pd.DataFrame(rng.rand(8, 3), columns=X_train.columns) >>> y_test = pd.DataFrame(rng.rand(8, 1), columns=["target"]) >>> selector = DescriptorExplainer( ... X_train, X_test, y_train, y_test, ... LinearRegression(), get_rmse, logic="lower") >>> selector.fit_stage_1(cv_iter=2)
- fit_stage_2(top_n_subsets: int = 10, cv_iter: int = 5) None[source]¶
Perform the second stage of combinatorial feature selection.
This method evaluates the top feature subsets from stage 1 using cross-validation to identify the best-performing combinations. Parallelization is controlled by the n_jobs parameter specified during initialization.
- Parameters:
top_n_subsets (int, optional (default=10)) – The number of top feature subsets to consider.
cv_iter (int, optional (default=5)) – The number of cross-validation iterations.
- Return type:
None
Examples
>>> import numpy as np >>> import pandas as pd >>> from sklearn.linear_model import LinearRegression >>> from mlchem.metrics import get_rmse >>> from mlchem.ml.modelling.model_interpretation import DescriptorExplainer >>> rng = np.random.RandomState(1) >>> X_train = pd.DataFrame(rng.rand(20, 3), columns=["a", "b", "c"]) >>> y_train = pd.DataFrame(rng.rand(20, 1), columns=["target"]) >>> X_test = pd.DataFrame(rng.rand(8, 3), columns=X_train.columns) >>> y_test = pd.DataFrame(rng.rand(8, 1), columns=["target"]) >>> selector = DescriptorExplainer( ... X_train, X_test, y_train, y_test, ... LinearRegression(), get_rmse, logic="lower") >>> selector.fit_stage_1(cv_iter=2) >>> selector.fit_stage_2(top_n_subsets=4, cv_iter=2)
- class ShapExplainer[source]¶
Bases:
objectA class to generate SHAP (SHapley Additive exPlanations) values for model interpretability.
This class provides methods to explain the output of machine learning models using SHAP values. It supports both tree-based models and general estimators, and offers a variety of visualisation tools to understand the impact of each feature on model predictions.
- is_tree¶
Whether the estimator is tree-based. This describes the model, not the explainer selected; a tree model can fall back to PermutationExplainer.
- Type:
bool
- data¶
The foreground dataset to explain.
- Type:
pandas.DataFrame
- y¶
The target values corresponding to the dataset.
- Type:
array-like
- estimator¶
The machine learning model to be explained.
- Type:
object
- explainer_type¶
The SHAP explainer actually used after
explain().- Type:
str or None
- output_scale¶
The units of the SHAP values: raw tree output or positive-class probability.
- Type:
str or None
- Methods:
explain() – Generates SHAP values for the model.
load(base_values, shap_values) – Loads precomputed SHAP values.
save(path, filename) – Saves the SHAP values to the specified path.
force_plot() – Generates a force plot to visualise SHAP values.
force_plot_single(i) – Generates a force plot for a single instance.
dependence_plot(column) – Generates a dependence plot for a specified feature.
dependence_plot_all() – Generates dependence plots for all features.
summary_plot(plot_type=’dot’) – Generates a summary plot of SHAP values.
waterfall_plot(i) – Generates a waterfall plot for a single instance.
bar_plot() – Generates a bar plot of SHAP values.
feature_importance() – Calculates and returns feature importance based on SHAP values.
decision_plot(interval_lower, interval_upper) – Generates a decision plot for a specified probability interval.
- __init__(estimator, data: DataFrame, y: Iterable, is_tree: bool = False, max_samples: int | None = None, background_data: DataFrame | None = None) None[source]¶
Initialise the ShapExplainer with a model, dataset, and target values.
- Parameters:
estimator (object) – The machine learning model to be explained.
data (pandas.DataFrame) – The foreground dataset to explain.
y (Iterable) – The target values corresponding to the dataset.
is_tree (bool, optional (default=False)) – Whether the estimator is tree-based (e.g., XGBoost, LightGBM). This remains True if unsupported categorical splits require a PermutationExplainer.
max_samples (int or None, optional (default=None)) – Maximum number of background rows used by the masker. A positive integer selects a deterministic subset; None uses all background rows.
background_data (pandas.DataFrame or None, optional (default=None)) – Reference rows used for SHAP masking. If None,
datais also used as the background for both tree and non-tree explainers.
Notes
Tree models use an interventional TreeExplainer with the selected background. Tree-path-dependent TreeExplainer is an explicit alternative that can be constructed directly with SHAP; it does not use this class’s background_data or max_samples and is not the automatic categorical fallback.
- bar_plot() None[source]¶
Generate a bar plot of SHAP values.
- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> explainer.bar_plot()
- decision_plot(interval_lower: float, interval_upper: float) None[source]¶
Generate a decision plot for a specified probability interval.
This method creates a SHAP decision plot to visualise how features contribute to model predictions for samples within a given probability interval. It also prints classification statistics for the selected interval.
Note
Supported for binary classifiers with predict_proba output. The method handles both tree and non-tree SHAP layouts and selects the positive class contributions when class-wise SHAP values are provided.
- Parameters:
interval_lower (float) – The lower bound of the probability interval.
interval_upper (float) – The upper bound of the probability interval.
- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> explainer.decision_plot(interval_lower=0.0, interval_upper=1.0)
- dependence_plot(column: int) None[source]¶
Generate a dependence plot for a specified feature.
- Parameters:
column (int) – The index of the feature to visualise.
- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> explainer.dependence_plot(column=0)
- dependence_plot_all() None[source]¶
Generate dependence plots for all features.
- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> explainer.dependence_plot_all()
- explain() None[source]¶
Generate SHAP values for the model.
Tree models use an interventional TreeExplainer and raw model output. If TreeExplainer raises SHAP’s unsupported-categorical-splits error, this method warns and uses PermutationExplainer on positive-class probabilities instead.
is_treecontinues to describe the estimator;explainer_typeandoutput_scaledescribe the result.- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({ ... "length": [1.0, 2.0, 3.0, 4.0], ... "width": [0.0, 1.0, 0.0, 1.0], ... }) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> explainer.shap_values.shape (4, 2)
- feature_importance() DataFrame[source]¶
Calculate and visualise feature importance based on SHAP values.
This method computes feature importance by summing the absolute SHAP values for each feature. It also calculates the Spearman correlation between each feature and its SHAP values, and derives an overall impact score. The results are visualised using a color-coded bar plot and returned as a DataFrame.
- Returns:
A DataFrame containing the feature importance weights, correlations, and overall impact scores for each feature.
- Return type:
pandas.DataFrame
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> importance = explainer.feature_importance()
- force_plot() HTML[source]¶
Generate a force plot to visualise SHAP values.
- Returns:
An HTML object containing the SHAP force plot.
- Return type:
IPython.core.display.HTML
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> html = explainer.force_plot() # Keep the HTML; display it separately if needed.
- force_plot_single(i: int) HTML[source]¶
Generate a force plot for a single instance.
- Parameters:
i (int) – The index of the instance to visualise.
- Returns:
An HTML object containing the SHAP force plot for the specified instance.
- Return type:
IPython.core.display.HTML
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> html = explainer.force_plot_single(0)
- heatmap() None[source]¶
Generate a heatmap of SHAP values.
This method creates a heatmap to visualise the SHAP values for the model’s predictions. It initialises the SHAP JavaScript visualisation and displays the plot.
Note
Heatmaps are not available for TreeExplainer results. A tree model using the categorical fallback uses PermutationExplainer and supports this plot.
- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> explainer.heatmap()
- load(base_values: ndarray, shap_values: ndarray) None[source]¶
Load precomputed SHAP values.
- Parameters:
base_values (numpy.ndarray) – The precomputed base values.
shap_values (numpy.ndarray) – The precomputed SHAP values.
- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> original = ShapExplainer(model, X, y) >>> original.explain() >>> restored = ShapExplainer(model, X, y) >>> restored.load(original.base_values, original.shap_values) >>> restored.shap_values.shape (4, 2)
- save(path: str, filename: str) None[source]¶
Save SHAP values to the specified path.
- Parameters:
path (str) – The directory path where the SHAP values will be saved.
filename (str) – The base filename for the saved SHAP values.
- Return type:
None
Examples
>>> import os >>> import tempfile >>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> with tempfile.TemporaryDirectory() as temp_dir: ... output_dir = os.path.join(temp_dir, "shap") ... explainer.save(output_dir, "demo")
- summary_plot(plot_type: Literal['dot', 'bar', 'violin', 'layered_violin', 'compact_dot'] = 'dot') None[source]¶
Generate a summary plot of SHAP values.
- Parameters:
plot_type ({'dot', 'bar', 'violin', 'layered_violin', 'compact_dot'},)
(default='dot') (optional) – The type of plot to generate.
- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> explainer.summary_plot(plot_type="dot")
- waterfall_plot(i: int) None[source]¶
Generate a waterfall plot for a single instance.
Note: Not available for TreeExplainer results. A tree model using the categorical fallback uses PermutationExplainer and supports this plot.
- Parameters:
i (int) – The index of the instance to visualise.
- Return type:
None
Examples
>>> import pandas as pd >>> from sklearn.linear_model import LogisticRegression >>> from mlchem.ml.modelling.model_interpretation import ShapExplainer >>> X = pd.DataFrame({"length": [1., 2., 3., 4.], "width": [0., 1., 0., 1.]}) >>> y = [0, 0, 1, 1] >>> model = LogisticRegression().fit(X, y) >>> explainer = ShapExplainer(model, X, y) >>> explainer.explain() >>> explainer.waterfall_plot(0)