TargetEncoder
- class sklearn.preprocessing.TargetEncoder(categories='auto', target_type='auto', smooth='auto', cv=5, shuffle='deprecated', random_state='deprecated'
Target Encoder for regression and classification targets.
Each category is encoded based on a shrunk estimate of the average target values for observations belonging to the category. The encoding scheme mixes the global target mean with the target mean conditioned on the value of the category (see [MIC]).
When the target type is “multiclass”, encodings are based
on the conditional probability estimate for each class. The target is first
binarized using the “one-vs-all” scheme via
LabelBinarizer, then the average target
value for each class and each category is used for encoding, resulting in
n_features * n_classes encoded output features.
TargetEncoder considers missing values, such as np.nan or None,
as another category and encodes them like any other category. Categories
that are not seen during fit are encoded with the target mean, i.e.
target_mean_.
For a demo on the importance of the TargetEncoder internal cross fitting,
see
Target Encoder’s Internal Cross fitting.
For a comparison of different encoders, refer to
Comparing Target Encoder with Other Encoders. Read
more in the User Guide.
Categories (unique values) per feature:
"auto" : Determine categories automatically from the training data.
list : categories[i] holds the categories expected in the i-th column. The
passed categories should not mix strings and numeric values within a single
feature, and should be sorted in case of numeric values.
The used categories are stored in the categories_ fitted attribute.
Type of target.
: Type of target is inferred with
.
With smooth="auto", the smoothing parameter is set to an empirical Bayes estimate:
>>> import numpy as np
>>> from sklearn.preprocessing import TargetEncoder
>>> X = np.array([["dog"] * 20 + ["cat"] * 30 + ["snake"] * 38
>>> # A high `smooth` parameter puts more weight on global mean on the categorical
>>> # encodings:
>>> enc_high_smooth = TargetEncoder(smooth=5000.0).fit(X, y)
>>> enc_high_smooth.target_mean_
np.float64(44.3)
>>> enc_high_smooth.encodings_
[array([44.1, 44.4, 44.3])]
>>> # On the other hand, a low `smooth` parameter puts more weight on target
>>> # conditioned on the value of the categorical:
>>> enc_low_smooth = TargetEncoder(smooth=1.0).fit(X, y)
>>> enc_low_smooth.encodings_
[array([21, 80.8, 43.2])]
Fit the TargetEncoder to X and y.
It is discouraged to use this method because it can introduce data leakage.
Use fit_transform on training data instead.
Fit TargetEncoder and transform X with the target encoding.
This method uses a cross fitting scheme to prevent target leakage and overfitting in downstream predictors. It is the recommended method for encoding training data.
Get output feature names for transformation.
Not used, present here for API consistency by convention.
Transformed feature names. feature_names_in_ is used unless it is
not defined, in which case the following input feature names are
generated: .
When is “multiclass” the names are of the format
‘<feature_name>_<class_name>’.
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set output container.
Refer to the user guide for more details and Introducing the set_output API for an example on how to use the API.
Configure output of transform and .
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.
Transform X with the target encoding.
This method internally uses the encodings_ attribute learnt during
TargetEncoder.fit_transform to transform test data.
"continuous" : Continuous target
"binary" : Binary target
"multiclass" : Multiclass target
The amount of mixing of the target mean conditioned on the value of the
category with the global target mean. A larger smooth value will put
more weight on the global target mean.
If "auto", then smooth is set to an empirical Bayes estimate.
Determines the splitting strategy used in the internal cross fitting
during fit_transform. Splitters where each sample index doesn’t appear
in the validation fold exactly once, raise a ValueError.
Possible inputs for cv are:
None, to use a 5-fold cross-validation chosen internally based ontarget_type,
internally based on target_type,
CV splitter that does not repeat samples across validation folds,
an iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if target_type is "continuous", KFold is
used, otherwise StratifiedKFold is used.
Refer User Guide for more information on cross-validation strategies.
Whether to shuffle the data in fit_transform before splitting into
folds. Note that the samples within each split will not be shuffled. Only
applies if cv is an int or None. If cv is a cross-validation generator or
an iterable, shuffle is ignored.
When shuffle is True, random_state affects the ordering of the
indices, which controls the randomness of each fold. Otherwise, this
parameter has no effect.
Pass an int for reproducible output across multiple function calls.
See Glossary.
Encodings learnt on all of X.
For feature i, encodings_[i] are the encodings matching the
categories listed in categories_[i]. When target_type_ is
“multiclass”, the encoding for feature i and class j is stored in
encodings_[j + (i * len(classes_))]. E.g., for 2 features (f) and
3 classes (c), encodings are ordered:
f0_c0, f0_c1, f0_c2, f1_c0, f1_c1, f1_c2,
The categories of each input feature determined during fitting or
specified in categories
(in order of the features in X and corresponding with the output
of transform).
Type of target.
The overall mean of the target. This value is only used in transform
to encode categories.
Number of features seen during fit.
n_features_in_,)Names of features seen during fit. Defined only when X
has feature names that are all strings.
If target_type_ is ‘binary’ or ‘multiclass’, holds the label for each class,
otherwise None.
fit_transformThe data to determine the categories of each feature.
The target data used to encode the categories.
Fitted encoder.
fit_transform(X, y)fit_transformThe data to determine the categories of each feature.
The target data used to encode the categories.
Parameters to route to the internal CV object.
Can only be used in conjunction with a cross-validation generator as CV object.
For instance, groups (array-like of shape (n_samples,)) can be routed to
a CV splitter that accepts groups, such as GroupKFold or
StratifiedGroupKFold.
Transformed input.
["x0", "x1", ..., "x(n_features_in_ - 1)"]type_of_target_"default": Default output format of a transformer
"pandas": DataFrame output
"polars": Polars output
None: Transform configuration is unchanged
Estimator instance.
Estimator instance.
fit_transformThe data to determine the categories of each feature.
Transformed input.