DecisionTreeEncoder#
- class feature_engine.encoding.DecisionTreeEncoder(encoding_method='arbitrary', cv=3, scoring='neg_mean_squared_error', param_grid=None, regression=True, random_state=None, variables=None, ignore_format=False, precision=None, unseen='ignore', fill_value=None)[source]#
The DecisionTreeEncoder() encodes categorical variables with the predictions of a decision tree.
The encoder fits a single feature decision tree to predict the target, and with that, it creates mappings from category to prediction value. Then, it uses these mappings to replace the categories of the feature. The encoder trains a decision tree per feature to encode.
The DecisionTreeEncoder() will encode only categorical variables by default (type ‘object’ or ‘categorical’). You can pass a list of variables to encode or the encoder will find and encode all categorical variables.
With
ignore_format=Trueyou have the option to encode numerical variables as well. In this case, you can either enter the list of variables to encode, or the transformer will automatically select all variables.More details in the User Guide.
- Parameters
- encoding_method: str, default=’arbitrary’
The method used to encode the categories to numerical values before fitting the decision tree.
‘ordered’: the categories are numbered in ascending order according to the target mean value per category.
‘arbitrary’ : categories are numbered arbitrarily.
- cv: int, cross-validation generator or an iterable, default=3
Determines the cross-validation splitting strategy. Possible inputs for cv are:
None, to use cross_validate’s default 5-fold cross validation
int, to specify the number of folds in a (Stratified)KFold,
An iterable yielding (train, test) splits as arrays of indices.
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=Falseso the splits will be the same across calls. For more details check Scikit-learn’scross_validate’s documentation.- scoring: str, default=’neg_mean_squared_error’
Desired metric to optimise the performance for the decision tree. Comes from sklearn.metrics. See the DecisionTreeRegressor or DecisionTreeClassifier model evaluation documentation for more options: https://scikit-learn.org/stable/modules/model_evaluation.html
- param_grid: dictionary, default=None
The hyperparameters for the decision tree to test with a grid search. The
param_gridcan contain any of the permitted hyperparameters for Scikit-learn’s DecisionTreeRegressor() or DecisionTreeClassifier(). If None, then param_grid will optimise the ‘max_depth’ over[1, 2, 3, 4].- regression: boolean, default=True
Indicates whether the encoder should train a regression or a classification decision tree.
- random_state: int, default=None
The random_state to initialise the training of the decision tree. It is one of the parameters of the Scikit-learn’s DecisionTreeRegressor() or DecisionTreeClassifier(). For reproducibility it is recommended to set the random_state to an integer.
- variables: list, default=None
The list of categorical variables that will be encoded. If None, the encoder will find and transform all variables of type object or categorical by default. You can also make the transformer accept numerical variables, see the parameter
ignore_format.- ignore_format: bool, default=False
This transformer operates only on variables of type object or categorical. To override this behaviour and allow the transformer to transform numerical variables as well, set to
True.If
ignore_formatisFalse, the encoder will automatically select variables of type object or categorical, or check that the variables entered by the user are of type object or categorical. IfTrue, the encoder will select all variables or accept all variables entered by the user, including those cast as numeric.In short, set to
Truewhen you want to encode numerical variables.- precision: int, default=None
The precision at which to store and display the category mappings. In other words, the number of decimals after the comma for the tree predictions.
- unseen: string, default=’ignore’
Indicates what to do when categories not present in the train set are encountered during transform. If
'raise', then unseen categories will raise an error. If'ignore', then unseen categories will be encoded as NaN and a warning will be raised instead. If'encode'unseen categories will be encoded asfill_value.- fill_value: float, default=None
The value used to encode unseen categories. Only used when
unseen='encode'.
- Attributes
- encoder_dict_:
Dictionary with the prediction per category, per variable.
- variables_:
The group of variables that will be transformed.
- feature_names_in_:
List with the names of features seen during
fit.- n_features_in_:
The number of features in the train set used in fit.
See also
sklearn.ensemble.DecisionTreeRegressorsklearn.ensemble.DecisionTreeClassifierfeature_engine.discretisation.DecisionTreeDiscretiserfeature_engine.encoding.RareLabelEncoderfeature_engine.encoding.OrdinalEncoder
Notes
The authors designed this method originally to work with numerical variables. We can replace numerical variables by the predictions of a decision tree utilising the DecisionTreeDiscretiser(). Here, we extend this functionality to work also with categorical variables.
References
- 1
Niculescu-Mizil, et al. “Winning the KDD Cup Orange Challenge with Ensemble Selection”. JMLR: Workshop and Conference Proceedings 7: 23-34. KDD 2009 http://proceedings.mlr.press/v7/niculescu09/niculescu09.pdf
Examples
>>> import pandas as pd >>> from feature_engine.encoding import DecisionTreeEncoder >>> X = pd.DataFrame(dict(x1 = [1,2,3,4,5], x2 = ["b", "b", "b", "a", "a"])) >>> y = pd.Series([2.2,4, 1.5, 3.2, 1.1]) >>> dte = DecisionTreeEncoder(cv=2) >>> dte.fit(X, y) >>> dte.transform(X) x1 x2 0 1 2.566667 1 2 2.566667 2 3 2.566667 3 4 2.150000 4 5 2.150000
You can also use it for classification by using
regression=False.>>> y = pd.Series([0,1,1,1,0]) >>> dte = DecisionTreeEncoder(regression=False, cv=2) >>> dte.fit(X, y) >>> dte.transform(X) x1 x2 0 1 0.666667 1 2 0.666667 2 3 0.666667 3 4 0.500000 4 5 0.500000
Methods
fit:
Fit a decision tree per variable.
fit_transform:
Fit to data, then transform it.
get_feature_names_out:
Get output feature names for transformation.
get_params:
Get parameters for this estimator.
set_params:
Set the parameters of this estimator.
inverse_transform:
Convert the data back to the original representation.
transform:
Replace categorical variable by the predictions of the decision tree.
- fit(X, y)[source]#
Fit a decision tree per variable.
- Parameters
- Xpandas dataframe of shape = [n_samples, n_features]
The training input samples. Can be the entire dataframe, not just the categorical variables.
- ypandas series.
The target variable. Required to train the decision tree and for ordered ordinal encoding.
- fit_transform(X, y=None, **fit_params)[source]#
Fit to data, then transform it.
Fits transformer to
Xandywith optional parametersfit_paramsand returns a transformed version ofX.- Parameters
- 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).
- **fit_paramsdict
Additional fit parameters. Pass only if the estimator accepts additional params in its
fitmethod.
- Returns
- X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
- get_feature_names_out(input_features=None)[source]#
Get output feature names for transformation. In other words, returns the variable names of transformed dataframe.
- Parameters
- input_featuresarray or list, default=None
This parameter exits only for compatibility with the Scikit-learn pipeline.
If
None, thenfeature_names_in_is used as feature names in.If an array or list, then
input_featuresmust matchfeature_names_in_.
- Returns
- feature_names_out: list
Transformed feature names.
- get_metadata_routing()[source]#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns
- routingMetadataRequest
A
MetadataRequestencapsulating routing information.
- get_params(deep=True)[source]#
Get parameters for this estimator.
- Parameters
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns
- paramsdict
Parameter names mapped to their values.
- inverse_transform(X)[source]#
Convert the encoded variable back to the original values.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features].
The transformed dataframe.
- Returns
- X_tr: pandas dataframe of shape = [n_samples, n_features].
The un-transformed dataframe, with the categorical variables containing the original values.
- rtype
DataFrame..
- set_params(**params)[source]#
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.- Parameters
- **paramsdict
Estimator parameters.
- Returns
- selfestimator instance
Estimator instance.
- transform(X)[source]#
Replace categorical variables by the predictions of the decision tree.
- Parameters
- Xpandas dataframe of shape = [n_samples, n_features]
The input samples.
- Returns
- X_newpandas dataframe of shape = [n_samples, n_features].
Dataframe with variables encoded with decision tree predictions.
- rtype
DataFrame..