TargetEncoder#

class sklearn.preprocessing.TargetEncoder(categories='auto', target_type='auto', smooth='auto', cv=5, shuffle=True, random_state=None)[source]#

用于回归和分类目标的 Target Encoder。

每个类别都根据属于该类别的观测值的平均目标值的收缩估计进行编码。编码方案将全局目标均值与以类别值为条件的条件目标均值混合(参见 [MIC])。

当目标类型为“multiclass”时,编码基于每个类别的条件概率估计。目标首先通过 LabelBinarizer 使用“一对多”方案进行二值化,然后使用每个类别和每个类别的平均目标值进行编码,生成 n_features * n_classes 个编码后的输出特征。

TargetEncoder 将缺失值(例如 np.nanNone)视为另一个类别,并像对待其他类别一样对其进行编码。在 fit 期间未见过的类别使用目标均值(即 target_mean_)进行编码。

有关 TargetEncoder 内部交叉拟合重要性的演示,请参阅 目标编码器的内部交叉拟合。有关不同编码器的比较,请参阅 目标编码器与其他编码器的比较。在 用户指南 中阅读更多内容。

注意

fit(X, y).transform(X) 不等于 fit_transform(X, y),因为 fit_transform 中使用了交叉拟合方案进行编码。有关详细信息,请参阅用户指南

在版本 1.3 中新增。

参数:
categories“auto” or list of shape (n_features,) of array-like, default=”auto”

每个特征的类别(唯一值)。

  • "auto" : 自动从训练数据中确定类别。

  • list : categories[i] 包含第 i 列中预期的类别。传递的类别不应在单个特征中混合字符串和数值,并且在数值的情况下应进行排序。

使用的类别存储在 categories_ 拟合属性中。

target_type{“auto”, “continuous”, “binary”, “multiclass”}, default=”auto”

目标类型。

  • "auto" : 使用 type_of_target 推断目标类型。

  • "continuous" : 连续目标

  • "binary" : 二进制目标

  • "multiclass" : 多类别目标

注意

使用 "auto" 推断的目标类型可能不是建模所需的理想目标类型。例如,如果目标包含 0 到 100 之间的整数,则 type_of_target 将推断目标为 "multiclass"。在这种情况下,设置 target_type="continuous" 将把目标指定为回归问题。 target_type_ 属性给出编码器使用的目标类型。

版本 1.4 中更改: 添加了“multiclass”选项。

smooth“auto” or float, default=”auto”

以类别值为条件的条件目标均值与全局目标均值的混合量。较大的 smooth 值将赋予全局目标均值更大的权重。如果为 "auto",则 smooth 设置为经验贝叶斯估计。

cvint, default=5

确定 fit_transform 中使用的 交叉拟合 策略中的折叠数。对于分类目标,使用 StratifiedKFold;对于连续目标,使用 KFold

shufflebool, default=True

在将数据分成折叠之前,是否在 fit_transform 中打乱数据。请注意,每个拆分中的样本不会被打乱。

random_stateint, RandomState instance or None, default=None

shuffle 为 True 时,random_state 会影响索引的顺序,从而控制每个折叠的随机性。否则,此参数无效。传递一个整数可在多次函数调用中实现可复现的输出。请参阅词汇表

属性:
encodings_list of shape (n_features,) or (n_features * n_classes) of ndarray

在所有 X 上学习到的编码。对于特征 iencodings_[i] 是与 categories_[i] 中列出的类别匹配的编码。当 target_type_ 为“multiclass”时,特征 i 和类别 j 的编码存储在 encodings_[j + (i * len(classes_))] 中。例如,对于 2 个特征 (f) 和 3 个类别 (c),编码按顺序排列:f0_c0, f0_c1, f0_c2, f1_c0, f1_c1, f1_c2,

categories_list of shape (n_features,) of ndarray

在拟合期间确定或在 categories 中指定的每个输入特征的类别(按 X 中特征的顺序,并与 transform 的输出相对应)。

target_type_str

目标类型。

target_mean_float

目标的总体均值。此值仅用于 transform 中对类别进行编码。

n_features_in_int

拟合 期间看到的特征数。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

fit 期间看到的特征名称。仅当 X 具有全部为字符串的特征名称时才定义。

classes_ndarray or None

如果 target_type_ 是 'binary' 或 'multiclass',则包含每个类别的标签,否则为 None

另请参阅

OrdinalEncoder

对分类特征执行序数(整数)编码。与 TargetEncoder 相反,此编码是无监督的。因此,将生成的编码视为数值特征会导致任意排序的值,通常在用作分类器或回归器的预处理时导致较低的预测性能。

OneHotEncoder

对分类特征执行独热编码。这种无监督编码更适合低基数分类变量,因为它为每个唯一类别生成一个新特征。

References

示例

smooth="auto" 时,平滑参数设置为经验贝叶斯估计。

>>> import numpy as np
>>> from sklearn.preprocessing import TargetEncoder
>>> X = np.array([["dog"] * 20 + ["cat"] * 30 + ["snake"] * 38], dtype=object).T
>>> y = [90.3] * 5 + [80.1] * 15 + [20.4] * 5 + [20.1] * 25 + [21.2] * 8 + [49] * 30
>>> enc_auto = TargetEncoder(smooth="auto")
>>> X_trans = enc_auto.fit_transform(X, y)
>>> # 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(X, y)[source]#

TargetEncoder 拟合到 X 和 y。

不建议使用此方法,因为它可能引入数据泄漏。请改用训练数据上的 fit_transform

注意

fit(X, y).transform(X) 不等于 fit_transform(X, y),因为 fit_transform 中使用了交叉拟合方案进行编码。有关详细信息,请参阅用户指南

参数:
Xshape 为 (n_samples, n_features) 的 array-like

用于确定每个特征类别的​​数据。

yarray-like of shape (n_samples,)

用于编码类别的目标数据。

返回:
selfobject

已拟合的编码器。

fit_transform(X, y)[source]#

拟合 TargetEncoder 并使用目标编码转换 X

此方法使用 交叉拟合 方案来防止下游预测器中的目标泄漏和过拟合。这是编码训练数据的推荐方法。

注意

fit(X, y).transform(X) 不等于 fit_transform(X, y),因为 fit_transform 中使用了交叉拟合方案进行编码。有关详细信息,请参阅用户指南

参数:
Xshape 为 (n_samples, n_features) 的 array-like

用于确定每个特征类别的​​数据。

yarray-like of shape (n_samples,)

用于编码类别的目标数据。

返回:
X_transndarray of shape (n_samples, n_features) or (n_samples, (n_features * n_classes))

转换后的输入。

get_feature_names_out(input_features=None)[source]#

获取转换的输出特征名称。

参数:
input_featuresarray-like of str or None, default=None

Not used, present here for API consistency by convention.

返回:
feature_names_outstr 对象的 ndarray

转换后的特征名称。除非未定义 feature_names_in_,否则使用它,在这种情况下生成以下输入特征名称:["x0", "x1", ..., "x(n_features_in_ - 1)"]。当 type_of_target_ 为“multiclass”时,名称格式为“<feature_name>_<class_name>”。

get_metadata_routing()[source]#

获取此对象的元数据路由。

请查阅 用户指南,了解路由机制如何工作。

返回:
routingMetadataRequest

封装路由信息的 MetadataRequest

get_params(deep=True)[source]#

获取此估计器的参数。

参数:
deepbool, default=True

如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。

返回:
paramsdict

参数名称映射到其值。

set_output(*, transform=None)[source]#

设置输出容器。

有关如何使用 API 的示例,请参阅引入 set_output API

参数:
transform{“default”, “pandas”, “polars”}, default=None

配置 transformfit_transform 的输出。

  • "default": 转换器的默认输出格式

  • "pandas": DataFrame 输出

  • "polars": Polars 输出

  • None: 转换配置保持不变

1.4 版本新增: 添加了 "polars" 选项。

返回:
selfestimator instance

估计器实例。

set_params(**params)[source]#

设置此估计器的参数。

此方法适用于简单的估计器以及嵌套对象(如 Pipeline)。后者具有 <component>__<parameter> 形式的参数,以便可以更新嵌套对象的每个组件。

参数:
**paramsdict

估计器参数。

返回:
selfestimator instance

估计器实例。

transform(X)[source]#

使用目标编码转换 X。

此方法在内部使用在 TargetEncoder.fit_transform 期间学习到的 encodings_ 属性来转换测试数据。

注意

fit(X, y).transform(X) 不等于 fit_transform(X, y),因为 fit_transform 中使用了交叉拟合方案进行编码。有关详细信息,请参阅用户指南

参数:
Xshape 为 (n_samples, n_features) 的 array-like

用于确定每个特征类别的​​数据。

返回:
X_transndarray of shape (n_samples, n_features) or (n_samples, (n_features * n_classes))

转换后的输入。