6.3. Preprocessing data#
6.3. 预处理数据#
The sklearn.preprocessing
package provides several common
utility functions and transformer classes to change raw feature vectors
into a representation that is more suitable for the downstream estimators.
该软件包提供了几个常见的 Utility 函数和 transformer 类,用于将原始特征向量转换为更适合下游估计器的表示形式。
In general, many learning algorithms such as linear models benefit from standardization of the data set
(see Importance of Feature Scaling).
If some outliers are present in the set, robust scalers or other transformers can
be more appropriate. The behaviors of the different scalers, transformers, and
normalizers on a dataset containing marginal outliers is highlighted in
Compare the effect of different scalers on data with outliers.
一般来说,许多学习算法(如线性模型)都受益于数据集的标准化(请参阅特征缩放的重要性)。如果集合中存在一些异常值,则健壮的缩放器或其他转换器可能更合适。比较不同缩放器对具有异常值的数据的影响中突出显示了不同缩放器、转换器和归一化器在包含边缘异常值的数据集上的行为。
6.3.1. Standardization, or mean removal and variance scaling#
6.3.1. 标准化,或均值去除和方差缩放#
Standardization of datasets is a common requirement for many
machine learning estimators implemented in scikit-learn; they might behave
badly if the individual features do not more or less look like standard
normally distributed data: Gaussian with zero mean and unit variance.
数据集的标准化是在 scikit-learn 中实现的许多机器学习估计器的常见要求;如果单个特征或多或少看起来不像标准正态分布数据:均值和单位方差为零的高斯数据,则它们可能会表现不佳。
In practice we often ignore the shape of the distribution and just
transform the data to center it by removing the mean value of each
feature, then scale it by dividing non-constant features by their
standard deviation.
在实践中,我们经常忽略分布的形状,只是通过删除每个特征的平均值来转换数据以使其居中,然后通过将非常量特征除以标准差来缩放它。
For instance, many elements used in the objective function of
a learning algorithm (such as the RBF kernel of Support Vector
Machines or the l1 and l2 regularizers of linear models) may assume that
all features are centered around zero or have variance in the same
order. If a feature has a variance that is orders of magnitude larger
than others, it might dominate the objective function and make the
estimator unable to learn from other features correctly as expected.
例如,学习算法的目标函数中使用的许多元素(例如支持向量机的 RBF 内核或线性模型的 l1 和 l2 正则化器)可能假设所有特征都以零为中心或具有相同顺序的方差。如果某个特征的方差比其他特征大几个数量级,则它可能会主导目标函数,并使估计器无法按预期正确地从其他特征中学习。
The preprocessing
module provides the
StandardScaler
utility class, which is a quick and
easy way to perform the following operation on an array-like
dataset:
该模块提供了 utility 类,这是一种对类似数组的数据集执行以下操作的快速简便的方法:
>>> from sklearn import preprocessing
>>> import numpy as np
>>> X_train = np.array([[ 1., -1., 2.],
... [ 2., 0., 0.],
... [ 0., 1., -1.]])
>>> scaler = preprocessing.StandardScaler().fit(X_train)
>>> scaler
StandardScaler()
>>> scaler.mean_
array([1. ..., 0. ..., 0.33...])
>>> scaler.scale_
array([0.81..., 0.81..., 1.24...])
>>> X_scaled = scaler.transform(X_train)
>>> X_scaled
array([[ 0. ..., -1.22..., 1.33...],
[ 1.22..., 0. ..., -0.26...],
[-1.22..., 1.22..., -1.06...]])
Scaled data has zero mean and unit variance:
缩放数据的平均值和单位方差为零:
>>> X_scaled.mean(axis=0)
array([0., 0., 0.])
>>> X_scaled.std(axis=0)
array([1., 1., 1.])
This class implements the Transformer
API to compute the mean and
standard deviation on a training set so as to be able to later re-apply the
same transformation on the testing set. This class is hence suitable for
use in the early steps of a Pipeline
:
此类实现 API 来计算训练集上的平均值和标准差,以便以后能够在测试集上重新应用相同的转换。因此,此类适合在 :
>>> from sklearn.datasets import make_classification
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> X, y = make_classification(random_state=42)
>>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
>>> pipe = make_pipeline(StandardScaler(), LogisticRegression())
>>> pipe.fit(X_train, y_train) # apply scaling on training data
Pipeline(steps=[('standardscaler', StandardScaler()),
('logisticregression', LogisticRegression())])
>>> pipe.score(X_test, y_test) # apply scaling on testing data, without leaking training data.
0.96
It is possible to disable either centering or scaling by either
passing with_mean=False
or with_std=False
to the constructor
of StandardScaler
.
可以通过将 或 传递给 的构造函数来禁用居中或缩放。
6.3.1.1. Scaling features to a range#
6.3.1.1. 将 Feature 缩放到某个范围#
An alternative standardization is scaling features to
lie between a given minimum and maximum value, often between zero and one,
or so that the maximum absolute value of each feature is scaled to unit size.
This can be achieved using MinMaxScaler
or MaxAbsScaler
,
respectively.
另一种标准化方法是将特征缩放到给定的最小值和最大值之间,通常介于 0 和 1 之间,或者将每个特征的最大绝对值缩放为单位大小。这可以分别使用 或 来实现。
The motivation to use this scaling include robustness to very small
standard deviations of features and preserving zero entries in sparse data.
使用这种缩放的动机包括对非常小的特征标准差的鲁棒性,以及在稀疏数据中保留零条目。
Here is an example to scale a toy data matrix to the [0, 1]
range:
下面是将玩具数据矩阵缩放到范围的示例:
>>> X_train = np.array([[ 1., -1., 2.],
... [ 2., 0., 0.],
... [ 0., 1., -1.]])
...
>>> min_max_scaler = preprocessing.MinMaxScaler()
>>> X_train_minmax = min_max_scaler.fit_transform(X_train)
>>> X_train_minmax
array([[0.5 , 0. , 1. ],
[1. , 0.5 , 0.33333333],
[0. , 1. , 0. ]])
The same instance of the transformer can then be applied to some new test data
unseen during the fit call: the same scaling and shifting operations will be
applied to be consistent with the transformation performed on the train data:
然后,可以将 transformer 的相同实例应用于 fit 调用期间看不到的一些新测试数据:将应用相同的缩放和移位操作,以与对 train 数据执行的转换保持一致:
>>> X_test = np.array([[-3., -1., 4.]])
>>> X_test_minmax = min_max_scaler.transform(X_test)
>>> X_test_minmax
array([[-1.5 , 0. , 1.66666667]])
It is possible to introspect the scaler attributes to find about the exact
nature of the transformation learned on the training data:
可以内省 scaler 属性,以找出在训练数据上学习的转换的确切性质:
>>> min_max_scaler.scale_
array([0.5 , 0.5 , 0.33...])
>>> min_max_scaler.min_
array([0. , 0.5 , 0.33...])
If MinMaxScaler
is given an explicit feature_range=(min, max)
the
full formula is:
如果给定一个显式,则完整公式为:
X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
MaxAbsScaler
works in a very similar fashion, but scales in a way
that the training data lies within the range [-1, 1]
by dividing through
the largest maximum value in each feature. It is meant for data
that is already centered at zero or sparse data.
其工作方式非常相似,但通过除以每个特征中的最大最大值,以训练数据位于该范围内的方式进行扩展。它适用于已经以零数据或稀疏数据为中心的数据。
Here is how to use the toy data from the previous example with this scaler:
以下是如何将上一个示例中的玩具数据与此缩放器一起使用:
>>> X_train = np.array([[ 1., -1., 2.],
... [ 2., 0., 0.],
... [ 0., 1., -1.]])
...
>>> max_abs_scaler = preprocessing.MaxAbsScaler()
>>> X_train_maxabs = max_abs_scaler.fit_transform(X_train)
>>> X_train_maxabs
array([[ 0.5, -1. , 1. ],
[ 1. , 0. , 0. ],
[ 0. , 1. , -0.5]])
>>> X_test = np.array([[ -3., -1., 4.]])
>>> X_test_maxabs = max_abs_scaler.transform(X_test)
>>> X_test_maxabs
array([[-1.5, -1. , 2. ]])
>>> max_abs_scaler.scale_
array([2., 1., 2.])
6.3.1.2. Scaling sparse data#
6.3.1.2. 缩放稀疏数据#
Centering sparse data would destroy the sparseness structure in the data, and
thus rarely is a sensible thing to do. However, it can make sense to scale
sparse inputs, especially if features are on different scales.
将稀疏数据居中会破坏数据中的稀疏结构,因此很少是明智的做法。但是,缩放稀疏输入是有意义的,尤其是在要素处于不同比例时。
MaxAbsScaler
was specifically designed for scaling
sparse data, and is the recommended way to go about this.
However, StandardScaler
can accept scipy.sparse
matrices as input, as long as with_mean=False
is explicitly passed
to the constructor. Otherwise a ValueError
will be raised as
silently centering would break the sparsity and would often crash the
execution by allocating excessive amounts of memory unintentionally.
RobustScaler
cannot be fitted to sparse inputs, but you can use
the transform
method on sparse inputs.
专为扩展稀疏数据而设计,是实现此目的的推荐方法。但是,可以接受矩阵作为输入,只要显式传递给构造函数即可。否则将引发 a,因为静默居中会破坏稀疏性,并且经常会因无意中分配过多的内存而使执行崩溃。 不能拟合到稀疏 inputs,但你可以在稀疏 inputs上使用该方法。
Note that the scalers accept both Compressed Sparse Rows and Compressed
Sparse Columns format (see scipy.sparse.csr_matrix
and
scipy.sparse.csc_matrix
). Any other sparse input will be converted to
the Compressed Sparse Rows representation. To avoid unnecessary memory
copies, it is recommended to choose the CSR or CSC representation upstream.
请注意,缩放器接受 Compressed Sparse Rows 和 Compressed Sparse Columns 格式(请参阅 和 )。任何其他稀疏输入都将转换为 Compressed Sparse Rows 表示。为避免不必要的内存副本,建议选择上游的 CSR 或 CSC 表示形式。
Finally, if the centered data is expected to be small enough, explicitly
converting the input to an array using the toarray
method of sparse matrices
is another option.
最后,如果预期居中数据足够小,则使用稀疏矩阵方法将输入显式转换为数组是另一种选择。
6.3.1.3. Scaling data with outliers#
6.3.1.3. 使用异常值缩放数据#
If your data contains many outliers, scaling using the mean and variance
of the data is likely to not work very well. In these cases, you can use
RobustScaler
as a drop-in replacement instead. It uses
more robust estimates for the center and range of your data.
如果您的数据包含许多异常值,则使用数据的均值和方差进行缩放可能效果不佳。在这些情况下,您可以改用 drop-in replacement 代替。它对数据的中心和范围使用更可靠的估计值。
References# 参考资料#
Further discussion on the importance of centering and scaling data is available on this FAQ: Should I normalize/standardize/rescale the data?
Scaling vs Whitening#
洗牙与美白#
It is sometimes not enough to center and scale the features independently, since a downstream model can further make some assumption on the linear independence of the features.
To address this issue you can use PCA
with
whiten=True
to further remove the linear correlation across features.
6.3.1.4. Centering kernel matrices#
6.3.1.4. 将核矩阵居中#
If you have a kernel matrix of a kernel KernelCenterer
can transform the kernel matrix
so that it contains inner products in the feature space defined by KernelCenterer
computes the centered Gram matrix associated to a
positive semidefinite kernel
如果您有一个内核的内核矩阵,该内核
Mathematical formulation#
数学公式#
We can have a look at the mathematical formulation now that we have the
intuition. Let (n_samples, n_samples)
computed from (n_samples, n_features)
,
during the fit
step.
where
Thus, one could compute
(n_samples, n_samples)
where
all entries are equal to transform
step, the kernel becomes
(n_samples_test, n_features)
and thus
(n_samples_test, n_samples)
. In this case,
centering
(n_samples_test, n_samples)
where all entries are equal to
References
B. Schölkopf, A. Smola, and K.R. Müller, “Nonlinear component analysis as a kernel eigenvalue problem.” Neural computation 10.5 (1998): 1299-1319.
6.3.2. Non-linear transformation#
6.3.2. 非线性变换#
Two types of transformations are available: quantile transforms and power
transforms. Both quantile and power transforms are based on monotonic
transformations of the features and thus preserve the rank of the values
along each feature.
有两种类型的转换可用:分位数转换和幂转换。分位数转换和幂转换都基于特征的单调转换,因此保留了每个特征上的值的排名。
Quantile transforms put all features into the same desired distribution based
on the formula
分位数转换将所有特征放入基于相同所需分布的
在公式
Power transforms are a family of parametric transformations that aim to map
data from any distribution to as close to a Gaussian distribution.
幂变换是一系列参数变换,旨在将数据从任何分布映射到尽可能接近高斯分布。
6.3.2.1. Mapping to a Uniform distribution#
6.3.2.1. 映射到 Uniform 发行版#
QuantileTransformer
provides a non-parametric
transformation to map the data to a uniform distribution
with values between 0 and 1:
提供非参数变换,以将数据映射到值介于 0 和 1 之间的均匀分布:
>>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import train_test_split
>>> X, y = load_iris(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
>>> quantile_transformer = preprocessing.QuantileTransformer(random_state=0)
>>> X_train_trans = quantile_transformer.fit_transform(X_train)
>>> X_test_trans = quantile_transformer.transform(X_test)
>>> np.percentile(X_train[:, 0], [0, 25, 50, 75, 100])
array([ 4.3, 5.1, 5.8, 6.5, 7.9])
This feature corresponds to the sepal length in cm. Once the quantile
transformation applied, those landmarks approach closely the percentiles
previously defined:
这个特征对应于以 cm 为单位的萼片长度。应用分位数转换后,这些地标将接近之前定义的百分位数:
>>> np.percentile(X_train_trans[:, 0], [0, 25, 50, 75, 100])
...
array([ 0.00... , 0.24..., 0.49..., 0.73..., 0.99... ])
This can be confirmed on a independent testing set with similar remarks:
这可以通过类似的评论在独立的测试集中得到确认:
>>> np.percentile(X_test[:, 0], [0, 25, 50, 75, 100])
...
array([ 4.4 , 5.125, 5.75 , 6.175, 7.3 ])
>>> np.percentile(X_test_trans[:, 0], [0, 25, 50, 75, 100])
...
array([ 0.01..., 0.25..., 0.46..., 0.60... , 0.94...])
6.3.2.2. Mapping to a Gaussian distribution#
6.3.2.2. 映射到高斯分布#
In many modeling scenarios, normality of the features in a dataset is desirable.
Power transforms are a family of parametric, monotonic transformations that aim
to map data from any distribution to as close to a Gaussian distribution as
possible in order to stabilize variance and minimize skewness.
在许多建模场景中,数据集中特征的正态性是可取的。幂变换是一系列参数化的单调变换,旨在将数据从任何分布映射到尽可能接近高斯分布,以稳定方差并最小化偏度。
PowerTransformer
currently provides two such power transformations,
the Yeo-Johnson transform and the Box-Cox transform.
目前提供两种这样的幂变换,即 Yeo-Johnson 变换和 Box-Cox 变换。
Box-Cox transform#
Box-Cox 变换#
Box-Cox can only be applied to strictly positive data. In both methods, the
transformation is parameterized by
>>> pt = preprocessing.PowerTransformer(method='box-cox', standardize=False)
>>> X_lognormal = np.random.RandomState(616).lognormal(size=(3, 3))
>>> X_lognormal
array([[1.28..., 1.18..., 0.84...],
[0.94..., 1.60..., 0.38...],
[1.35..., 0.21..., 1.09...]])
>>> pt.fit_transform(X_lognormal)
array([[ 0.49..., 0.17..., -0.15...],
[-0.05..., 0.58..., -0.57...],
[ 0.69..., -0.84..., 0.10...]])
While the above example sets the standardize
option to False
,
PowerTransformer
will apply zero-mean, unit-variance normalization
to the transformed output by default.
Below are examples of Box-Cox and Yeo-Johnson applied to various probability
distributions. Note that when applied to certain distributions, the power
transforms achieve very Gaussian-like results, but with others, they are
ineffective. This highlights the importance of visualizing the data before and
after transformation.
以下是应用于各种概率分布的 Box-Cox 和 Yeo-Johnson 的示例。请注意,当应用于某些分布时,幂变换会获得非常类似于高斯的结果,但对于其他分布,它们无效。这凸显了在转换前后可视化数据的重要性。
It is also possible to map data to a normal distribution using
QuantileTransformer
by setting output_distribution='normal'
.
Using the earlier example with the iris dataset:
也可以通过设置 将数据映射到正态分布。将前面的示例与 iris 数据集一起使用:
>>> quantile_transformer = preprocessing.QuantileTransformer(
... output_distribution='normal', random_state=0)
>>> X_trans = quantile_transformer.fit_transform(X)
>>> quantile_transformer.quantiles_
array([[4.3, 2. , 1. , 0.1],
[4.4, 2.2, 1.1, 0.1],
[4.4, 2.2, 1.2, 0.1],
...,
[7.7, 4.1, 6.7, 2.5],
[7.7, 4.2, 6.7, 2.5],
[7.9, 4.4, 6.9, 2.5]])
Thus the median of the input becomes the mean of the output, centered at 0. The
normal output is clipped so that the input’s minimum and maximum —
corresponding to the 1e-7 and 1 - 1e-7 quantiles respectively — do not
become infinite under the transformation.
因此,输入的中位数成为输出的平均值,以 0 为中心。正常输出被裁剪,以便输入的最小值和最大值(分别对应于 1e-7 和 1 - 1e-7 分位数)在转换下不会变为无限。
6.3.3. Normalization#
6.3.3. 归一化#
Normalization is the process of scaling individual samples to have
unit norm. This process can be useful if you plan to use a quadratic form
such as the dot-product or any other kernel to quantify the similarity
of any pair of samples.
归一化是将单个样本缩放为具有单位范数的过程。如果您计划使用二次形式(如 dot-product 或任何其他内核)来量化任何一对样本的相似性,则此过程可能很有用。
This assumption is the base of the Vector Space Model often used in text
classification and clustering contexts.
此假设是文本分类和聚类上下文中经常使用的向量空间模型的基础。
The function normalize
provides a quick and easy way to perform this
operation on a single array-like dataset, either using the l1
, l2
, or
max
norms:
该函数提供了一种快速简便的方法,可以使用 、 或 norms 对单个类似数组的数据集执行此操作:
>>> X = [[ 1., -1., 2.],
... [ 2., 0., 0.],
... [ 0., 1., -1.]]
>>> X_normalized = preprocessing.normalize(X, norm='l2')
>>> X_normalized
array([[ 0.40..., -0.40..., 0.81...],
[ 1. ..., 0. ..., 0. ...],
[ 0. ..., 0.70..., -0.70...]])
The preprocessing
module further provides a utility class
Normalizer
that implements the same operation using the
Transformer
API (even though the fit
method is useless in this case:
the class is stateless as this operation treats samples independently).
该模块还提供了一个实用程序类,该类使用 API 实现相同的操作(即使该方法在这种情况下无用:该类是无状态的,因为此操作独立处理样本)。
This class is hence suitable for use in the early steps of a
Pipeline
:
因此,此类适合在 :
>>> normalizer = preprocessing.Normalizer().fit(X) # fit does nothing
>>> normalizer
Normalizer()
The normalizer instance can then be used on sample vectors as any transformer:
然后,标准化器实例可以像任何转换器一样在样本向量上使用:
>>> normalizer.transform(X)
array([[ 0.40..., -0.40..., 0.81...],
[ 1. ..., 0. ..., 0. ...],
[ 0. ..., 0.70..., -0.70...]])
>>> normalizer.transform([[-1., 1., 0.]])
array([[-0.70..., 0.70..., 0. ...]])
Note: L2 normalization is also known as spatial sign preprocessing.
注意:L2 归一化也称为空间符号预处理。
Sparse input# 稀疏输入#
normalize
and Normalizer
accept both dense array-like
and sparse matrices from scipy.sparse as input.
For sparse input the data is converted to the Compressed Sparse Rows
representation (see scipy.sparse.csr_matrix
) before being fed to
efficient Cython routines. To avoid unnecessary memory copies, it is
recommended to choose the CSR representation upstream.
6.3.4. Encoding categorical features#
6.3.4. 对分类特征进行编码#
Often features are not given as continuous values but categorical.
For example a person could have features ["male", "female"]
,
["from Europe", "from US", "from Asia"]
,
["uses Firefox", "uses Chrome", "uses Safari", "uses Internet Explorer"]
.
Such features can be efficiently coded as integers, for instance
["male", "from US", "uses Internet Explorer"]
could be expressed as
[0, 1, 3]
while ["female", "from Asia", "uses Chrome"]
would be
[1, 2, 1]
.
通常,特征不是以连续值的形式给出的,而是以分类值的形式给出的。例如,一个人可能具有特征 、 。此类特征可以有效地编码为整数,例如,可以表示为 while 将为 。
To convert categorical features to such integer codes, we can use the
OrdinalEncoder
. This estimator transforms each categorical feature to one
new feature of integers (0 to n_categories - 1):
要将分类特征转换为此类整数代码,我们可以使用 .此估计器将每个分类特征转换为一个新的整数特征(0 到 n_categories - 1):
>>> enc = preprocessing.OrdinalEncoder()
>>> X = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox']]
>>> enc.fit(X)
OrdinalEncoder()
>>> enc.transform([['female', 'from US', 'uses Safari']])
array([[0., 1., 1.]])
Such integer representation can, however, not be used directly with all
scikit-learn estimators, as these expect continuous input, and would interpret
the categories as being ordered, which is often not desired (i.e. the set of
browsers was ordered arbitrarily).
然而,这种整数表示不能直接与所有 scikit-learn 估计器一起使用,因为它们需要连续输入,并且会将类别解释为有序,这通常是不需要的(即浏览器集是任意排序的)。
By default, OrdinalEncoder
will also passthrough missing values that
are indicated by np.nan
.
默认情况下,还将传递由 .
>>> enc = preprocessing.OrdinalEncoder()
>>> X = [['male'], ['female'], [np.nan], ['female']]
>>> enc.fit_transform(X)
array([[ 1.],
[ 0.],
[nan],
[ 0.]])
OrdinalEncoder
provides a parameter encoded_missing_value
to encode
the missing values without the need to create a pipeline and using
SimpleImputer
.
提供了一个参数来对缺失值进行编码,而无需创建管道并使用 .
>>> enc = preprocessing.OrdinalEncoder(encoded_missing_value=-1)
>>> X = [['male'], ['female'], [np.nan], ['female']]
>>> enc.fit_transform(X)
array([[ 1.],
[ 0.],
[-1.],
[ 0.]])
The above processing is equivalent to the following pipeline:
上述处理相当于以下管道:
>>> from sklearn.pipeline import Pipeline
>>> from sklearn.impute import SimpleImputer
>>> enc = Pipeline(steps=[
... ("encoder", preprocessing.OrdinalEncoder()),
... ("imputer", SimpleImputer(strategy="constant", fill_value=-1)),
... ])
>>> enc.fit_transform(X)
array([[ 1.],
[ 0.],
[-1.],
[ 0.]])
Another possibility to convert categorical features to features that can be used
with scikit-learn estimators is to use a one-of-K, also known as one-hot or
dummy encoding.
This type of encoding can be obtained with the OneHotEncoder
,
which transforms each categorical feature with
n_categories
possible values into n_categories
binary features, with
one of them 1, and all others 0.
将分类特征转换为可与 scikit-learn 估计器一起使用的特征的另一种可能性是使用 one-of-K,也称为 one-hot 或虚拟编码。这种类型的编码可以通过 获得,它将每个具有可能值的分类特征转换为二进制特征,其中一个特征为 1,所有其他特征为 0。
Continuing the example above:
继续上面的示例:
>>> enc = preprocessing.OneHotEncoder()
>>> X = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox']]
>>> enc.fit(X)
OneHotEncoder()
>>> enc.transform([['female', 'from US', 'uses Safari'],
... ['male', 'from Europe', 'uses Safari']]).toarray()
array([[1., 0., 0., 1., 0., 1.],
[0., 1., 1., 0., 0., 1.]])
By default, the values each feature can take is inferred automatically
from the dataset and can be found in the categories_
attribute:
默认情况下,每个特征可以采用的值是从数据集中自动推断的,并且可以在以下属性中找到:
>>> enc.categories_
[array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object), array(['uses Firefox', 'uses Safari'], dtype=object)]
It is possible to specify this explicitly using the parameter categories
.
There are two genders, four possible continents and four web browsers in our
dataset:
可以使用参数 显式指定此项 。在我们的数据集中,有两种性别、四个可能的大洲和四种 Web 浏览器:
>>> genders = ['female', 'male']
>>> locations = ['from Africa', 'from Asia', 'from Europe', 'from US']
>>> browsers = ['uses Chrome', 'uses Firefox', 'uses IE', 'uses Safari']
>>> enc = preprocessing.OneHotEncoder(categories=[genders, locations, browsers])
>>> # Note that for there are missing categorical values for the 2nd and 3rd
>>> # feature
>>> X = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox']]
>>> enc.fit(X)
OneHotEncoder(categories=[['female', 'male'],
['from Africa', 'from Asia', 'from Europe',
'from US'],
['uses Chrome', 'uses Firefox', 'uses IE',
'uses Safari']])
>>> enc.transform([['female', 'from Asia', 'uses Chrome']]).toarray()
array([[1., 0., 0., 1., 0., 0., 1., 0., 0., 0.]])
If there is a possibility that the training data might have missing categorical
features, it can often be better to specify
handle_unknown='infrequent_if_exist'
instead of setting the categories
manually as above. When handle_unknown='infrequent_if_exist'
is specified
and unknown categories are encountered during transform, no error will be
raised but the resulting one-hot encoded columns for this feature will be all
zeros or considered as an infrequent category if enabled.
(handle_unknown='infrequent_if_exist'
is only supported for one-hot
encoding):
如果训练数据可能缺少分类特征,则通常最好指定而不是如上所述手动设置。如果指定了 API,并且在转换期间遇到未知类别,则不会引发错误,但为此功能生成的 one-hot 编码列将全部为零,或者如果启用,则被视为不频繁的类别。(仅支持 one-hot 编码):
>>> enc = preprocessing.OneHotEncoder(handle_unknown='infrequent_if_exist')
>>> X = [['male', 'from US', 'uses Safari'], ['female', 'from Europe', 'uses Firefox']]
>>> enc.fit(X)
OneHotEncoder(handle_unknown='infrequent_if_exist')
>>> enc.transform([['female', 'from Asia', 'uses Chrome']]).toarray()
array([[1., 0., 0., 0., 0., 0.]])
It is also possible to encode each column into n_categories - 1
columns
instead of n_categories
columns by using the drop
parameter. This
parameter allows the user to specify a category for each feature to be dropped.
This is useful to avoid co-linearity in the input matrix in some classifiers.
Such functionality is useful, for example, when using non-regularized
regression (LinearRegression
),
since co-linearity would cause the covariance matrix to be non-invertible:
还可以使用 parameter 将每列编码为列而不是列。此参数允许用户为要删除的每个功能指定类别。这对于避免某些分类器中 input matrix 中的共线性很有用。例如,在使用非正则化回归 () 时,此功能非常有用,因为共线性会导致协方差矩阵不可逆:
>>> X = [['male', 'from US', 'uses Safari'],
... ['female', 'from Europe', 'uses Firefox']]
>>> drop_enc = preprocessing.OneHotEncoder(drop='first').fit(X)
>>> drop_enc.categories_
[array(['female', 'male'], dtype=object), array(['from Europe', 'from US'], dtype=object),
array(['uses Firefox', 'uses Safari'], dtype=object)]
>>> drop_enc.transform(X).toarray()
array([[1., 1., 1.],
[0., 0., 0.]])
One might want to drop one of the two columns only for features with 2
categories. In this case, you can set the parameter drop='if_binary'
.
您可能希望仅针对具有 2 个类别的特征删除两列之一。在这种情况下,您可以设置参数 .
>>> X = [['male', 'US', 'Safari'],
... ['female', 'Europe', 'Firefox'],
... ['female', 'Asia', 'Chrome']]
>>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary').fit(X)
>>> drop_enc.categories_
[array(['female', 'male'], dtype=object), array(['Asia', 'Europe', 'US'], dtype=object),
array(['Chrome', 'Firefox', 'Safari'], dtype=object)]
>>> drop_enc.transform(X).toarray()
array([[1., 0., 0., 1., 0., 0., 1.],
[0., 0., 1., 0., 0., 1., 0.],
[0., 1., 0., 0., 1., 0., 0.]])
In the transformed X
, the first column is the encoding of the feature with
categories “male”/”female”, while the remaining 6 columns is the encoding of
the 2 features with respectively 3 categories each.
在转换后,第一列是类别为“male”/“female”的特征的编码,而其余6列是2个特征的编码,每个特征有3个类别。
When handle_unknown='ignore'
and drop
is not None, unknown categories will
be encoded as all zeros:
当 and 不是 None 时,未知类别将被编码为全零:
>>> drop_enc = preprocessing.OneHotEncoder(drop='first',
... handle_unknown='ignore').fit(X)
>>> X_test = [['unknown', 'America', 'IE']]
>>> drop_enc.transform(X_test).toarray()
array([[0., 0., 0., 0., 0.]])
All the categories in X_test
are unknown during transform and will be mapped
to all zeros. This means that unknown categories will have the same mapping as
the dropped category. OneHotEncoder.inverse_transform
will map all zeros
to the dropped category if a category is dropped and None
if a category is
not dropped:
中的所有类别在转换期间都是未知的,并且将映射到所有零。这意味着未知类别将与已删除的类别具有相同的映射。 如果删除了类别且未删除类别,则将所有零映射到已删除的类别:
>>> drop_enc = preprocessing.OneHotEncoder(drop='if_binary', sparse_output=False,
... handle_unknown='ignore').fit(X)
>>> X_test = [['unknown', 'America', 'IE']]
>>> X_trans = drop_enc.transform(X_test)
>>> X_trans
array([[0., 0., 0., 0., 0., 0., 0.]])
>>> drop_enc.inverse_transform(X_trans)
array([['female', None, None]], dtype=object)
Support of categorical features with missing values#
支持具有缺失值的分类特征#
OneHotEncoder
supports categorical features with missing values by
considering the missing values as an additional category:
>>> X = [['male', 'Safari'],
... ['female', None],
... [np.nan, 'Firefox']]
>>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)
>>> enc.categories_
[array(['female', 'male', nan], dtype=object),
array(['Firefox', 'Safari', None], dtype=object)]
>>> enc.transform(X).toarray()
array([[0., 1., 0., 0., 1., 0.],
[1., 0., 0., 0., 0., 1.],
[0., 0., 1., 1., 0., 0.]])
If a feature contains both np.nan
and None
, they will be considered
separate categories:
>>> X = [['Safari'], [None], [np.nan], ['Firefox']]
>>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)
>>> enc.categories_
[array(['Firefox', 'Safari', None, nan], dtype=object)]
>>> enc.transform(X).toarray()
array([[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.],
[1., 0., 0., 0.]])
See Loading features from dicts for categorical features that are represented as a dict, not as scalars.
6.3.4.1. Infrequent categories#
6.3.4.1. 不常见的分类#
OneHotEncoder
and OrdinalEncoder
support aggregating
infrequent categories into a single output for each feature. The parameters to
enable the gathering of infrequent categories are min_frequency
and
max_categories
.
并支持将不频繁的类别聚合到每个特征的单个输出中。用于收集不常见类别的参数是 和 。
min_frequency
is either an integer greater or equal to 1, or a float in the interval(0.0, 1.0)
. Ifmin_frequency
is an integer, categories with a cardinality smaller thanmin_frequency
will be considered infrequent. Ifmin_frequency
is a float, categories with a cardinality smaller than this fraction of the total number of samples will be considered infrequent. The default value is 1, which means every category is encoded separately.
是大于或等于 1 的整数,或者是区间 中的浮点数。如果是整数,则基数小于 的类别将被视为不常见。如果 是浮点数,则基数小于样本总数的此分数的类别将被视为不常见。默认值为 1,这意味着每个类别都单独编码。max_categories
is eitherNone
or any integer greater than 1. This parameter sets an upper limit to the number of output features for each input feature.max_categories
includes the feature that combines infrequent categories.
是 or 任何大于 1 的整数。此参数为每个输入要素的输出要素数量设置上限。 包括组合不频繁类别的功能。
In the following example with OrdinalEncoder
, the categories 'dog' and
'snake'
are considered infrequent:
在以下示例中,使用 ,这些类别被视为不常见:
>>> X = np.array([['dog'] * 5 + ['cat'] * 20 + ['rabbit'] * 10 +
... ['snake'] * 3], dtype=object).T
>>> enc = preprocessing.OrdinalEncoder(min_frequency=6).fit(X)
>>> enc.infrequent_categories_
[array(['dog', 'snake'], dtype=object)]
>>> enc.transform(np.array([['dog'], ['cat'], ['rabbit'], ['snake']]))
array([[2.],
[0.],
[1.],
[2.]])
OrdinalEncoder
’s max_categories
do not take into account missing
or unknown categories. Setting unknown_value
or encoded_missing_value
to an
integer will increase the number of unique integer codes by one each. This can
result in up to max_categories + 2
integer codes. In the following example,
“a” and “d” are considered infrequent and grouped together into a single
category, “b” and “c” are their own categories, unknown values are encoded as 3
and missing values are encoded as 4.
不考虑缺失或未知的类别。将 or 设置为整数将使唯一整数代码的数量每个增加 1。这可能导致最多为整数的代码。在以下示例中,“a” 和 “d” 被视为不常见,并一起分组到一个类别中,“b” 和 “c” 是它们自己的类别,未知值编码为 3,缺失值编码为 4。
>>> X_train = np.array(
... [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3 + [np.nan]],
... dtype=object).T
>>> enc = preprocessing.OrdinalEncoder(
... handle_unknown="use_encoded_value", unknown_value=3,
... max_categories=3, encoded_missing_value=4)
>>> _ = enc.fit(X_train)
>>> X_test = np.array([["a"], ["b"], ["c"], ["d"], ["e"], [np.nan]], dtype=object)
>>> enc.transform(X_test)
array([[2.],
[0.],
[1.],
[2.],
[3.],
[4.]])
Similarity, OneHotEncoder
can be configured to group together infrequent
categories:
相似性,可以配置为将不常见的类别组合在一起:
>>> enc = preprocessing.OneHotEncoder(min_frequency=6, sparse_output=False).fit(X)
>>> enc.infrequent_categories_
[array(['dog', 'snake'], dtype=object)]
>>> enc.transform(np.array([['dog'], ['cat'], ['rabbit'], ['snake']]))
array([[0., 0., 1.],
[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
By setting handle_unknown to 'infrequent_if_exist'
, unknown categories will
be considered infrequent:
通过将 handle_unknown 设置为 ,未知类别将被视为不常见:
>>> enc = preprocessing.OneHotEncoder(
... handle_unknown='infrequent_if_exist', sparse_output=False, min_frequency=6)
>>> enc = enc.fit(X)
>>> enc.transform(np.array([['dragon']]))
array([[0., 0., 1.]])
OneHotEncoder.get_feature_names_out
uses ‘infrequent’ as the infrequent
feature name:
使用 'infrequent' 作为 Infrequently Feature Name:
>>> enc.get_feature_names_out()
array(['x0_cat', 'x0_rabbit', 'x0_infrequent_sklearn'], dtype=object)
When 'handle_unknown'
is set to 'infrequent_if_exist'
and an unknown
category is encountered in transform:
当设置为 且在 transform 中遇到未知类别时:
If infrequent category support was not configured or there was no infrequent category during training, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as
None
.
如果未配置 infrequent category 支持,或者在训练期间没有 infrequent 类别,则此功能生成的 one-hot 编码列将全部为零。在逆变换中,未知类别将表示为 。If there is an infrequent category during training, the unknown category will be considered infrequent. In the inverse transform, ‘infrequent_sklearn’ will be used to represent the infrequent category.
如果在训练期间存在不频繁的类别,则未知类别将被视为不频繁。在逆变换中,'infrequent_sklearn' 将用于表示不频繁的类别。
Infrequent categories can also be configured using max_categories
. In the
following example, we set max_categories=2
to limit the number of features in
the output. This will result in all but the 'cat'
category to be considered
infrequent, leading to two features, one for 'cat'
and one for infrequent
categories - which are all the others:
不频繁的类别也可以使用 进行配置。在以下示例中,我们设置为限制输出中的特征数。这将导致除 category 之外的所有 cookie 都被视为不频繁,从而导致两个功能,一个用于 infrequent categories - 即所有其他 cookie:
>>> enc = preprocessing.OneHotEncoder(max_categories=2, sparse_output=False)
>>> enc = enc.fit(X)
>>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']])
array([[0., 1.],
[1., 0.],
[0., 1.],
[0., 1.]])
If both max_categories
and min_frequency
are non-default values, then
categories are selected based on min_frequency
first and max_categories
categories are kept. In the following example, min_frequency=4
considers
only snake
to be infrequent, but max_categories=3
, forces dog
to also be
infrequent:
如果 和 都是非默认值,则根据 first 选择类别并保留类别。在以下示例中,仅认为不频繁,但 强制也为不频繁:
>>> enc = preprocessing.OneHotEncoder(min_frequency=4, max_categories=3, sparse_output=False)
>>> enc = enc.fit(X)
>>> enc.transform([['dog'], ['cat'], ['rabbit'], ['snake']])
array([[0., 0., 1.],
[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
If there are infrequent categories with the same cardinality at the cutoff of
max_categories
, then then the first max_categories
are taken based on lexicon
ordering. In the following example, “b”, “c”, and “d”, have the same cardinality
and with max_categories=2
, “b” and “c” are infrequent because they have a higher
lexicon order.
如果在 的截止处存在具有相同基数的不常见类别,则根据词典排序采用第一个类别。在以下示例中,“b”、“c” 和 “d” 具有相同的基数,而 、 “b” 和 “c” 很少见,因为它们具有较高的词典顺序。
>>> X = np.asarray([["a"] * 20 + ["b"] * 10 + ["c"] * 10 + ["d"] * 10], dtype=object).T
>>> enc = preprocessing.OneHotEncoder(max_categories=3).fit(X)
>>> enc.infrequent_categories_
[array(['b', 'c'], dtype=object)]
6.3.4.2. Target Encoder#
6.3.4.2. 目标编码器#
The TargetEncoder
uses the target mean conditioned on the categorical
feature for encoding unordered categories, i.e. nominal categories [PAR]
[MIC]. This encoding scheme is useful with categorical features with high
cardinality, where one-hot encoding would inflate the feature space making it
more expensive for a downstream model to process. A classical example of high
cardinality categories are location based such as zip code or region.
它使用以分类特征为条件的目标均值来编码无序类别,即名义类别 [PAR][MIC]。此编码方案对于具有高基数的分类特征非常有用,其中独热编码会膨胀特征空间,使下游模型的处理成本更高。高基数类别的一个典型示例是基于位置,例如邮政编码或区域。
Binary classification targets#
二元分类目标#
For the binary classification target, the target encoding is given by:
where
where smooth
parameter in TargetEncoder
. Large smoothing factors will put more
weight on the global mean. When smooth="auto"
, the smoothing factor is
computed as an empirical Bayes estimate: y
with category y
.
Multiclass classification targets#
多类分类目标#
For multiclass classification targets, the formulation is similar to binary classification:
where
Continuous targets#
连续目标#
For continuous targets, the formulation is similar to binary classification:
where
fit_transform
internally relies on a cross fitting
scheme to prevent target information from leaking into the train-time
representation, especially for non-informative high-cardinality categorical
variables, and help prevent the downstream model from overfitting spurious
correlations. Note that as a result, fit(X, y).transform(X)
does not equal
fit_transform(X, y)
. In fit_transform
, the training
data is split into k folds (determined by the cv
parameter) and each fold is
encoded using the encodings learnt using the other k-1 folds. The following
diagram shows the cross fitting scheme in
fit_transform
with the default cv=5
:
内部依赖于交叉拟合方案来防止目标信息泄漏到训练时间表示中,特别是对于非信息性高基数分类变量,并有助于防止下游模型过度拟合虚假相关性。请注意,因此, 不等于 。在 中,训练数据被分成 k 个折叠(由参数确定),每个折叠都使用使用其他 k-1 个折叠学习的编码进行编码。下图显示了默认的交叉拟合方案:
fit_transform
also learns a ‘full data’ encoding using
the whole training set. This is never used in
fit_transform
but is saved to the attribute encodings_
,
for use when transform
is called. Note that the encodings
learned for each fold during the cross fitting scheme are not saved to
an attribute.
此外,还使用整个训练集学习 'full data' 编码。这永远不会在 中使用,而是保存到属性 中,以便在调用时使用。请注意,在交叉拟合方案期间为每个折叠学习的编码不会保存到属性中。
The fit
method does not use any cross fitting
schemes and learns one encoding on the entire training set, which is used to
encode categories in transform
.
This encoding is the same as the ‘full data’
encoding learned in fit_transform
.
该方法不使用任何交叉拟合方案,而是在整个训练集上学习一种编码,该编码用于对 中的类别进行编码。此编码与 中学习的“完整数据”编码相同。
Note 注意
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_
.
将缺失值(如 或 )视为另一个类别,并像任何其他类别一样对其进行编码。期间未看到的类别使用目标均值进行编码,即 。
Examples 例子
References 引用