class feature_engine.selection.SelectByTargetMeanPerformance(variables=None, bins=5, strategy='equal_width', scoring='roc_auc', cv=3, threshold=None, regression=False, confirm_variables=False)[source]#

SelectByTargetMeanPerformance() uses the mean value of the target per category or per interval(if the variable is numerical), as proxy for target estimation. With this proxy, the selector determines the performance of each feature based on a metric of choice, and then selects the features based on this performance value.

SelectByTargetMeanPerformance() can evaluate numerical and categorical variables, without much prior manipulation. In other words, you don’t need to encode the categorical variables or transform the numerical variables to assess their importance if you use this transformer.

SelectByTargetMeanPerformance() requires that the dataset is complete, without missing data.

SelectByTargetMeanPerformance() determines the performance of each variable with cross-validation. More specifically:

For each categorical variable:

  1. Determines the mean target value per category in the training folds.

  2. Replaces the categories by the target mean values in the test folds.

  3. Determines the performance of the transformed variables in the test folds.

For each numerical variable:

  1. Discretises the variable into intervals of equal width or equal frequency.

  2. Determines the mean value of the target per interval in the training folds.

  3. Replaces the intervals by the target mean values in the test fold.

  4. Determines the performance of the transformed variable in the test fold.

Finally, it selects the features which performance is bigger than the indicated threshold. If the threshold if left to None, it selects features which performance is bigger than the mean performance of all features.

All the steps are performed with cross-validation. That means, that intervals and target mean values per interval or category are determined in a certain portion of the data, and evaluated in a left-out sample. The performance metric per variable is the average across the cross-validation folds.

More details in the User Guide.

variables: list, default=None

The list of variables to evaluate. If None, the transformer will evaluate all variables in the dataset (except datetime).

bins: int, default = 5

If the dataset contains numerical variables, the number of bins into which the values will be sorted.

strategy: str, default = ‘equal_width’

Whether the bins should be of equal width (‘equal_width’) or equal frequency (‘equal_frequency’).

scoring: str, default=’roc_auc’

Metric to evaluate the performance of the estimator. Comes from sklearn.metrics. See the model evaluation documentation for more options:

threshold: float, int, default = 0.01

The value that defines whether a feature will be selected. Note that for metrics like the roc-auc, r2, and the accuracy, the threshold will be a float between 0 and 1. For metrics like the mean squared error and the root mean squared error, the threshold can take any number. The threshold must be defined by the user. With bigger thresholds, fewer features will be selected.

cv: int, cross-validation generator or an iterable, default=3

Determines the cross-validation splitting strategy. Possible inputs for cv are:

For int/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. These splitters are instantiated with shuffle=False so the splits will be the same across calls. For more details check Scikit-learn’s cross_validate’s documentation.

regression: boolean, default=True

Indicates whether the target is one for regression or a classification.

confirm_variables: bool, default=False

If set to True, variables that are not present in the input dataframe will be removed from the list of variables. Only used when passing a variable list to the parameter variables. See parameter variables for more details.


The variables that will be considered for the feature selection procedure.


Dictionary with the performance of each feature.


List with the features that will be removed.


List with the names of features seen during fit.


The number of features in the train set used in fit.


Replacing the categories or intervals by the target mean is the equivalent to target mean encoding.



Miller, et al. “Predicting customer behaviour: The University of Melbourne’s KDD Cup report”. JMLR Workshop and Conference Proceeding. KDD 2009


>>> from sklearn.ensemble import RandomForestClassifier
>>> from feature_engine.selection import SelectByTargetMeanPerformance
>>> X = pd.DataFrame(dict(x1 = [1000,2000,1000,1000,2000,3000],
>>>                     x2 = [1,1,1,0,0,0],
>>>                     x3 = [1,2,1,1,0,1],
>>>                     x4 = [1,1,1,1,1,1]))
>>> y = pd.Series([1,0,0,1,1,0])
>>> tmp = SelectByTargetMeanPerformance(bins = 3, cv=2,scoring='accuracy')
>>> tmp.fit_transform(X, y)
    x2  x3  x4
0   1   1   1
1   1   2   1
2   1   1   1
3   0   1   1
4   0   0   1
5   0   1   1

This transformer also works with Categorical examples:

>>> X = pd.DataFrame(dict(x1 = ["a","b","a","a","b","b"],
>>>             x2 = ["a","a","a","b","b","b"]))
>>> y = pd.Series([1,0,0,1,1,0])
>>> tmp = SelectByTargetMeanPerformance(bins = 3, cv=2,scoring='accuracy')
>>> tmp.fit_transform(X, y)
0  a
1  a
2  a
3  b
4  b
5  b



Find the important features.


Fit to data, then transform it.


Get output feature names for transformation.


Get parameters for this estimator.


Set the parameters of this estimator.


Get a mask, or integer index, of the features selected.


Reduce X to the selected features.

fit(X, y)[source]#

Find the important features.

X: pandas dataframe of shape = [n_samples, n_features]

The input dataframe.

y: array-like of shape (n_samples)

Target variable. Required to train the estimator.

fit_transform(X, y=None, **fit_params)[source]#

Fit to data, then transform it.

Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.

Xarray-like of shape (n_samples, n_features)

Input samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).


Additional fit parameters.

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.


Get output feature names for transformation. In other words, returns the variable names of transformed dataframe.

input_featuresarray or list, default=None

This parameter exits only for compatibility with the Scikit-learn pipeline.

  • If None, then feature_names_in_ is used as feature names in.

  • If an array or list, then input_features must match feature_names_in_.

feature_names_out: list

Transformed feature names.


List[Union[str, int]] ..


Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.


A MetadataRequest encapsulating routing information.


Get parameters for this estimator.

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.


Parameter names mapped to their values.


Get a mask, or integer index, of the features selected.

indicesbool, default=False

If True, the return value will be an array of integers, rather than a boolean mask.


An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True if its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.


Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.


Estimator parameters.

selfestimator instance

Estimator instance.


Return dataframe with selected features.

X: pandas dataframe of shape = [n_samples, n_features].

The input dataframe.

X_new: pandas dataframe of shape = [n_samples, n_selected_features]

Pandas dataframe with the selected features.


DataFrame ..