Skip to content

Features Elimination

This module focuses on feature elimination and it contains two classes:

  • ShapRFECV: Perform Backwards Recursive Feature Elimination, using SHAP feature importance. It supports binary classification models and hyperparameter optimization at every feature elimination step.
  • EarlyStoppingShapRFECV: adds support to early stopping of the model fitting process. It can be an alternative regularization technique to hyperparameter optimization of the number of base trees in gradient boosted tree models. Particularly useful when dealing with large datasets.

EarlyStoppingShapRFECV

Bases: ShapRFECV

This class performs Backwards Recursive Feature Elimination, using SHAP feature importance.

This is a child of ShapRFECV which allows early stopping of the training step, this class is compatible with LightGBM, XGBoost and CatBoost models. If you are not using early stopping, you should use the parent class, ShapRFECV, instead of EarlyStoppingShapRFECV.

Early stopping is a type of regularization technique in which the model is trained until the scoring metric, measured on a validation set, stops improving after a number of early_stopping_rounds. In boosted tree models, this technique can increase the training speed, by skipping the training of trees that do not improve the scoring metric any further, which is particularly useful when the training dataset is large.

Note that if the classifier is a hyperparameter search model is used, the early stopping parameter is passed only to the fit method of the model duiring the Shapley values estimation step, and not for the hyperparameter search step. Early stopping can be seen as a type of regularization of the optimal number of trees. Therefore you can use it directly with a LightGBM or XGBoost model, as an alternative to a hyperparameter search model.

At each round, for a given feature set, starting from all available features, the following steps are applied:

  1. (Optional) Tune the hyperparameters of the model using sklearn compatible search CV e.g. GridSearchCV, RandomizedSearchCV, or BayesSearchCV. Note that during this step the model does not use early stopping.
  2. Apply Cross-validation (CV) to estimate the SHAP feature importance on the provided dataset. In each CV iteration, the model is fitted on the train folds, and applied on the validation fold to estimate SHAP feature importance. The model is trained until the scoring metric eval_metric, measured on the validation fold, stops improving after a number of early_stopping_rounds.
  3. Remove step lowest SHAP importance features from the dataset.

At the end of the process, the user can plot the performance of the model for each iteration, and select the optimal number of features and the features set.

We recommend using LGBMClassifier, because by default it handles missing values and categorical features. In case of other models, make sure to handle these issues for your dataset and consider impact it might have on features importance.

Example:

from lightgbm import LGBMClassifier
import pandas as pd
from probatus.feature_elimination import EarlyStoppingShapRFECV
from sklearn.datasets import make_classification

feature_names = [
    'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7',
    'f8', 'f9', 'f10', 'f11', 'f12', 'f13',
    'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20']

# Prepare two samples
X, y = make_classification(n_samples=200, class_sep=0.05, n_informative=6, n_features=20,
                           random_state=0, n_redundant=10, n_clusters_per_class=1)
X = pd.DataFrame(X, columns=feature_names)

# Prepare model
clf = LGBMClassifier(n_estimators=200, max_depth=3)

# Run feature elimination
shap_elimination = EarlyStoppingShapRFECV(
    clf=clf, step=0.2, cv=10, scoring='roc_auc', early_stopping_rounds=10, n_jobs=3)
report = shap_elimination.fit_compute(X, y)

# Make plots
performance_plot = shap_elimination.plot()

# Get final feature set
final_features_set = shap_elimination.get_reduced_features_set(num_features=3)

Source code in probatus/feature_elimination/feature_elimination.py
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
class EarlyStoppingShapRFECV(ShapRFECV):
    """
    This class performs Backwards Recursive Feature Elimination, using SHAP feature importance.

    This is a child of ShapRFECV which allows early stopping of the training step, this class is compatible with
        LightGBM, XGBoost and CatBoost models. If you are not using early stopping, you should use the parent class,
        ShapRFECV, instead of EarlyStoppingShapRFECV.

    [Early stopping](https://en.wikipedia.org/wiki/Early_stopping) is a type of
        regularization technique in which the model is trained until the scoring metric, measured on a validation set,
        stops improving after a number of early_stopping_rounds. In boosted tree models, this technique can increase
        the training speed, by skipping the training of trees that do not improve the scoring metric any further,
        which is particularly useful when the training dataset is large.

    Note that if the classifier is a hyperparameter search model is used, the early stopping parameter is passed only
        to the fit method of the model duiring the Shapley values estimation step, and not for the hyperparameter
        search step.
        Early stopping can be seen as a type of regularization of the optimal number of trees. Therefore you can use
        it directly with a LightGBM or XGBoost model, as an alternative to a hyperparameter search model.

    At each round, for a
        given feature set, starting from all available features, the following steps are applied:

    1. (Optional) Tune the hyperparameters of the model using sklearn compatible search CV e.g.
        [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LassoCV.html),
        [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html?highlight=randomized#sklearn.model_selection.RandomizedSearchCV), or
        [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html).
        Note that during this step the model does not use early stopping.
    2. Apply Cross-validation (CV) to estimate the SHAP feature importance on the provided dataset. In each CV
        iteration, the model is fitted on the train folds, and applied on the validation fold to estimate
        SHAP feature importance. The model is trained until the scoring metric eval_metric, measured on the
        validation fold, stops improving after a number of early_stopping_rounds.
    3. Remove `step` lowest SHAP importance features from the dataset.

    At the end of the process, the user can plot the performance of the model for each iteration, and select the
        optimal number of features and the features set.

    We recommend using [LGBMClassifier](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMClassifier.html),
        because by default it handles missing values and categorical features. In case of other models, make sure to
        handle these issues for your dataset and consider impact it might have on features importance.


    Example:
    ```python
    from lightgbm import LGBMClassifier
    import pandas as pd
    from probatus.feature_elimination import EarlyStoppingShapRFECV
    from sklearn.datasets import make_classification

    feature_names = [
        'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7',
        'f8', 'f9', 'f10', 'f11', 'f12', 'f13',
        'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20']

    # Prepare two samples
    X, y = make_classification(n_samples=200, class_sep=0.05, n_informative=6, n_features=20,
                               random_state=0, n_redundant=10, n_clusters_per_class=1)
    X = pd.DataFrame(X, columns=feature_names)

    # Prepare model
    clf = LGBMClassifier(n_estimators=200, max_depth=3)

    # Run feature elimination
    shap_elimination = EarlyStoppingShapRFECV(
        clf=clf, step=0.2, cv=10, scoring='roc_auc', early_stopping_rounds=10, n_jobs=3)
    report = shap_elimination.fit_compute(X, y)

    # Make plots
    performance_plot = shap_elimination.plot()

    # Get final feature set
    final_features_set = shap_elimination.get_reduced_features_set(num_features=3)
    ```
    <img src="../img/earlystoppingshaprfecv.png" width="500" />

    """  # noqa

    def __init__(
        self,
        clf,
        step=1,
        min_features_to_select=1,
        cv=None,
        scoring="roc_auc",
        n_jobs=-1,
        verbose=0,
        random_state=None,
        early_stopping_rounds=5,
        eval_metric="auc",
    ):
        """
        This method initializes the class.

        Args:
            clf (sklearn compatible classifier or regressor, sklearn compatible search CV e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV):
                A model that will be optimized and trained at each round of features elimination. The model must
                support early stopping of training, which is the case for XGBoost and LightGBM, for example. The
                recommended model is [LGBMClassifier](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMClassifier.html),
                because it by default handles the missing values and categorical variables. This parameter also supports
                any hyperparameter search schema that is consistent with the sklearn API e.g.
                [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html),
                [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)
                or [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html#skopt.BayesSearchCV).
                Note that if a hyperparemeter search model is used, the hyperparameters are tuned without early
                stopping. Early stopping is applied only during the Shapley values estimation for feature
                elimination. We recommend simply passing the model without hyperparameter optimization, or using
                ShapRFECV without early stopping.


            step (int or float, optional):
                Number of lowest importance features removed each round. If it is an int, then each round such number of
                features is discarded. If float, such percentage of remaining features (rounded down) is removed each
                iteration. It is recommended to use float, since it is faster for a large number of features, and slows
                down and becomes more precise towards less features. Note: the last round may remove fewer features in
                order to reach min_features_to_select.
                If columns_to_keep parameter is specified in the fit method, step is the number of features to remove after
                keeping those columns.

            min_features_to_select (int, optional):
                Minimum number of features to be kept. This is a stopping criterion of the feature elimination. By
                default the process stops when one feature is left. If columns_to_keep is specified in the fit method,
                it may override this parameter to the maximum between length of columns_to_keep the two.

            cv (int, cross-validation generator or an iterable, optional):
                Determines the cross-validation splitting strategy. Compatible with sklearn
                [cv parameter](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFECV.html).
                If None, then cv of 5 is used.

            scoring (string or probatus.utils.Scorer, optional):
                Metric for which the model performance is calculated. It can be either a metric name  aligned with predefined
                [classification scorers names in sklearn](https://scikit-learn.org/stable/modules/model_evaluation.html).
                Another option is using probatus.utils.Scorer to define a custom metric.

            n_jobs (int, optional):
                Number of cores to run in parallel while fitting across folds. None means 1 unless in a
                `joblib.parallel_backend` context. -1 means using all processors.

            verbose (int, optional):
                Controls verbosity of the output:

                - 0 - nether prints nor warnings are shown
                - 1 - 50 - only most important warnings
                - 51 - 100 - shows other warnings and prints
                - above 100 - presents all prints and all warnings (including SHAP warnings).

            random_state (int, optional):
                Random state set at each round of feature elimination. If it is None, the results will not be
                reproducible and in random search at each iteration a different hyperparameters might be tested. For
                reproducible results set it to integer.

            early_stopping_rounds (int, optional):
                Number of rounds with constant performance after which the model fitting stops. This is passed to the
                fit method of the model for Shapley values estimation, but not for hyperparameter search. Only
                supported by some models, such as XGBoost and LightGBM.

            eval_metric (str, optional):
                Metric for scoring fitting rounds and activating early stopping. This is passed to the
                fit method of the model for Shapley values estimation, but not for hyperparameter search. Only
                supported by some models, such as [XGBoost](https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters)
                 and [LightGBM](https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters).
                Note that `eval_metric` is an argument of the model's fit method and it is different from `scoring`.
        """  # noqa
        super().__init__(
            clf,
            step=step,
            min_features_to_select=min_features_to_select,
            cv=cv,
            scoring=scoring,
            n_jobs=n_jobs,
            verbose=verbose,
            random_state=random_state,
        )

        if self.search_clf:
            if self.verbose > 0:
                warnings.warn(
                    "Early stopping will be used only during Shapley value"
                    " estimation step, and not for hyperparameter"
                    " optimization."
                )

        if isinstance(early_stopping_rounds, int) and early_stopping_rounds > 0:
            self.early_stopping_rounds = early_stopping_rounds
        else:
            raise (
                ValueError(
                    f"The current value of early_stopping_rounds ="
                    f" {early_stopping_rounds} is not allowed."
                    f" It needs to be a positive integer."
                )
            )

        self.eval_metric = eval_metric

    def _get_fit_params_lightGBM(
        self, X_train, y_train, X_val, y_val, sample_weight=None, train_index=None, val_index=None
    ):
        """Get the fit parameters for for a LightGBM Model.

        Args:

            X_train (pd.DataFrame):
                Train Dataset used in CV.

            y_train (pd.Series):
                Train labels for X.

            X_val (pd.DataFrame):
                Validation Dataset used in CV.

            y_val (pd.Series):
                Validation labels for X.

            sample_weight (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,) - only use if the model you're using supports
                sample weighting (check the corresponding scikit-learn documentation).
                Array of weights that are assigned to individual samples.
                Note that they're only used for fitting of  the model, not during evaluation of metrics.
                If not provided, then each sample is given unit weight.

            train_index (np.array):
                Positions of train folds samples.

            val_index (np.array):
                Positions of validation fold samples.

        Raises:
            ValueError: if the clf is not supported.

        Returns:
            dict: fit parameters
        """
        from lightgbm import early_stopping, log_evaluation

        fit_params = {
            "X": X_train,
            "y": y_train,
            "eval_set": [(X_val, y_val)],
            "callbacks": [early_stopping(self.early_stopping_rounds, first_metric_only=True)],
        }
        if self.verbose >= 100:
            fit_params["callbacks"].append(log_evaluation(1))
        else:
            fit_params["callbacks"].append(log_evaluation(0))
        if sample_weight is not None:
            fit_params["sample_weight"] = sample_weight.iloc[train_index]
            fit_params["eval_sample_weight"] = [sample_weight.iloc[val_index]]
        return fit_params

    def _get_fit_params_XGBoost(
        self, X_train, y_train, X_val, y_val, sample_weight=None, train_index=None, val_index=None
    ):
        """Get the fit parameters for for a XGBoost Model.

        Args:

            X_train (pd.DataFrame):
                Train Dataset used in CV.

            y_train (pd.Series):
                Train labels for X.

            X_val (pd.DataFrame):
                Validation Dataset used in CV.

            y_val (pd.Series):
                Validation labels for X.

            sample_weight (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,) - only use if the model you're using supports
                sample weighting (check the corresponding scikit-learn documentation).
                Array of weights that are assigned to individual samples.
                Note that they're only used for fitting of  the model, not during evaluation of metrics.
                If not provided, then each sample is given unit weight.

            train_index (np.array):
                Positions of train folds samples.

            val_index (np.array):
                Positions of validation fold samples.

        Raises:
            ValueError: if the clf is not supported.

        Returns:
            dict: fit parameters
        """
        fit_params = {
            "X": X_train,
            "y": y_train,
            "eval_set": [(X_val, y_val)],
        }
        if sample_weight is not None:
            fit_params["sample_weight"] = sample_weight.iloc[train_index]
            fit_params["eval_sample_weight"] = [sample_weight.iloc[val_index]]
        return fit_params

    def _get_fit_params_CatBoost(
        self, X_train, y_train, X_val, y_val, sample_weight=None, train_index=None, val_index=None
    ):
        """Get the fit parameters for for a CatBoost Model.

        Args:

            X_train (pd.DataFrame):
                Train Dataset used in CV.

            y_train (pd.Series):
                Train labels for X.

            X_val (pd.DataFrame):
                Validation Dataset used in CV.

            y_val (pd.Series):
                Validation labels for X.

            sample_weight (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,) - only use if the model you're using supports
                sample weighting (check the corresponding scikit-learn documentation).
                Array of weights that are assigned to individual samples.
                Note that they're only used for fitting of  the model, not during evaluation of metrics.
                If not provided, then each sample is given unit weight.

            train_index (np.array):
                Positions of train folds samples.

            val_index (np.array):
                Positions of validation fold samples.

        Raises:
            ValueError: if the clf is not supported.

        Returns:
            dict: fit parameters
        """
        from catboost import Pool

        cat_features = [col for col in X_train.select_dtypes(include=["category"]).columns]
        fit_params = {
            "X": Pool(X_train, y_train, cat_features=cat_features),
            "eval_set": Pool(X_val, y_val, cat_features=cat_features),
            # Evaluation metric should be passed during initialization
        }
        if sample_weight is not None:
            fit_params["X"].set_weight(sample_weight.iloc[train_index])
            fit_params["eval_set"].set_weight(sample_weight.iloc[val_index])
        return fit_params

    def _get_fit_params(
        self, clf, X_train, y_train, X_val, y_val, sample_weight=None, train_index=None, val_index=None
    ):
        """Get the fit parameters for the specified classifier.

        Args:
            clf (classifier):
                Model to be fitted on the train folds.

            X_train (pd.DataFrame):
                Train Dataset used in CV.

            y_train (pd.Series):
                Train labels for X.

            X_val (pd.DataFrame):
                Validation Dataset used in CV.

            y_val (pd.Series):
                Validation labels for X.

            sample_weight (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,) - only use if the model you're using supports
                sample weighting (check the corresponding scikit-learn documentation).
                Array of weights that are assigned to individual samples.
                Note that they're only used for fitting of  the model, not during evaluation of metrics.
                If not provided, then each sample is given unit weight.

            train_index (np.array):
                Positions of train folds samples.

            val_index (np.array):
                Positions of validation fold samples.

        Raises:
            ValueError: if the clf is not supported.

        Returns:
            dict: fit parameters
        """
        # The lightgbm and xgboost imports are temporarily placed here, until the tests on
        # macOS have been fixed.

        try:
            from lightgbm import LGBMModel

            if isinstance(clf, LGBMModel):
                return self._get_fit_params_lightGBM(
                    X_train=X_train,
                    y_train=y_train,
                    X_val=X_val,
                    y_val=y_val,
                    sample_weight=sample_weight,
                    train_index=train_index,
                    val_index=val_index,
                )
        except ImportError:
            pass

        try:
            from xgboost.sklearn import XGBModel

            if isinstance(clf, XGBModel):
                return self._get_fit_params_XGBoost(
                    X_train=X_train,
                    y_train=y_train,
                    X_val=X_val,
                    y_val=y_val,
                    sample_weight=sample_weight,
                    train_index=train_index,
                    val_index=val_index,
                )
        except ImportError:
            pass

        try:
            from catboost import CatBoost

            if isinstance(clf, CatBoost):
                return self._get_fit_params_CatBoost(
                    X_train=X_train,
                    y_train=y_train,
                    X_val=X_val,
                    y_val=y_val,
                    sample_weight=sample_weight,
                    train_index=train_index,
                    val_index=val_index,
                )
        except ImportError:
            pass

        raise ValueError("Model type not supported")

    def _get_feature_shap_values_per_fold(
        self,
        X,
        y,
        clf,
        train_index,
        val_index,
        sample_weight=None,
        **shap_kwargs,
    ):
        """
        This function calculates the shap values on validation set, and Train and Val score.

        Args:
            X (pd.DataFrame):
                Dataset used in CV.

            y (pd.Series):
                Labels for X.

            sample_weight (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,) - only use if the model you're using supports
                sample weighting (check the corresponding scikit-learn documentation).
                Array of weights that are assigned to individual samples.
                Note that they're only used for fitting of  the model, not during evaluation of metrics.
                If not provided, then each sample is given unit weight.

            clf:
                Classifier to be fitted on the train folds.

            train_index (np.array):
                Positions of train folds samples.

            val_index (np.array):
                Positions of validation fold samples.

            **shap_kwargs:
                keyword arguments passed to
                [shap.Explainer](https://shap.readthedocs.io/en/latest/generated/shap.Explainer.html#shap.Explainer).
                It also enables `approximate` and `check_additivity` parameters, passed while calculating SHAP values.
                The `approximate=True` causes less accurate, but faster SHAP values calculation, while
                `check_additivity=False` disables the additivity check inside SHAP.
        Returns:
            (np.array, float, float):
                Tuple with the results: Shap Values on validation fold, train score, validation score.
        """
        X_train, X_val = X.iloc[train_index, :], X.iloc[val_index, :]
        y_train, y_val = y.iloc[train_index], y.iloc[val_index]

        fit_params = self._get_fit_params(
            clf=clf,
            X_train=X_train,
            y_train=y_train,
            X_val=X_val,
            y_val=y_val,
            sample_weight=sample_weight,
            train_index=train_index,
            val_index=val_index,
        )

        # Due to deprecation issues (compatibility with Sklearn) set some params
        # like below, instead of through fit().
        try:
            from lightgbm import LGBMModel

            if isinstance(clf, LGBMModel):
                clf.set_params(eval_metric=self.eval_metric)
        except ImportError:
            pass

        try:
            from xgboost.sklearn import XGBModel

            if isinstance(clf, XGBModel):
                clf.set_params(eval_metric=self.eval_metric, early_stopping_rounds=self.early_stopping_rounds)
        except ImportError:
            pass

        try:
            from catboost import CatBoost

            if isinstance(clf, CatBoost):
                clf.set_params(early_stopping_rounds=self.early_stopping_rounds)
        except ImportError:
            pass

        # Train the model
        clf = clf.fit(**fit_params)

        # Score the model
        score_train = self.scorer.scorer(clf, X_train, y_train)
        score_val = self.scorer.scorer(clf, X_val, y_val)

        # Compute SHAP values
        shap_values = shap_calc(clf, X_val, verbose=self.verbose, **shap_kwargs)
        return shap_values, score_train, score_val

__init__(clf, step=1, min_features_to_select=1, cv=None, scoring='roc_auc', n_jobs=-1, verbose=0, random_state=None, early_stopping_rounds=5, eval_metric='auc')

This method initializes the class.

Parameters:

Name Type Description Default
clf sklearn compatible classifier or regressor, sklearn compatible search CV e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV

A model that will be optimized and trained at each round of features elimination. The model must support early stopping of training, which is the case for XGBoost and LightGBM, for example. The recommended model is LGBMClassifier, because it by default handles the missing values and categorical variables. This parameter also supports any hyperparameter search schema that is consistent with the sklearn API e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV. Note that if a hyperparemeter search model is used, the hyperparameters are tuned without early stopping. Early stopping is applied only during the Shapley values estimation for feature elimination. We recommend simply passing the model without hyperparameter optimization, or using ShapRFECV without early stopping.

required
step int or float

Number of lowest importance features removed each round. If it is an int, then each round such number of features is discarded. If float, such percentage of remaining features (rounded down) is removed each iteration. It is recommended to use float, since it is faster for a large number of features, and slows down and becomes more precise towards less features. Note: the last round may remove fewer features in order to reach min_features_to_select. If columns_to_keep parameter is specified in the fit method, step is the number of features to remove after keeping those columns.

1
min_features_to_select int

Minimum number of features to be kept. This is a stopping criterion of the feature elimination. By default the process stops when one feature is left. If columns_to_keep is specified in the fit method, it may override this parameter to the maximum between length of columns_to_keep the two.

1
cv int, cross-validation generator or an iterable

Determines the cross-validation splitting strategy. Compatible with sklearn cv parameter. If None, then cv of 5 is used.

None
scoring string or Scorer

Metric for which the model performance is calculated. It can be either a metric name aligned with predefined classification scorers names in sklearn. Another option is using probatus.utils.Scorer to define a custom metric.

'roc_auc'
n_jobs int

Number of cores to run in parallel while fitting across folds. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors.

-1
verbose int

Controls verbosity of the output:

  • 0 - nether prints nor warnings are shown
  • 1 - 50 - only most important warnings
  • 51 - 100 - shows other warnings and prints
  • above 100 - presents all prints and all warnings (including SHAP warnings).
0
random_state int

Random state set at each round of feature elimination. If it is None, the results will not be reproducible and in random search at each iteration a different hyperparameters might be tested. For reproducible results set it to integer.

None
early_stopping_rounds int

Number of rounds with constant performance after which the model fitting stops. This is passed to the fit method of the model for Shapley values estimation, but not for hyperparameter search. Only supported by some models, such as XGBoost and LightGBM.

5
eval_metric str

Metric for scoring fitting rounds and activating early stopping. This is passed to the fit method of the model for Shapley values estimation, but not for hyperparameter search. Only supported by some models, such as XGBoost and LightGBM. Note that eval_metric is an argument of the model's fit method and it is different from scoring.

'auc'
Source code in probatus/feature_elimination/feature_elimination.py
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
def __init__(
    self,
    clf,
    step=1,
    min_features_to_select=1,
    cv=None,
    scoring="roc_auc",
    n_jobs=-1,
    verbose=0,
    random_state=None,
    early_stopping_rounds=5,
    eval_metric="auc",
):
    """
    This method initializes the class.

    Args:
        clf (sklearn compatible classifier or regressor, sklearn compatible search CV e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV):
            A model that will be optimized and trained at each round of features elimination. The model must
            support early stopping of training, which is the case for XGBoost and LightGBM, for example. The
            recommended model is [LGBMClassifier](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMClassifier.html),
            because it by default handles the missing values and categorical variables. This parameter also supports
            any hyperparameter search schema that is consistent with the sklearn API e.g.
            [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html),
            [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)
            or [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html#skopt.BayesSearchCV).
            Note that if a hyperparemeter search model is used, the hyperparameters are tuned without early
            stopping. Early stopping is applied only during the Shapley values estimation for feature
            elimination. We recommend simply passing the model without hyperparameter optimization, or using
            ShapRFECV without early stopping.


        step (int or float, optional):
            Number of lowest importance features removed each round. If it is an int, then each round such number of
            features is discarded. If float, such percentage of remaining features (rounded down) is removed each
            iteration. It is recommended to use float, since it is faster for a large number of features, and slows
            down and becomes more precise towards less features. Note: the last round may remove fewer features in
            order to reach min_features_to_select.
            If columns_to_keep parameter is specified in the fit method, step is the number of features to remove after
            keeping those columns.

        min_features_to_select (int, optional):
            Minimum number of features to be kept. This is a stopping criterion of the feature elimination. By
            default the process stops when one feature is left. If columns_to_keep is specified in the fit method,
            it may override this parameter to the maximum between length of columns_to_keep the two.

        cv (int, cross-validation generator or an iterable, optional):
            Determines the cross-validation splitting strategy. Compatible with sklearn
            [cv parameter](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFECV.html).
            If None, then cv of 5 is used.

        scoring (string or probatus.utils.Scorer, optional):
            Metric for which the model performance is calculated. It can be either a metric name  aligned with predefined
            [classification scorers names in sklearn](https://scikit-learn.org/stable/modules/model_evaluation.html).
            Another option is using probatus.utils.Scorer to define a custom metric.

        n_jobs (int, optional):
            Number of cores to run in parallel while fitting across folds. None means 1 unless in a
            `joblib.parallel_backend` context. -1 means using all processors.

        verbose (int, optional):
            Controls verbosity of the output:

            - 0 - nether prints nor warnings are shown
            - 1 - 50 - only most important warnings
            - 51 - 100 - shows other warnings and prints
            - above 100 - presents all prints and all warnings (including SHAP warnings).

        random_state (int, optional):
            Random state set at each round of feature elimination. If it is None, the results will not be
            reproducible and in random search at each iteration a different hyperparameters might be tested. For
            reproducible results set it to integer.

        early_stopping_rounds (int, optional):
            Number of rounds with constant performance after which the model fitting stops. This is passed to the
            fit method of the model for Shapley values estimation, but not for hyperparameter search. Only
            supported by some models, such as XGBoost and LightGBM.

        eval_metric (str, optional):
            Metric for scoring fitting rounds and activating early stopping. This is passed to the
            fit method of the model for Shapley values estimation, but not for hyperparameter search. Only
            supported by some models, such as [XGBoost](https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters)
             and [LightGBM](https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters).
            Note that `eval_metric` is an argument of the model's fit method and it is different from `scoring`.
    """  # noqa
    super().__init__(
        clf,
        step=step,
        min_features_to_select=min_features_to_select,
        cv=cv,
        scoring=scoring,
        n_jobs=n_jobs,
        verbose=verbose,
        random_state=random_state,
    )

    if self.search_clf:
        if self.verbose > 0:
            warnings.warn(
                "Early stopping will be used only during Shapley value"
                " estimation step, and not for hyperparameter"
                " optimization."
            )

    if isinstance(early_stopping_rounds, int) and early_stopping_rounds > 0:
        self.early_stopping_rounds = early_stopping_rounds
    else:
        raise (
            ValueError(
                f"The current value of early_stopping_rounds ="
                f" {early_stopping_rounds} is not allowed."
                f" It needs to be a positive integer."
            )
        )

    self.eval_metric = eval_metric

ShapRFECV

Bases: BaseFitComputePlotClass

This class performs Backwards Recursive Feature Elimination, using SHAP feature importance.

At each round, for a given feature set, starting from all available features, the following steps are applied:

  1. (Optional) Tune the hyperparameters of the model using sklearn compatible search CV e.g. GridSearchCV, RandomizedSearchCV, or BayesSearchCV,
  2. Apply Cross-validation (CV) to estimate the SHAP feature importance on the provided dataset. In each CV iteration, the model is fitted on the train folds, and applied on the validation fold to estimate SHAP feature importance.
  3. Remove step lowest SHAP importance features from the dataset.

At the end of the process, the user can plot the performance of the model for each iteration, and select the optimal number of features and the features set.

The functionality is similar to RFECV. The main difference is removing the lowest importance features based on SHAP features importance. It also supports the use of sklearn compatible search CV for hyperparameter optimization e.g. GridSearchCV, RandomizedSearchCV, or BayesSearchCV, which needs to be passed as the clf. Thanks to this you can perform hyperparameter optimization at each step of the feature elimination. Lastly, it supports categorical features (object and category dtype) and missing values in the data, as long as the model supports them.

We recommend using LGBMClassifier, because by default it handles missing values and categorical features. In case of other models, make sure to handle these issues for your dataset and consider impact it might have on features importance.

Example:

import numpy as np
import pandas as pd
from probatus.feature_elimination import ShapRFECV
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV

feature_names = [
    'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7',
    'f8', 'f9', 'f10', 'f11', 'f12', 'f13',
    'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20']

# Prepare two samples
X, y = make_classification(n_samples=200, class_sep=0.05, n_informative=6, n_features=20,
                           random_state=0, n_redundant=10, n_clusters_per_class=1)
X = pd.DataFrame(X, columns=feature_names)


# Prepare model and parameter search space
clf = RandomForestClassifier(max_depth=5, class_weight='balanced')

param_grid = {
    'n_estimators': [5, 7, 10],
    'min_samples_leaf': [3, 5, 7, 10],
}
search = RandomizedSearchCV(clf, param_grid)


# Run feature elimination
shap_elimination = ShapRFECV(
    clf=search, step=0.2, cv=10, scoring='roc_auc', n_jobs=3)
report = shap_elimination.fit_compute(X, y)

# Make plots
performance_plot = shap_elimination.plot()

# Get final feature set
final_features_set = shap_elimination.get_reduced_features_set(num_features=3)

Source code in probatus/feature_elimination/feature_elimination.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
class ShapRFECV(BaseFitComputePlotClass):
    """
    This class performs Backwards Recursive Feature Elimination, using SHAP feature importance.

    At each round, for a
        given feature set, starting from all available features, the following steps are applied:

    1. (Optional) Tune the hyperparameters of the model using sklearn compatible search CV e.g.
        [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LassoCV.html),
        [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html?highlight=randomized#sklearn.model_selection.RandomizedSearchCV), or
        [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html),
    2. Apply Cross-validation (CV) to estimate the SHAP feature importance on the provided dataset. In each CV
        iteration, the model is fitted on the train folds, and applied on the validation fold to estimate
        SHAP feature importance.
    3. Remove `step` lowest SHAP importance features from the dataset.

    At the end of the process, the user can plot the performance of the model for each iteration, and select the
        optimal number of features and the features set.

    The functionality is
        similar to [RFECV](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFECV.html).
        The main difference is removing the lowest importance features based on SHAP features importance. It also
        supports the use of sklearn compatible search CV for hyperparameter optimization e.g.
        [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LassoCV.html),
        [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html?highlight=randomized#sklearn.model_selection.RandomizedSearchCV), or
        [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html), which
        needs to be passed as the `clf`. Thanks to this you can perform hyperparameter optimization at each step of
        the feature elimination. Lastly, it supports categorical features (object and category dtype) and missing values
        in the data, as long as the model supports them.

    We recommend using [LGBMClassifier](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMClassifier.html),
        because by default it handles missing values and categorical features. In case of other models, make sure to
        handle these issues for your dataset and consider impact it might have on features importance.


    Example:
    ```python
    import numpy as np
    import pandas as pd
    from probatus.feature_elimination import ShapRFECV
    from sklearn.datasets import make_classification
    from sklearn.model_selection import train_test_split
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.model_selection import RandomizedSearchCV

    feature_names = [
        'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7',
        'f8', 'f9', 'f10', 'f11', 'f12', 'f13',
        'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20']

    # Prepare two samples
    X, y = make_classification(n_samples=200, class_sep=0.05, n_informative=6, n_features=20,
                               random_state=0, n_redundant=10, n_clusters_per_class=1)
    X = pd.DataFrame(X, columns=feature_names)


    # Prepare model and parameter search space
    clf = RandomForestClassifier(max_depth=5, class_weight='balanced')

    param_grid = {
        'n_estimators': [5, 7, 10],
        'min_samples_leaf': [3, 5, 7, 10],
    }
    search = RandomizedSearchCV(clf, param_grid)


    # Run feature elimination
    shap_elimination = ShapRFECV(
        clf=search, step=0.2, cv=10, scoring='roc_auc', n_jobs=3)
    report = shap_elimination.fit_compute(X, y)

    # Make plots
    performance_plot = shap_elimination.plot()

    # Get final feature set
    final_features_set = shap_elimination.get_reduced_features_set(num_features=3)
    ```
    <img src="../img/shaprfecv.png" width="500" />

    """  # noqa

    def __init__(
        self,
        clf,
        step=1,
        min_features_to_select=1,
        cv=None,
        scoring="roc_auc",
        n_jobs=-1,
        verbose=0,
        random_state=None,
    ):
        """
        This method initializes the class.

        Args:
            clf (classifier, sklearn compatible search CV e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV):
                A model that will be optimized and trained at each round of feature elimination. The recommended model
                is [LGBMClassifier](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMClassifier.html),
                because it by default handles the missing values and categorical variables. This parameter also supports
                any hyperparameter search schema that is consistent with the sklearn API e.g.
                [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html),
                [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)
                or [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html#skopt.BayesSearchCV).

            step (int or float, optional):
                Number of lowest importance features removed each round. If it is an int, then each round such a number of
                features are discarded. If float, such a percentage of remaining features (rounded down) is removed each
                iteration. It is recommended to use float, since it is faster for a large number of features, and slows
                down and becomes more precise with fewer features. Note: the last round may remove fewer features in
                order to reach min_features_to_select.
                If columns_to_keep parameter is specified in the fit method, step is the number of features to remove after
                keeping those columns.

            min_features_to_select (int, optional):
                Minimum number of features to be kept. This is a stopping criterion of the feature elimination. By
                default the process stops when one feature is left. If columns_to_keep is specified in the fit method,
                it may override this parameter to the maximum between length of columns_to_keep the two.

            cv (int, cross-validation generator or an iterable, optional):
                Determines the cross-validation splitting strategy. Compatible with sklearn
                [cv parameter](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFECV.html).
                If None, then cv of 5 is used.

            scoring (string or probatus.utils.Scorer, optional):
                Metric for which the model performance is calculated. It can be either a metric name aligned with predefined
                [classification scorers names in sklearn](https://scikit-learn.org/stable/modules/model_evaluation.html).
                Another option is using probatus.utils.Scorer to define a custom metric.

            n_jobs (int, optional):
                Number of cores to run in parallel while fitting across folds. None means 1 unless in a
                `joblib.parallel_backend` context. -1 means using all processors.

            verbose (int, optional):
                Controls verbosity of the output:

                - 0 - neither prints nor warnings are shown
                - 1 - 50 - only most important warnings
                - 51 - 100 - shows other warnings and prints
                - above 100 - presents all prints and all warnings (including SHAP warnings).

            random_state (int, optional):
                Random state set at each round of feature elimination. If it is None, the results will not be
                reproducible and in random search at each iteration a different hyperparameters might be tested. For
                reproducible results set it to an integer.
        """  # noqa
        self.clf = clf
        if isinstance(self.clf, BaseSearchCV):
            self.search_clf = True
        else:
            self.search_clf = False

        if (isinstance(step, int) or isinstance(step, float)) and step > 0:
            self.step = step
        else:
            raise (
                ValueError(
                    f"The current value of step = {step} is not allowed. "
                    f"It needs to be a positive integer or positive float."
                )
            )

        if isinstance(min_features_to_select, int) and min_features_to_select > 0:
            self.min_features_to_select = min_features_to_select
        else:
            raise (
                ValueError(
                    f"The current value of min_features_to_select = {min_features_to_select} is not allowed. "
                    f"It needs to be a greater than or equal to 0."
                )
            )

        self.cv = cv
        self.scorer = get_single_scorer(scoring)
        self.random_state = random_state
        self.n_jobs = n_jobs
        self.report_df = pd.DataFrame([])
        self.verbose = verbose

    def _get_current_features_to_remove(self, shap_importance_df, columns_to_keep=None):
        """
        Implements the logic used to determine which features to remove.

        If step is a positive integer,
            at each round step lowest SHAP importance features are selected. If it is a float, such percentage
            of remaining features (rounded up) is removed each iteration. It is recommended to use float, since it is
            faster for a large set of features, and slows down and becomes more precise with fewer features.

        Args:
            shap_importance_df (pd.DataFrame):
                DataFrame presenting SHAP importance of remaining features.

        Returns:
            (list):
                List of features to be removed at a given round.
        """

        # Bounding the variable.
        num_features_to_remove = 0

        # If columns_to_keep is not None, exclude those columns and
        # calculate features to remove.
        if columns_to_keep is not None:
            mask = shap_importance_df.index.isin(columns_to_keep)
            shap_importance_df = shap_importance_df[~mask]

        # If the step is an int remove n features.
        if isinstance(self.step, int):
            num_features_to_remove = self._calculate_number_of_features_to_remove(
                current_num_of_features=shap_importance_df.shape[0],
                num_features_to_remove=self.step,
                min_num_features_to_keep=self.min_features_to_select,
            )
        # If the step is a float remove n * number features that are left, rounded down
        elif isinstance(self.step, float):
            current_step = int(np.floor(shap_importance_df.shape[0] * self.step))
            # The step after rounding down should be at least 1
            if current_step < 1:
                current_step = 1

            num_features_to_remove = self._calculate_number_of_features_to_remove(
                current_num_of_features=shap_importance_df.shape[0],
                num_features_to_remove=current_step,
                min_num_features_to_keep=self.min_features_to_select,
            )

        if num_features_to_remove == 0:
            return []
        else:
            return shap_importance_df.iloc[-num_features_to_remove:].index.tolist()

    @staticmethod
    def _calculate_number_of_features_to_remove(
        current_num_of_features,
        num_features_to_remove,
        min_num_features_to_keep,
    ):
        """
        Calculates the number of features to be removed.

        Makes sure that after removal at least
            min_num_features_to_keep are kept

         Args:
            current_num_of_features (int):
                Current number of features in the data.

            num_features_to_remove (int):
                Number of features to be removed at this stage.

            min_num_features_to_keep (int):
                Minimum number of features to be left after removal.

        Returns:
            (int):
                Number of features to be removed.
        """
        num_features_after_removal = current_num_of_features - num_features_to_remove
        if num_features_after_removal >= min_num_features_to_keep:
            num_to_remove = num_features_to_remove
        else:
            # take all available features minus number of them that should stay
            num_to_remove = current_num_of_features - min_num_features_to_keep
        return num_to_remove

    def _report_current_results(
        self,
        round_number,
        current_features_set,
        features_to_remove,
        train_metric_mean,
        train_metric_std,
        val_metric_mean,
        val_metric_std,
    ):
        """
        This function adds the results from a current iteration to the report.

        Args:
            round_number (int):
                Current number of the round.

            current_features_set (list of str):
                Current list of features.

            features_to_remove (list of str):
                List of features to be removed at the end of this iteration.

            train_metric_mean (float or int):
                Mean scoring metric measured on train set during CV.

            train_metric_std (float or int):
                Std scoring metric measured on train set during CV.

            val_metric_mean (float or int):
                Mean scoring metric measured on validation set during CV.

            val_metric_std (float or int):
                Std scoring metric measured on validation set during CV.
        """

        current_results = {
            "num_features": len(current_features_set),
            "features_set": None,
            "eliminated_features": None,
            "train_metric_mean": train_metric_mean,
            "train_metric_std": train_metric_std,
            "val_metric_mean": val_metric_mean,
            "val_metric_std": val_metric_std,
        }

        current_row = pd.DataFrame(current_results, index=[round_number])
        current_row["features_set"] = [current_features_set]
        current_row["eliminated_features"] = [features_to_remove]

        self.report_df = pd.concat([self.report_df, current_row], axis=0)

    def _get_feature_shap_values_per_fold(
        self,
        X,
        y,
        clf,
        train_index,
        val_index,
        sample_weight=None,
        **shap_kwargs,
    ):
        """
        This function calculates the shap values on validation set, and Train and Val score.

        Args:
            X (pd.DataFrame):
                Dataset used in CV.

            y (pd.Series):
                Labels for X.

            clf (classifier):
                Model to be fitted on the train folds.

            train_index (np.array):
                Positions of train folds samples.

            val_index (np.array):
                Positions of validation fold samples.

            sample_weight (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,) - only use if the model you're using supports
                sample weighting (check the corresponding scikit-learn documentation).
                Array of weights that are assigned to individual samples.
                Note that they're only used for fitting of  the model, not during evaluation of metrics.
                If not provided, then each sample is given unit weight.

            **shap_kwargs:
                keyword arguments passed to
                [shap.Explainer](https://shap.readthedocs.io/en/latest/generated/shap.Explainer.html#shap.Explainer).
                It also enables `approximate` and `check_additivity` parameters, passed while calculating SHAP values.
                The `approximate=True` causes less accurate, but faster SHAP values calculation, while
                `check_additivity=False` disables the additivity check inside SHAP.
        Returns:
            (np.array, float, float):
                Tuple with the results: Shap Values on validation fold, train score, validation score.
        """
        X_train, X_val = X.iloc[train_index, :], X.iloc[val_index, :]
        y_train, y_val = y.iloc[train_index], y.iloc[val_index]

        if sample_weight is not None:
            clf = clf.fit(X_train, y_train, sample_weight=sample_weight.iloc[train_index])
        else:
            clf = clf.fit(X_train, y_train)

        # Score the model
        score_train = self.scorer.scorer(clf, X_train, y_train)
        score_val = self.scorer.scorer(clf, X_val, y_val)

        # Compute SHAP values
        shap_values = shap_calc(clf, X_val, verbose=self.verbose, **shap_kwargs)
        return shap_values, score_train, score_val

    def fit(
        self,
        X,
        y,
        sample_weight=None,
        columns_to_keep=None,
        column_names=None,
        groups=None,
        shap_variance_penalty_factor=None,
        **shap_kwargs,
    ):
        """
        Fits the object with the provided data.

        The algorithm starts with the entire dataset, and then sequentially
             eliminates features. If sklearn compatible search CV is passed as clf e.g.
             [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html),
             [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)
             or [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html),
             the hyperparameter optimization is applied at each step of the elimination.
             Then, the SHAP feature importance is calculated using Cross-Validation,
             and `step` lowest importance features are removed.

        Args:
            X (pd.DataFrame):
                Provided dataset.

            y (pd.Series):
                Labels for X.

            sample_weight (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,) - only use if the model you're using supports
                sample weighting (check the corresponding scikit-learn documentation).
                Array of weights that are assigned to individual samples.
                Note that they're only used for fitting of  the model, not during evaluation of metrics.
                If not provided, then each sample is given unit weight.

            columns_to_keep (list of str, optional):
                List of column names to keep. If given,
                these columns will not be eliminated by the feature elimination process.
                However, these feature will used for the calculation of the SHAP values.

            column_names (list of str, optional):
                List of feature names of the provided samples. If provided it will be used to overwrite the existing
                feature names. If not provided the existing feature names are used or default feature names are
                generated.

            groups (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,)
                Group labels for the samples used while splitting the dataset into train/test set.
                Only used in conjunction with a "Group" `cv` instance.
                (e.g. `sklearn.model_selection.GroupKFold`).

            shap_variance_penalty_factor (int or float, optional):
                Apply aggregation penalty when computing average of shap values for a given feature.
                Results in a preference for features that have smaller standard deviation of shap
                values (more coherent shap importance). Recommend value 0.5 - 1.0.
                Formula: penalized_shap_mean = (mean_shap - (std_shap * shap_variance_penalty_factor))

            **shap_kwargs:
                keyword arguments passed to
                [shap.Explainer](https://shap.readthedocs.io/en/latest/generated/shap.Explainer.html#shap.Explainer).
                It also enables `approximate` and `check_additivity` parameters, passed while calculating SHAP values.
                The `approximate=True` causes less accurate, but faster SHAP values calculation, while
                `check_additivity=False` disables the additivity check inside SHAP.

        Returns:
            (ShapRFECV): Fitted object.
        """
        # Set seed for results reproducibility
        if self.random_state is not None:
            np.random.seed(self.random_state)

        # If to columns_to_keep is not provided, then initialise it by an empty string.
        # If provided check if all the elements in columns_to_keep are of type string.
        if columns_to_keep is None:
            len_columns_to_keep = 0
        else:
            if all(isinstance(x, str) for x in columns_to_keep):
                len_columns_to_keep = len(columns_to_keep)
            else:
                raise (
                    ValueError(
                        "The current values of columns_to_keep are not allowed.All the elements should be strings."
                    )
                )

        # If the columns_to_keep parameter is provided, check if they match the column names in the X.
        if column_names is not None:
            if all(x in column_names for x in list(X.columns)):
                pass
            else:
                raise (ValueError("The column names in parameter columns_to_keep and column_names are not matching."))

        # Check that the total number of columns to select is less than total number of columns in the data.
        # only when both parameters are provided.
        if column_names is not None and columns_to_keep is not None:
            if (self.min_features_to_select + len_columns_to_keep) > len(self.column_names):
                raise ValueError(
                    "Minimum features to select is greater than number of features."
                    "Lower the value for min_features_to_select or number of columns in columns_to_keep"
                )

        # Check shap_variance_penalty_factor has acceptable value
        if shap_variance_penalty_factor is None:
            _shap_variance_penalty_factor = 0
        elif (
            isinstance(shap_variance_penalty_factor, float) or isinstance(shap_variance_penalty_factor, int)
        ) and shap_variance_penalty_factor >= 0:
            _shap_variance_penalty_factor = shap_variance_penalty_factor
        else:
            warnings.warn(
                "shap_variance_penalty_factor must be None, int or float. " "Setting shap_variance_penalty_factor = 0"
            )
            _shap_variance_penalty_factor = 0

        self.X, self.column_names = preprocess_data(X, X_name="X", column_names=column_names, verbose=self.verbose)
        self.y = preprocess_labels(y, y_name="y", index=self.X.index, verbose=self.verbose)
        if sample_weight is not None:
            if self.verbose > 0:
                warnings.warn(
                    "sample_weight is passed only to the fit method of the model, not the evaluation metrics."
                )
            sample_weight = assure_pandas_series(sample_weight, index=self.X.index)
        self.cv = check_cv(self.cv, self.y, classifier=is_classifier(self.clf))

        remaining_features = current_features_set = self.column_names
        round_number = 0

        # Stop when stopping criteria is met.
        stopping_criteria = np.max([self.min_features_to_select, len_columns_to_keep])

        # Setting up the min_features_to_select parameter.
        if columns_to_keep is None:
            pass
        else:
            self.min_features_to_select = 0
            # This ensures that, if columns_to_keep is provided ,
            # the last features remaining are only the columns_to_keep.
            if self.verbose > 50:
                warnings.warn(f"Minimum features to select : {stopping_criteria}")

        while len(current_features_set) > stopping_criteria:
            round_number += 1

            # Get current dataset info
            current_features_set = remaining_features
            if columns_to_keep is None:
                # Keeps the original order, while removing duplicate elements
                remaining_removeable_features = pd.Series(current_features_set).unique()
            else:
                # Keeps the original order, while removing duplicate elements
                remaining_removeable_features = pd.Series(list(current_features_set) + columns_to_keep).unique()

            current_X = self.X[remaining_removeable_features]

            # Set seed for results reproducibility
            if self.random_state is not None:
                np.random.seed(self.random_state)

            # Optimize parameters
            if self.search_clf:
                current_search_clf = clone(self.clf).fit(current_X, self.y)
                current_clf = current_search_clf.estimator.set_params(**current_search_clf.best_params_)
            else:
                current_clf = clone(self.clf)

            # Perform CV to estimate feature importance with SHAP
            results_per_fold = Parallel(n_jobs=self.n_jobs)(
                delayed(self._get_feature_shap_values_per_fold)(
                    X=current_X,
                    y=self.y,
                    clf=current_clf,
                    train_index=train_index,
                    val_index=val_index,
                    sample_weight=sample_weight,
                    **shap_kwargs,
                )
                for train_index, val_index in self.cv.split(current_X, self.y, groups)
            )

            if self.y.nunique() == 2 or is_regressor(current_clf):
                shap_values = np.vstack([current_result[0] for current_result in results_per_fold])
            else:  # multi-class case
                shap_values = np.hstack([current_result[0] for current_result in results_per_fold])

            scores_train = [current_result[1] for current_result in results_per_fold]
            scores_val = [current_result[2] for current_result in results_per_fold]

            # Calculate the shap features with remaining features and features to keep.

            shap_importance_df = calculate_shap_importance(
                shap_values, remaining_removeable_features, shap_variance_penalty_factor=_shap_variance_penalty_factor
            )

            # Get features to remove
            features_to_remove = self._get_current_features_to_remove(
                shap_importance_df, columns_to_keep=columns_to_keep
            )
            # Ensures the order of the first list is kept as it was originally,
            # while removing elements which are present in both lists.
            remaining_features = np.setdiff1d(
                pd.Series(current_features_set).unique(),
                pd.Series(features_to_remove).unique(),
                assume_unique=True,
            )

            # Report results
            self._report_current_results(
                round_number=round_number,
                current_features_set=current_features_set,
                features_to_remove=features_to_remove,
                train_metric_mean=np.round(np.mean(scores_train), 3),
                train_metric_std=np.round(np.std(scores_train), 3),
                val_metric_mean=np.round(np.mean(scores_val), 3),
                val_metric_std=np.round(np.std(scores_val), 3),
            )
            if self.verbose > 50:
                print(
                    f"Round: {round_number}, Current number of features: {len(current_features_set)}, "
                    f'Current performance: Train {self.report_df.loc[round_number]["train_metric_mean"]} '
                    f'+/- {self.report_df.loc[round_number]["train_metric_std"]}, CV Validation '
                    f'{self.report_df.loc[round_number]["val_metric_mean"]} '
                    f'+/- {self.report_df.loc[round_number]["val_metric_std"]}. \n'
                    f"Features left: {remaining_features}. "
                    f"Removed features at the end of the round: {features_to_remove}"
                )
        self.fitted = True
        return self

    def compute(self):
        """
        Checks if fit() method has been run.

        and computes the DataFrame with results of feature elimination for each round.

        Returns:
            (pd.DataFrame):
                DataFrame with results of feature elimination for each round.
        """
        self._check_if_fitted()

        return self.report_df

    def fit_compute(
        self,
        X,
        y,
        sample_weight=None,
        columns_to_keep=None,
        column_names=None,
        shap_variance_penalty_factor=None,
        **shap_kwargs,
    ):
        """
        Fits the object with the provided data.

        The algorithm starts with the entire dataset, and then sequentially
             eliminates features. If sklearn compatible search CV is passed as clf e.g.
             [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html),
             [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)
             or [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html),
             the hyperparameter optimization is applied at each step of the elimination.
             Then, the SHAP feature importance is calculated using Cross-Validation,
             and `step` lowest importance features are removed. At the end, the
             report containing results from each iteration is computed and returned to the user.

        Args:
            X (pd.DataFrame):
                Provided dataset.

            y (pd.Series):
                Labels for X.

            sample_weight (pd.Series, np.ndarray, list, optional):
                array-like of shape (n_samples,) - only use if the model you're using supports
                sample weighting (check the corresponding scikit-learn documentation).
                Array of weights that are assigned to individual samples.
                Note that they're only used for fitting of  the model, not during evaluation of metrics.
                If not provided, then each sample is given unit weight.

            columns_to_keep (list of str, optional):
                List of columns to keep. If given, these columns will not be eliminated.

            column_names (list of str, optional):
                List of feature names of the provided samples. If provided it will be used to overwrite the existing
                feature names. If not provided the existing feature names are used or default feature names are
                generated.

            shap_variance_penalty_factor (int or float, optional):
                Apply aggregation penalty when computing average of shap values for a given feature.
                Results in a preference for features that have smaller standard deviation of shap
                values (more coherent shap importance). Recommend value 0.5 - 1.0.
                Formula: penalized_shap_mean = (mean_shap - (std_shap * shap_variance_penalty_factor))

            **shap_kwargs:
                keyword arguments passed to
                [shap.Explainer](https://shap.readthedocs.io/en/latest/generated/shap.Explainer.html#shap.Explainer).
                It also enables `approximate` and `check_additivity` parameters, passed while calculating SHAP values.
                The `approximate=True` causes less accurate, but faster SHAP values calculation, while
                `check_additivity=False` disables the additivity check inside SHAP.

        Returns:
            (pd.DataFrame):
                DataFrame containing results of feature elimination from each iteration.
        """

        self.fit(
            X,
            y,
            sample_weight=sample_weight,
            columns_to_keep=columns_to_keep,
            column_names=column_names,
            shap_variance_penalty_factor=shap_variance_penalty_factor,
            **shap_kwargs,
        )
        return self.compute()

    def get_reduced_features_set(self, num_features, standard_error_threshold=1.0, return_type="feature_names"):
        """
        Gets the features set after the feature elimination process, for a given number of features.

        Args:
            num_features (int or str):
                If int: Number of features in the reduced features set.
                If str: One of the following automatic num feature selection methods supported:
                    1. best: strictly selects the num_features with the highest model score.
                    2. best_coherent: For iterations that are within standard_error_threshold of the highest
                    score, select the iteration with the lowest standard deviation of model score.
                    3. best_parsimonious: For iterations that are within standard_error_threshold of the
                    highest score, select the iteration with the fewest features.

            standard_error_threshold (float):
                If num_features is 'best_coherent' or 'best_parsimonious', this parameter is used.

            return_type:
                Accepts possible values of 'feature_names', 'support' or 'ranking'. These are defined as:
                    1. feature_names: returns column names
                    2. support: returns boolean mask
                    3. ranking: returns numeric ranking of features

        Returns:
            (list of str):
                Reduced features set.
        """
        self._check_if_fitted()

        if isinstance(num_features, str):
            best_num_features = self._get_best_num_features(
                best_method=num_features, standard_error_threshold=standard_error_threshold
            )
            if return_type == "feature_names":
                return self._get_feature_names(best_num_features)
            elif return_type == "support":
                feature_names_selected = self._get_feature_names(best_num_features)
                return self._get_feature_support(feature_names_selected)
            elif return_type == "ranking":
                return self._get_feature_ranking()

        elif isinstance(num_features, int):
            if return_type == "feature_names":
                return self._get_feature_names(num_features)
            elif return_type == "support":
                feature_names_selected = self._get_feature_names(num_features)
                return self._get_feature_support(feature_names_selected)
            elif return_type == "ranking":
                return self._get_feature_ranking()

        else:
            raise ValueError(
                "Parameter num_features can be of type int, or of type str with"
                "possible values of 'best', 'best_coherent' or 'best_parsimonious'"
            )

    def _get_best_num_features(self, best_method, standard_error_threshold=1.0):
        """
        Helper function to identify the best number of features to select as per some automatic
        feature selection strategy. Strategies supported are:
            1. best: strictly selects the num_features with the highest model score.
            2. best_coherent: For iterations that are within standard_error_threshold of the highest
            score, select the iteration with the lowest standard deviation of model score.
            3. best_parsimonious: For iterations that are within standard_error_threshold of the
            highest score, select the iteration with the fewest features.

        Args:
            best_method (str):
                Automatic best feature selection strategy. One of "best", "best_coherent" or
                "best_parsimonious".

            standard_error_threshold (float):
                Parameter used if best_method is 'best_coherent' or 'best_parsimonious'.
                Numeric value greater than zero.

        Returns:
            (int)
                num_features as per automatic feature selection strategy selected.
        """

        self._check_if_fitted()
        shap_report = self.report_df.copy()

        if (isinstance(standard_error_threshold, float) or isinstance(standard_error_threshold, int)) is not True:
            raise ValueError("Parameter standard_error_threshold must be int or float")
        elif standard_error_threshold < 0:
            raise ValueError("Parameter standard_error_threshold must be >= zero.")

        if best_method == "best":
            shap_report["eval_metric"] = shap_report["val_metric_mean"]
            best_iteration_idx = shap_report["eval_metric"].argmax()
            best_num_features = shap_report["num_features"].iloc[best_iteration_idx]

        elif best_method == "best_coherent":
            shap_report["eval_metric"] = (
                shap_report["val_metric_mean"] - shap_report["val_metric_std"] * standard_error_threshold
            )
            best_iteration_idx = shap_report["eval_metric"].argmax()
            # Find standard error threshold above which we want to focus
            best_val_metric_threshold = shap_report["eval_metric"].iloc[best_iteration_idx]
            # Drop iterations with val_metric below threshold
            shap_report = shap_report[shap_report["val_metric_mean"] >= best_val_metric_threshold]
            # Get iteration with smallest val_metric_std
            best_std_iteration_idx = shap_report["val_metric_std"].argmin()
            best_num_features = shap_report["num_features"].iloc[best_std_iteration_idx]

        elif best_method == "best_parsimonious":
            shap_report["eval_metric"] = (
                shap_report["val_metric_mean"] - shap_report["val_metric_std"] * standard_error_threshold
            )
            best_iteration_idx = shap_report["eval_metric"].argmax()
            # Find standard error threshold above which we want to focus
            best_val_metric_threshold = shap_report["eval_metric"].iloc[best_iteration_idx]
            # Drop iterations with val_metric below threshold
            shap_report = shap_report[shap_report["val_metric_mean"] >= best_val_metric_threshold]
            # Get iteration with smallest num_features
            best_parsimonious_iteration_idx = shap_report["num_features"].argmin()
            best_num_features = shap_report["num_features"].iloc[best_parsimonious_iteration_idx]

        else:
            raise ValueError(
                "The parameter best_method can take values of 'best', 'best_coherent' or 'best_parsimonious'"
            )

        # Log shap_report for users who want to inspect / debug
        if self.verbose > 50:
            print(shap_report)

        return best_num_features

    def _get_feature_names(self, num_features):
        """
        Helper function that takes num_features and returns the associated list of column/feature names.

        Args:
            num_features (int):
                Represents the top N features to get the column names for.

        Returns:
            (list of feature names)
                List of the names of the features representing top num_features
        """
        self._check_if_fitted()
        if num_features not in self.report_df.num_features.tolist():
            raise (
                ValueError(
                    f"The provided number of features has not been achieved at any stage of the process. "
                    f"You can select one of the following: {self.report_df.num_features.tolist()}"
                )
            )
        else:
            return self.report_df[self.report_df.num_features == num_features]["features_set"].values[0]

    def _get_feature_support(self, feature_names_selected):
        """
        Helper function that takes feature_names_selected and returns a boolean mask representing the columns
        that were selected by the RFECV method.

        Args:
            feature_names_selected (list):
                Represents the top N features to get the column names for.

        Returns:
            (list of bools)
                Boolean mask representing the features selected.
        """
        support = [True if col in feature_names_selected else False for col in self.column_names]
        return support

    def _get_feature_ranking(self):
        """
        Returns the feature ranking, such that ranking_[i] corresponds to the ranking position
        of the i-th feature. Selected (i.e., estimated best) features are assigned rank 1.

        Returns:
            (list of bools)
                Boolean mask representing the features selected.
        """

        flipped_report_df = self.report_df.iloc[::-1]

        # Some features are not eliminated. All have importance of zero (highest importance)
        features_not_eliminated = flipped_report_df["features_set"].iloc[0]
        features_not_eliminated_dict = {v: 0 for v in features_not_eliminated}

        # Eliminated features are ranked by shap importance
        features_eliminated = np.concatenate(flipped_report_df["eliminated_features"].to_numpy())
        features_eliminated_dict = {int(v): k + 1 for (k, v) in enumerate(features_eliminated)}

        # Combine dicts with rank info
        features_eliminated_dict.update(features_not_eliminated_dict)

        # Get ranking per the order of columns
        ranking = [features_eliminated_dict[col] for col in self.column_names]

        return ranking

    def plot(self, show=True, **figure_kwargs):
        """
        Generates plot of the model performance for each iteration of feature elimination.

        Args:
            show (bool, optional):
                If True, the plots are showed to the user, otherwise they are not shown. Not showing plot can be useful,
                when you want to edit the returned axis, before showing it.

            **figure_kwargs:
                Keyword arguments that are passed to the plt.figure, at its initialization.

        Returns:
            (plt.axis):
                Axis containing the performance plot.
        """
        x_ticks = list(reversed(self.report_df["num_features"].tolist()))

        fig = plt.figure(**figure_kwargs)

        plt.plot(
            self.report_df["num_features"],
            self.report_df["train_metric_mean"],
            label="Train Score",
        )
        plt.fill_between(
            pd.to_numeric(self.report_df.num_features, errors="coerce"),
            self.report_df["train_metric_mean"] - self.report_df["train_metric_std"],
            self.report_df["train_metric_mean"] + self.report_df["train_metric_std"],
            alpha=0.3,
        )

        plt.plot(
            self.report_df["num_features"],
            self.report_df["val_metric_mean"],
            label="Validation Score",
        )
        plt.fill_between(
            pd.to_numeric(self.report_df.num_features, errors="coerce"),
            self.report_df["val_metric_mean"] - self.report_df["val_metric_std"],
            self.report_df["val_metric_mean"] + self.report_df["val_metric_std"],
            alpha=0.3,
        )

        plt.xlabel("Number of features")
        plt.ylabel(f"Performance {self.scorer.metric_name}")
        plt.title("Backwards Feature Elimination using SHAP & CV")
        plt.legend(loc="lower left")
        fig.axes[0].invert_xaxis()
        fig.axes[0].set_xticks(x_ticks)
        if show:
            plt.show()
        else:
            plt.close()
        return fig

__init__(clf, step=1, min_features_to_select=1, cv=None, scoring='roc_auc', n_jobs=-1, verbose=0, random_state=None)

This method initializes the class.

Parameters:

Name Type Description Default
clf classifier, sklearn compatible search CV e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV

A model that will be optimized and trained at each round of feature elimination. The recommended model is LGBMClassifier, because it by default handles the missing values and categorical variables. This parameter also supports any hyperparameter search schema that is consistent with the sklearn API e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV.

required
step int or float

Number of lowest importance features removed each round. If it is an int, then each round such a number of features are discarded. If float, such a percentage of remaining features (rounded down) is removed each iteration. It is recommended to use float, since it is faster for a large number of features, and slows down and becomes more precise with fewer features. Note: the last round may remove fewer features in order to reach min_features_to_select. If columns_to_keep parameter is specified in the fit method, step is the number of features to remove after keeping those columns.

1
min_features_to_select int

Minimum number of features to be kept. This is a stopping criterion of the feature elimination. By default the process stops when one feature is left. If columns_to_keep is specified in the fit method, it may override this parameter to the maximum between length of columns_to_keep the two.

1
cv int, cross-validation generator or an iterable

Determines the cross-validation splitting strategy. Compatible with sklearn cv parameter. If None, then cv of 5 is used.

None
scoring string or Scorer

Metric for which the model performance is calculated. It can be either a metric name aligned with predefined classification scorers names in sklearn. Another option is using probatus.utils.Scorer to define a custom metric.

'roc_auc'
n_jobs int

Number of cores to run in parallel while fitting across folds. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors.

-1
verbose int

Controls verbosity of the output:

  • 0 - neither prints nor warnings are shown
  • 1 - 50 - only most important warnings
  • 51 - 100 - shows other warnings and prints
  • above 100 - presents all prints and all warnings (including SHAP warnings).
0
random_state int

Random state set at each round of feature elimination. If it is None, the results will not be reproducible and in random search at each iteration a different hyperparameters might be tested. For reproducible results set it to an integer.

None
Source code in probatus/feature_elimination/feature_elimination.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def __init__(
    self,
    clf,
    step=1,
    min_features_to_select=1,
    cv=None,
    scoring="roc_auc",
    n_jobs=-1,
    verbose=0,
    random_state=None,
):
    """
    This method initializes the class.

    Args:
        clf (classifier, sklearn compatible search CV e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV):
            A model that will be optimized and trained at each round of feature elimination. The recommended model
            is [LGBMClassifier](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMClassifier.html),
            because it by default handles the missing values and categorical variables. This parameter also supports
            any hyperparameter search schema that is consistent with the sklearn API e.g.
            [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html),
            [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)
            or [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html#skopt.BayesSearchCV).

        step (int or float, optional):
            Number of lowest importance features removed each round. If it is an int, then each round such a number of
            features are discarded. If float, such a percentage of remaining features (rounded down) is removed each
            iteration. It is recommended to use float, since it is faster for a large number of features, and slows
            down and becomes more precise with fewer features. Note: the last round may remove fewer features in
            order to reach min_features_to_select.
            If columns_to_keep parameter is specified in the fit method, step is the number of features to remove after
            keeping those columns.

        min_features_to_select (int, optional):
            Minimum number of features to be kept. This is a stopping criterion of the feature elimination. By
            default the process stops when one feature is left. If columns_to_keep is specified in the fit method,
            it may override this parameter to the maximum between length of columns_to_keep the two.

        cv (int, cross-validation generator or an iterable, optional):
            Determines the cross-validation splitting strategy. Compatible with sklearn
            [cv parameter](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFECV.html).
            If None, then cv of 5 is used.

        scoring (string or probatus.utils.Scorer, optional):
            Metric for which the model performance is calculated. It can be either a metric name aligned with predefined
            [classification scorers names in sklearn](https://scikit-learn.org/stable/modules/model_evaluation.html).
            Another option is using probatus.utils.Scorer to define a custom metric.

        n_jobs (int, optional):
            Number of cores to run in parallel while fitting across folds. None means 1 unless in a
            `joblib.parallel_backend` context. -1 means using all processors.

        verbose (int, optional):
            Controls verbosity of the output:

            - 0 - neither prints nor warnings are shown
            - 1 - 50 - only most important warnings
            - 51 - 100 - shows other warnings and prints
            - above 100 - presents all prints and all warnings (including SHAP warnings).

        random_state (int, optional):
            Random state set at each round of feature elimination. If it is None, the results will not be
            reproducible and in random search at each iteration a different hyperparameters might be tested. For
            reproducible results set it to an integer.
    """  # noqa
    self.clf = clf
    if isinstance(self.clf, BaseSearchCV):
        self.search_clf = True
    else:
        self.search_clf = False

    if (isinstance(step, int) or isinstance(step, float)) and step > 0:
        self.step = step
    else:
        raise (
            ValueError(
                f"The current value of step = {step} is not allowed. "
                f"It needs to be a positive integer or positive float."
            )
        )

    if isinstance(min_features_to_select, int) and min_features_to_select > 0:
        self.min_features_to_select = min_features_to_select
    else:
        raise (
            ValueError(
                f"The current value of min_features_to_select = {min_features_to_select} is not allowed. "
                f"It needs to be a greater than or equal to 0."
            )
        )

    self.cv = cv
    self.scorer = get_single_scorer(scoring)
    self.random_state = random_state
    self.n_jobs = n_jobs
    self.report_df = pd.DataFrame([])
    self.verbose = verbose

compute()

Checks if fit() method has been run.

and computes the DataFrame with results of feature elimination for each round.

Returns:

Type Description
DataFrame

DataFrame with results of feature elimination for each round.

Source code in probatus/feature_elimination/feature_elimination.py
631
632
633
634
635
636
637
638
639
640
641
642
643
def compute(self):
    """
    Checks if fit() method has been run.

    and computes the DataFrame with results of feature elimination for each round.

    Returns:
        (pd.DataFrame):
            DataFrame with results of feature elimination for each round.
    """
    self._check_if_fitted()

    return self.report_df

fit(X, y, sample_weight=None, columns_to_keep=None, column_names=None, groups=None, shap_variance_penalty_factor=None, **shap_kwargs)

Fits the object with the provided data.

The algorithm starts with the entire dataset, and then sequentially eliminates features. If sklearn compatible search CV is passed as clf e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV, the hyperparameter optimization is applied at each step of the elimination. Then, the SHAP feature importance is calculated using Cross-Validation, and step lowest importance features are removed.

Parameters:

Name Type Description Default
X DataFrame

Provided dataset.

required
y Series

Labels for X.

required
sample_weight (Series, ndarray, list)

array-like of shape (n_samples,) - only use if the model you're using supports sample weighting (check the corresponding scikit-learn documentation). Array of weights that are assigned to individual samples. Note that they're only used for fitting of the model, not during evaluation of metrics. If not provided, then each sample is given unit weight.

None
columns_to_keep list of str

List of column names to keep. If given, these columns will not be eliminated by the feature elimination process. However, these feature will used for the calculation of the SHAP values.

None
column_names list of str

List of feature names of the provided samples. If provided it will be used to overwrite the existing feature names. If not provided the existing feature names are used or default feature names are generated.

None
groups (Series, ndarray, list)

array-like of shape (n_samples,) Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a "Group" cv instance. (e.g. sklearn.model_selection.GroupKFold).

None
shap_variance_penalty_factor int or float

Apply aggregation penalty when computing average of shap values for a given feature. Results in a preference for features that have smaller standard deviation of shap values (more coherent shap importance). Recommend value 0.5 - 1.0. Formula: penalized_shap_mean = (mean_shap - (std_shap * shap_variance_penalty_factor))

None
**shap_kwargs

keyword arguments passed to shap.Explainer. It also enables approximate and check_additivity parameters, passed while calculating SHAP values. The approximate=True causes less accurate, but faster SHAP values calculation, while check_additivity=False disables the additivity check inside SHAP.

{}

Returns:

Type Description
ShapRFECV

Fitted object.

Source code in probatus/feature_elimination/feature_elimination.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
def fit(
    self,
    X,
    y,
    sample_weight=None,
    columns_to_keep=None,
    column_names=None,
    groups=None,
    shap_variance_penalty_factor=None,
    **shap_kwargs,
):
    """
    Fits the object with the provided data.

    The algorithm starts with the entire dataset, and then sequentially
         eliminates features. If sklearn compatible search CV is passed as clf e.g.
         [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html),
         [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)
         or [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html),
         the hyperparameter optimization is applied at each step of the elimination.
         Then, the SHAP feature importance is calculated using Cross-Validation,
         and `step` lowest importance features are removed.

    Args:
        X (pd.DataFrame):
            Provided dataset.

        y (pd.Series):
            Labels for X.

        sample_weight (pd.Series, np.ndarray, list, optional):
            array-like of shape (n_samples,) - only use if the model you're using supports
            sample weighting (check the corresponding scikit-learn documentation).
            Array of weights that are assigned to individual samples.
            Note that they're only used for fitting of  the model, not during evaluation of metrics.
            If not provided, then each sample is given unit weight.

        columns_to_keep (list of str, optional):
            List of column names to keep. If given,
            these columns will not be eliminated by the feature elimination process.
            However, these feature will used for the calculation of the SHAP values.

        column_names (list of str, optional):
            List of feature names of the provided samples. If provided it will be used to overwrite the existing
            feature names. If not provided the existing feature names are used or default feature names are
            generated.

        groups (pd.Series, np.ndarray, list, optional):
            array-like of shape (n_samples,)
            Group labels for the samples used while splitting the dataset into train/test set.
            Only used in conjunction with a "Group" `cv` instance.
            (e.g. `sklearn.model_selection.GroupKFold`).

        shap_variance_penalty_factor (int or float, optional):
            Apply aggregation penalty when computing average of shap values for a given feature.
            Results in a preference for features that have smaller standard deviation of shap
            values (more coherent shap importance). Recommend value 0.5 - 1.0.
            Formula: penalized_shap_mean = (mean_shap - (std_shap * shap_variance_penalty_factor))

        **shap_kwargs:
            keyword arguments passed to
            [shap.Explainer](https://shap.readthedocs.io/en/latest/generated/shap.Explainer.html#shap.Explainer).
            It also enables `approximate` and `check_additivity` parameters, passed while calculating SHAP values.
            The `approximate=True` causes less accurate, but faster SHAP values calculation, while
            `check_additivity=False` disables the additivity check inside SHAP.

    Returns:
        (ShapRFECV): Fitted object.
    """
    # Set seed for results reproducibility
    if self.random_state is not None:
        np.random.seed(self.random_state)

    # If to columns_to_keep is not provided, then initialise it by an empty string.
    # If provided check if all the elements in columns_to_keep are of type string.
    if columns_to_keep is None:
        len_columns_to_keep = 0
    else:
        if all(isinstance(x, str) for x in columns_to_keep):
            len_columns_to_keep = len(columns_to_keep)
        else:
            raise (
                ValueError(
                    "The current values of columns_to_keep are not allowed.All the elements should be strings."
                )
            )

    # If the columns_to_keep parameter is provided, check if they match the column names in the X.
    if column_names is not None:
        if all(x in column_names for x in list(X.columns)):
            pass
        else:
            raise (ValueError("The column names in parameter columns_to_keep and column_names are not matching."))

    # Check that the total number of columns to select is less than total number of columns in the data.
    # only when both parameters are provided.
    if column_names is not None and columns_to_keep is not None:
        if (self.min_features_to_select + len_columns_to_keep) > len(self.column_names):
            raise ValueError(
                "Minimum features to select is greater than number of features."
                "Lower the value for min_features_to_select or number of columns in columns_to_keep"
            )

    # Check shap_variance_penalty_factor has acceptable value
    if shap_variance_penalty_factor is None:
        _shap_variance_penalty_factor = 0
    elif (
        isinstance(shap_variance_penalty_factor, float) or isinstance(shap_variance_penalty_factor, int)
    ) and shap_variance_penalty_factor >= 0:
        _shap_variance_penalty_factor = shap_variance_penalty_factor
    else:
        warnings.warn(
            "shap_variance_penalty_factor must be None, int or float. " "Setting shap_variance_penalty_factor = 0"
        )
        _shap_variance_penalty_factor = 0

    self.X, self.column_names = preprocess_data(X, X_name="X", column_names=column_names, verbose=self.verbose)
    self.y = preprocess_labels(y, y_name="y", index=self.X.index, verbose=self.verbose)
    if sample_weight is not None:
        if self.verbose > 0:
            warnings.warn(
                "sample_weight is passed only to the fit method of the model, not the evaluation metrics."
            )
        sample_weight = assure_pandas_series(sample_weight, index=self.X.index)
    self.cv = check_cv(self.cv, self.y, classifier=is_classifier(self.clf))

    remaining_features = current_features_set = self.column_names
    round_number = 0

    # Stop when stopping criteria is met.
    stopping_criteria = np.max([self.min_features_to_select, len_columns_to_keep])

    # Setting up the min_features_to_select parameter.
    if columns_to_keep is None:
        pass
    else:
        self.min_features_to_select = 0
        # This ensures that, if columns_to_keep is provided ,
        # the last features remaining are only the columns_to_keep.
        if self.verbose > 50:
            warnings.warn(f"Minimum features to select : {stopping_criteria}")

    while len(current_features_set) > stopping_criteria:
        round_number += 1

        # Get current dataset info
        current_features_set = remaining_features
        if columns_to_keep is None:
            # Keeps the original order, while removing duplicate elements
            remaining_removeable_features = pd.Series(current_features_set).unique()
        else:
            # Keeps the original order, while removing duplicate elements
            remaining_removeable_features = pd.Series(list(current_features_set) + columns_to_keep).unique()

        current_X = self.X[remaining_removeable_features]

        # Set seed for results reproducibility
        if self.random_state is not None:
            np.random.seed(self.random_state)

        # Optimize parameters
        if self.search_clf:
            current_search_clf = clone(self.clf).fit(current_X, self.y)
            current_clf = current_search_clf.estimator.set_params(**current_search_clf.best_params_)
        else:
            current_clf = clone(self.clf)

        # Perform CV to estimate feature importance with SHAP
        results_per_fold = Parallel(n_jobs=self.n_jobs)(
            delayed(self._get_feature_shap_values_per_fold)(
                X=current_X,
                y=self.y,
                clf=current_clf,
                train_index=train_index,
                val_index=val_index,
                sample_weight=sample_weight,
                **shap_kwargs,
            )
            for train_index, val_index in self.cv.split(current_X, self.y, groups)
        )

        if self.y.nunique() == 2 or is_regressor(current_clf):
            shap_values = np.vstack([current_result[0] for current_result in results_per_fold])
        else:  # multi-class case
            shap_values = np.hstack([current_result[0] for current_result in results_per_fold])

        scores_train = [current_result[1] for current_result in results_per_fold]
        scores_val = [current_result[2] for current_result in results_per_fold]

        # Calculate the shap features with remaining features and features to keep.

        shap_importance_df = calculate_shap_importance(
            shap_values, remaining_removeable_features, shap_variance_penalty_factor=_shap_variance_penalty_factor
        )

        # Get features to remove
        features_to_remove = self._get_current_features_to_remove(
            shap_importance_df, columns_to_keep=columns_to_keep
        )
        # Ensures the order of the first list is kept as it was originally,
        # while removing elements which are present in both lists.
        remaining_features = np.setdiff1d(
            pd.Series(current_features_set).unique(),
            pd.Series(features_to_remove).unique(),
            assume_unique=True,
        )

        # Report results
        self._report_current_results(
            round_number=round_number,
            current_features_set=current_features_set,
            features_to_remove=features_to_remove,
            train_metric_mean=np.round(np.mean(scores_train), 3),
            train_metric_std=np.round(np.std(scores_train), 3),
            val_metric_mean=np.round(np.mean(scores_val), 3),
            val_metric_std=np.round(np.std(scores_val), 3),
        )
        if self.verbose > 50:
            print(
                f"Round: {round_number}, Current number of features: {len(current_features_set)}, "
                f'Current performance: Train {self.report_df.loc[round_number]["train_metric_mean"]} '
                f'+/- {self.report_df.loc[round_number]["train_metric_std"]}, CV Validation '
                f'{self.report_df.loc[round_number]["val_metric_mean"]} '
                f'+/- {self.report_df.loc[round_number]["val_metric_std"]}. \n'
                f"Features left: {remaining_features}. "
                f"Removed features at the end of the round: {features_to_remove}"
            )
    self.fitted = True
    return self

fit_compute(X, y, sample_weight=None, columns_to_keep=None, column_names=None, shap_variance_penalty_factor=None, **shap_kwargs)

Fits the object with the provided data.

The algorithm starts with the entire dataset, and then sequentially eliminates features. If sklearn compatible search CV is passed as clf e.g. GridSearchCV, RandomizedSearchCV or BayesSearchCV, the hyperparameter optimization is applied at each step of the elimination. Then, the SHAP feature importance is calculated using Cross-Validation, and step lowest importance features are removed. At the end, the report containing results from each iteration is computed and returned to the user.

Parameters:

Name Type Description Default
X DataFrame

Provided dataset.

required
y Series

Labels for X.

required
sample_weight (Series, ndarray, list)

array-like of shape (n_samples,) - only use if the model you're using supports sample weighting (check the corresponding scikit-learn documentation). Array of weights that are assigned to individual samples. Note that they're only used for fitting of the model, not during evaluation of metrics. If not provided, then each sample is given unit weight.

None
columns_to_keep list of str

List of columns to keep. If given, these columns will not be eliminated.

None
column_names list of str

List of feature names of the provided samples. If provided it will be used to overwrite the existing feature names. If not provided the existing feature names are used or default feature names are generated.

None
shap_variance_penalty_factor int or float

Apply aggregation penalty when computing average of shap values for a given feature. Results in a preference for features that have smaller standard deviation of shap values (more coherent shap importance). Recommend value 0.5 - 1.0. Formula: penalized_shap_mean = (mean_shap - (std_shap * shap_variance_penalty_factor))

None
**shap_kwargs

keyword arguments passed to shap.Explainer. It also enables approximate and check_additivity parameters, passed while calculating SHAP values. The approximate=True causes less accurate, but faster SHAP values calculation, while check_additivity=False disables the additivity check inside SHAP.

{}

Returns:

Type Description
DataFrame

DataFrame containing results of feature elimination from each iteration.

Source code in probatus/feature_elimination/feature_elimination.py
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def fit_compute(
    self,
    X,
    y,
    sample_weight=None,
    columns_to_keep=None,
    column_names=None,
    shap_variance_penalty_factor=None,
    **shap_kwargs,
):
    """
    Fits the object with the provided data.

    The algorithm starts with the entire dataset, and then sequentially
         eliminates features. If sklearn compatible search CV is passed as clf e.g.
         [GridSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html),
         [RandomizedSearchCV](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)
         or [BayesSearchCV](https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html),
         the hyperparameter optimization is applied at each step of the elimination.
         Then, the SHAP feature importance is calculated using Cross-Validation,
         and `step` lowest importance features are removed. At the end, the
         report containing results from each iteration is computed and returned to the user.

    Args:
        X (pd.DataFrame):
            Provided dataset.

        y (pd.Series):
            Labels for X.

        sample_weight (pd.Series, np.ndarray, list, optional):
            array-like of shape (n_samples,) - only use if the model you're using supports
            sample weighting (check the corresponding scikit-learn documentation).
            Array of weights that are assigned to individual samples.
            Note that they're only used for fitting of  the model, not during evaluation of metrics.
            If not provided, then each sample is given unit weight.

        columns_to_keep (list of str, optional):
            List of columns to keep. If given, these columns will not be eliminated.

        column_names (list of str, optional):
            List of feature names of the provided samples. If provided it will be used to overwrite the existing
            feature names. If not provided the existing feature names are used or default feature names are
            generated.

        shap_variance_penalty_factor (int or float, optional):
            Apply aggregation penalty when computing average of shap values for a given feature.
            Results in a preference for features that have smaller standard deviation of shap
            values (more coherent shap importance). Recommend value 0.5 - 1.0.
            Formula: penalized_shap_mean = (mean_shap - (std_shap * shap_variance_penalty_factor))

        **shap_kwargs:
            keyword arguments passed to
            [shap.Explainer](https://shap.readthedocs.io/en/latest/generated/shap.Explainer.html#shap.Explainer).
            It also enables `approximate` and `check_additivity` parameters, passed while calculating SHAP values.
            The `approximate=True` causes less accurate, but faster SHAP values calculation, while
            `check_additivity=False` disables the additivity check inside SHAP.

    Returns:
        (pd.DataFrame):
            DataFrame containing results of feature elimination from each iteration.
    """

    self.fit(
        X,
        y,
        sample_weight=sample_weight,
        columns_to_keep=columns_to_keep,
        column_names=column_names,
        shap_variance_penalty_factor=shap_variance_penalty_factor,
        **shap_kwargs,
    )
    return self.compute()

get_reduced_features_set(num_features, standard_error_threshold=1.0, return_type='feature_names')

Gets the features set after the feature elimination process, for a given number of features.

Parameters:

Name Type Description Default
num_features int or str

If int: Number of features in the reduced features set. If str: One of the following automatic num feature selection methods supported: 1. best: strictly selects the num_features with the highest model score. 2. best_coherent: For iterations that are within standard_error_threshold of the highest score, select the iteration with the lowest standard deviation of model score. 3. best_parsimonious: For iterations that are within standard_error_threshold of the highest score, select the iteration with the fewest features.

required
standard_error_threshold float

If num_features is 'best_coherent' or 'best_parsimonious', this parameter is used.

1.0
return_type

Accepts possible values of 'feature_names', 'support' or 'ranking'. These are defined as: 1. feature_names: returns column names 2. support: returns boolean mask 3. ranking: returns numeric ranking of features

'feature_names'

Returns:

Type Description
list of str

Reduced features set.

Source code in probatus/feature_elimination/feature_elimination.py
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
def get_reduced_features_set(self, num_features, standard_error_threshold=1.0, return_type="feature_names"):
    """
    Gets the features set after the feature elimination process, for a given number of features.

    Args:
        num_features (int or str):
            If int: Number of features in the reduced features set.
            If str: One of the following automatic num feature selection methods supported:
                1. best: strictly selects the num_features with the highest model score.
                2. best_coherent: For iterations that are within standard_error_threshold of the highest
                score, select the iteration with the lowest standard deviation of model score.
                3. best_parsimonious: For iterations that are within standard_error_threshold of the
                highest score, select the iteration with the fewest features.

        standard_error_threshold (float):
            If num_features is 'best_coherent' or 'best_parsimonious', this parameter is used.

        return_type:
            Accepts possible values of 'feature_names', 'support' or 'ranking'. These are defined as:
                1. feature_names: returns column names
                2. support: returns boolean mask
                3. ranking: returns numeric ranking of features

    Returns:
        (list of str):
            Reduced features set.
    """
    self._check_if_fitted()

    if isinstance(num_features, str):
        best_num_features = self._get_best_num_features(
            best_method=num_features, standard_error_threshold=standard_error_threshold
        )
        if return_type == "feature_names":
            return self._get_feature_names(best_num_features)
        elif return_type == "support":
            feature_names_selected = self._get_feature_names(best_num_features)
            return self._get_feature_support(feature_names_selected)
        elif return_type == "ranking":
            return self._get_feature_ranking()

    elif isinstance(num_features, int):
        if return_type == "feature_names":
            return self._get_feature_names(num_features)
        elif return_type == "support":
            feature_names_selected = self._get_feature_names(num_features)
            return self._get_feature_support(feature_names_selected)
        elif return_type == "ranking":
            return self._get_feature_ranking()

    else:
        raise ValueError(
            "Parameter num_features can be of type int, or of type str with"
            "possible values of 'best', 'best_coherent' or 'best_parsimonious'"
        )

plot(show=True, **figure_kwargs)

Generates plot of the model performance for each iteration of feature elimination.

Parameters:

Name Type Description Default
show bool

If True, the plots are showed to the user, otherwise they are not shown. Not showing plot can be useful, when you want to edit the returned axis, before showing it.

True
**figure_kwargs

Keyword arguments that are passed to the plt.figure, at its initialization.

{}

Returns:

Type Description
axis

Axis containing the performance plot.

Source code in probatus/feature_elimination/feature_elimination.py
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
def plot(self, show=True, **figure_kwargs):
    """
    Generates plot of the model performance for each iteration of feature elimination.

    Args:
        show (bool, optional):
            If True, the plots are showed to the user, otherwise they are not shown. Not showing plot can be useful,
            when you want to edit the returned axis, before showing it.

        **figure_kwargs:
            Keyword arguments that are passed to the plt.figure, at its initialization.

    Returns:
        (plt.axis):
            Axis containing the performance plot.
    """
    x_ticks = list(reversed(self.report_df["num_features"].tolist()))

    fig = plt.figure(**figure_kwargs)

    plt.plot(
        self.report_df["num_features"],
        self.report_df["train_metric_mean"],
        label="Train Score",
    )
    plt.fill_between(
        pd.to_numeric(self.report_df.num_features, errors="coerce"),
        self.report_df["train_metric_mean"] - self.report_df["train_metric_std"],
        self.report_df["train_metric_mean"] + self.report_df["train_metric_std"],
        alpha=0.3,
    )

    plt.plot(
        self.report_df["num_features"],
        self.report_df["val_metric_mean"],
        label="Validation Score",
    )
    plt.fill_between(
        pd.to_numeric(self.report_df.num_features, errors="coerce"),
        self.report_df["val_metric_mean"] - self.report_df["val_metric_std"],
        self.report_df["val_metric_mean"] + self.report_df["val_metric_std"],
        alpha=0.3,
    )

    plt.xlabel("Number of features")
    plt.ylabel(f"Performance {self.scorer.metric_name}")
    plt.title("Backwards Feature Elimination using SHAP & CV")
    plt.legend(loc="lower left")
    fig.axes[0].invert_xaxis()
    fig.axes[0].set_xticks(x_ticks)
    if show:
        plt.show()
    else:
        plt.close()
    return fig