مطالعهٔ scikit-learn Docs
انتخاب و ارزیابی مدل، پیشپردازش داده، اشتباهات رایج
باز کردن مرجع کامل دانلود آرشیو مستندات ناشر
گزیدهای از مستندات scikit-learn Docs · نسخهٔ 5e9184e53cd3 · BSD-3-Clause
انتخاب و ارزیابی مدل
Model selection and evaluation
:maxdepth: 2
modules/cross_validation modules/grid_search modules/classification_threshold modules/model_evaluation modules/learning_curve
پیشپردازش داده
==================
Preprocessing data
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.
In general, many learning algorithms such as linear models benefit from standardization of the data set (see sphx_glr_auto_examples_preprocessing_plot_scaling_importance.py). 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 are highlighted in sphx_glr_auto_examples_preprocessing_plot_all_scaling.py.
Standardization, or mean removal and variance scaling
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.
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.
The ~sklearn.preprocessing module provides the StandardScaler utility class, which is a quick and easy way to perform the following operation on an array-like dataset::
توجه: >> 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.267], [-1.22, 1.22, -1.06 ]])
..
توجه: >> import numpy as np >> print_options = np.get_printoptions() >> np.set_printoptions(suppress=True)
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 ~sklearn.pipeline.Pipeline`::
توجه: >> 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`.
Scaling features to a range
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.
The motivation to use this scaling includes 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::
توجه: >> 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::
توجه: >> 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.])
Scaling sparse data
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.
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.
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.
Scaling data with outliers
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.
Further discussion on the importance of centering and scaling data is available on this FAQ: Should I normalize/standardize/rescale the data? <http://www.faqs.org/faqs/ai-faq/neural-nets/part2/section-16.html>_
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 ~sklearn.decomposition.PCA with `whiten=True` to further remove the linear correlation across features.
Centering kernel matrices
If you have a kernel matrix of a kernel K that computes a dot product in a feature space (possibly implicitly) defined by a function \phi(\cdot), a KernelCenterer can transform the kernel matrix so that it contains inner products in the feature space defined by \phi followed by the removal of the mean in that space. In other words, KernelCenterer computes the centered Gram matrix associated to a positive semidefinite kernel K.
We can have a look at the mathematical formulation now that we have the intuition. Let K be a kernel matrix of shape (n_samples, n_samples) computed from X, a data matrix of shape (n_samples, n_features), during the fit step. K is defined by
K(X, X) = \phi(X) . \phi(X)^{T}
\phi(X) is a function mapping of X to a Hilbert space. A centered kernel \tilde{K} is defined as:
\tilde{K}(X, X) = \tilde{\phi}(X) . \tilde{\phi}(X)^{T}
where \tilde{\phi}(X) results from centering \phi(X) in the Hilbert space.
Thus, one could compute \tilde{K} by mapping X using the function \phi(\cdot) and center the data in this new space. However, kernels are often used because they allow some algebra calculations that avoid computing explicitly this mapping using \phi(\cdot). Indeed, one can implicitly center as shown in Appendix B in [Scholkopf1998]_:
\tilde{K} = K - 1_{\text{n}_{samples}} K - K 1_{\text{n}_{samples}} + 1_{\text{n}_{samples}} K 1_{\text{n}_{samples}}
1_{\text{n}_{samples}} is a matrix of (n_samples, n_samples) where all entries are equal to \frac{1}{\text{n}_{samples}}. In the transform step, the kernel becomes K_{test}(X, Y) defined as:
K_{test}(X, Y) = \phi(Y) . \phi(X)^{T}
Y is the test dataset of shape (n_samples_test, n_features) and thus K_{test} is of shape (n_samples_test, n_samples). In this case, centering K_{test} is done as:
\tilde{K}_{test}(X, Y) = K_{test} - 1'_{\text{n}_{samples}} K - K_{test} 1_{\text{n}_{samples}} + 1'_{\text{n}_{samples}} K 1_{\text{n}_{samples}}
1'_{\text{n}_{samples}} is a matrix of shape (n_samples_test, n_samples) where all entries are equal to \frac{1}{\text{n}_{samples}}.
"Nonlinear component analysis as a kernel eigenvalue problem." <https://www.mlpack.org/papers/kpca.pdf>_ Neural computation 10.5 (1998): 1299-1319.
Non-linear transformation
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 G^{-1}(F(X)) where F is the cumulative distribution function of the feature and G^{-1} the quantile function <https://en.wikipedia.org/wiki/Quantile_function>_ of the desired output distribution G. This formula is using the two following facts: (i) if X is a random variable with a continuous cumulative distribution function F then F(X) is uniformly distributed on [0,1]; (ii) if U is a random variable with uniform distribution on [0,1] then G^{-1}(U) has distribution G. By performing a rank transformation, a quantile transform smooths out unusual distributions and is less influenced by outliers than scaling methods. It does, however, distort correlations and distances within and across features.
Power transforms are a family of parametric transformations that aim to map data from any distribution to as close to a Gaussian distribution.
Mapping to a Uniform distribution
QuantileTransformer provides a non-parametric transformation to map the data to a uniform distribution with values between 0 and 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]) # doctest: +SKIP
array([ 4.3, 5.1, 5.8, 6.5, 7.9])
This feature corresponds to the sepal length in cm. Once the quantile transformation is applied, those landmarks approach closely the percentiles previously defined::
توجه: >> np.percentile(X_train_trans[:, 0], [0, 25, 50, 75, 100])
... # doctest: +SKIP array([ 0.00 , 0.24, 0.49, 0.73, 0.99 ])
This can be confirmed on an independent testing set with similar remarks::
توجه: >> np.percentile(X_test[:, 0], [0, 25, 50, 75, 100])
... # doctest: +SKIP array([ 4.4 , 5.125, 5.75 , 6.175, 7.3 ])
توجه: >> np.percentile(X_test_trans[:, 0], [0, 25, 50, 75, 100])
... # doctest: +SKIP array([ 0.01, 0.25, 0.46, 0.60 , 0.94])
Mapping to a Gaussian distribution
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.
x_i^{(\lambda)} = \begin{cases} [(x_i + 1)^\lambda - 1] / \lambda & \text{if } \lambda \neq 0, x_i \geq 0, \\[8pt] \ln{(x_i + 1)} & \text{if } \lambda = 0, x_i \geq 0 \\[8pt] -[(-x_i + 1)^{2 - \lambda} - 1] / (2 - \lambda) & \text{if } \lambda \neq 2, x_i < 0, \\[8pt]
- \ln (- x_i + 1) & \text{if } \lambda = 2, x_i < 0
\end{cases}
x_i^{(\lambda)} = \begin{cases} \dfrac{x_i^\lambda - 1}{\lambda} & \text{if } \lambda \neq 0, \\[8pt] \ln{(x_i)} & \text{if } \lambda = 0, \end{cases}
Box-Cox can only be applied to strictly positive data. In both methods, the transformation is parameterized by \lambda, which is determined through maximum likelihood estimation. Here is an example of using Box-Cox to map samples drawn from a lognormal distribution to a normal distribution::
توجه: >> 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.388], [1.35, 0.217, 1.09 ]])
توجه: >> pt.fit_transform(X_lognormal)
array([[ 0.49 , 0.179, -0.156], [-0.051, 0.589, -0.576], [ 0.69 , -0.849, 0.101]])
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.
:target: ../auto_examples/preprocessing/plot_map_data_to_normal.html :align: center :scale: 100
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::
توجه: >> quantile_transformer = preprocessing.QuantileTransformer(
... output_distribution='normal', n_quantiles=150, 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.
Normalization
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.
This assumption is the base of the Vector Space Model <https://en.wikipedia.org/wiki/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::
توجه: >> X = [[ 1., -1., 2.],
... [ 2., 0., 0.], ... [ 0., 1., -1.]]
توجه: >> X_normalized = preprocessing.normalize(X, norm='l2')
توجه: >> X_normalized
array([[ 0.408, -0.408, 0.812], [ 1. , 0. , 0. ], [ 0. , 0.707, -0.707]])
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).
This class is hence suitable for use in the early steps of a ~sklearn.pipeline.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.408, -0.408, 0.812], [ 1. , 0. , 0. ], [ 0. , 0.707, -0.707]])
توجه: >> normalizer.transform([[-1., 1., 0.]])
array([[-0.707, 0.707, 0.]])
Note: L2 normalization is also known as spatial sign preprocessing.
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.
Encoding categorical features
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]`.
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)::
توجه: >> 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).
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 ~sklearn.impute.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.
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::
توجه: >> 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)::
توجه: >> 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 <sklearn.linear_model.LinearRegression>`), since co-linearity would cause the covariance matrix to be non-invertible::
توجه: >> 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'.
توجه: >> 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 are the encoding of the 2 features with respectively 3 categories each.
When handle_unknown='ignore' and drop is not None, unknown categories will be encoded as all zeros::
توجه: >> 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)
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 dict_feature_extraction for categorical features that are represented as a dict, not as scalars.
Infrequent categories
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_frequencyis either an integer greater or equal to 1, or a float in
the interval (0.0, 1.0). If min_frequency is an integer, categories with a cardinality smaller than min_frequency will be considered infrequent. If min_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.
max_categoriesis eitherNoneor 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.
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.
توجه: >> 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.]])
Similarly, 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::
توجه: >> 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::
توجه: >> 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:
- 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.
- 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 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::
توجه: >> 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::
توجه: >> 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 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.
توجه: >> 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)]
Target Encoder
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.
For the binary classification target, the target encoding is given by:
S_i = \lambda_i\frac{n_{iY}}{n_i} + (1 - \lambda_i)\frac{n_Y}{n}
where S_i is the encoding for category i, n_{iY} is the number of observations with Y=1 and category i, n_i is the number of observations with category i, n_Y is the number of observations with Y=1, n is the number of observations, and \lambda_i is a shrinkage factor for category i. The shrinkage factor is given by:
\lambda_i = \frac{n_i}{m + n_i}
where m is a smoothing factor, which is controlled with the 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: m=\sigma_i^2/\tau^2, where \sigma_i^2 is the variance of y with category i and \tau^2 is the global variance of y.
For multiclass classification targets, the formulation is similar to binary classification:
S_{ij} = \lambda_i\frac{n_{iY_j}}{n_i} + (1 - \lambda_i)\frac{n_{Y_j}}{n}
where S_{ij} is the encoding for category i and class j, n_{iY_j} is the number of observations with Y=j and category i, n_i is the number of observations with category i, n_{Y_j} is the number of observations with Y=j, n is the number of observations, and \lambda_i is a shrinkage factor for category i.
For continuous targets, the formulation is similar to binary classification:
S_i = \lambda_i\frac{\sum_{k\in L_i}Y_k}{n_i} + (1 - \lambda_i)\frac{\sum_{k=1}^{n}Y_k}{n}
where L_i is the set of observations with category i and n_i is the number of observations with category i.
In TargetEncoder, fit(X, y).transform(X) does not equal fit_transform(X, y).
~TargetEncoder.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 (features with many unique categories where each category appears only a few times), and help prevent the downstream model from overfitting spurious correlations. In ~TargetEncoder.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. For this reason, training data should always be trained and transformed with fit_transform(X_train, y_train).
This diagram shows the cross fitting scheme in ~TargetEncoder.fit_transform with the default cv=5:
:width: 600 :align: center
The ~TargetEncoder.fit method does not use any cross fitting schemes and learns one encoding on the entire training set. It is discouraged to use this method because it can introduce data leakage as mentioned above. Use ~TargetEncoder.fit_transform instead.
During ~TargetEncoder.fit_transform, the encoder learns category encodings from the full training data and stores them in the ~TargetEncoder.encodings_ attribute. The intermediate encodings learned for each fold during the cross fitting process are temporary and not saved. The stored encodings can then be used to transform test data with encoder.transform(X_test).
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_.
sphx_glr_auto_examples_preprocessing_plot_target_encoder.pysphx_glr_auto_examples_preprocessing_plot_target_encoder_cross_val.py
categorical attributes in classification and prediction problems" SIGKDD Explor. Newsl. 3, 1 (July 2001), 27-32. <10.1145/507533.507538>`
encoding outperforms traditional methods in supervised machine learning with high cardinality features" Comput Stat 37, 2671-2692 (2022) <10.1007/s00180-022-01207-6>`
Discretization
Discretization <https://en.wikipedia.org/wiki/Discretization_of_continuous_features>_ (otherwise known as quantization or binning) provides a way to partition continuous features into discrete values. Certain datasets with continuous features may benefit from discretization, because discretization can transform the dataset of continuous attributes to one with only nominal attributes.
One-hot encoded discretized features can make a model more expressive, while maintaining interpretability. For instance, pre-processing with a discretizer can introduce nonlinearity to linear models. For more advanced possibilities, in particular smooth ones, see generating_polynomial_features further below.
K-bins discretization
KBinsDiscretizer discretizes features into `k` bins::
توجه: >> X = np.array([[ -3., 5., 15 ],
... [ 0., 6., 14 ], ... [ 6., 3., 11 ]])
توجه: >> est = preprocessing.KBinsDiscretizer(n_bins=[3, 2, 2], encode='ordinal').fit(X)
By default the output is one-hot encoded into a sparse matrix (See preprocessing_categorical_features) and this can be configured with the `encode parameter. For each feature, the bin edges are computed during fit` and together with the number of bins, they will define the intervals. Therefore, for the current example, these intervals are defined as:
- feature 1:
{[-\infty, -1), [-1, 2), [2, \infty)} - feature 2:
{[-\infty, 5), [5, \infty)} - feature 3:
{[-\infty, 14), [14, \infty)}
Based on these bin intervals, `X` is transformed as follows::
توجه: >> est.transform(X) # doctest: +SKIP
array([[ 0., 1., 1.], [ 1., 1., 1.], [ 2., 0., 0.]])
The resulting dataset contains ordinal attributes which can be further used in a ~sklearn.pipeline.Pipeline.
Discretization is similar to constructing histograms for continuous data. However, histograms focus on counting features which fall into particular bins, whereas discretization focuses on assigning feature values to these bins.
KBinsDiscretizer implements different binning strategies, which can be selected with the `strategy` parameter. The 'uniform' strategy uses constant-width bins. The 'quantile' strategy uses the quantiles values to have equally populated bins in each feature. The 'kmeans' strategy defines bins based on a k-means clustering procedure performed on each feature independently.
Be aware that one can specify custom bins by passing a callable defining the discretization strategy to ~sklearn.preprocessing.FunctionTransformer. For instance, we can use the Pandas function pandas.cut::
توجه: >> import pandas as pd >> import numpy as np >> from sklearn import preprocessing >> >> bins = [0, 1, 13, 20, 60, np.inf] >> labels = ['infant', 'kid', 'teen', 'adult', 'senior citizen'] >> transformer = preprocessing.FunctionTransformer(
... pd.cut, kw_args={'bins': bins, 'labels': labels, 'retbins': False} ... )
توجه: >> X = np.array([0.2, 2, 15, 25, 97]) >> transformer.fit_transform(X)
['infant', 'kid', 'teen', 'adult', 'senior citizen'] Categories (5, str): ['infant' < 'kid' < 'teen' < 'adult' < 'senior citizen']
sphx_glr_auto_examples_preprocessing_plot_discretization.pysphx_glr_auto_examples_preprocessing_plot_discretization_classification.pysphx_glr_auto_examples_preprocessing_plot_discretization_strategies.py
Feature binarization
Feature binarization is the process of thresholding numerical features to get boolean values. This can be useful for downstream probabilistic estimators that make assumption that the input data is distributed according to a multi-variate Bernoulli distribution <https://en.wikipedia.org/wiki/Bernoulli_distribution>_. For instance, this is the case for the ~sklearn.neural_network.BernoulliRBM.
It is also common among the text processing community to use binary feature values (probably to simplify the probabilistic reasoning) even if normalized counts (a.k.a. term frequencies) or TF-IDF valued features often perform slightly better in practice.
As for the Normalizer, the utility class Binarizer is meant to be used in the early stages of ~sklearn.pipeline.Pipeline. The `fit` method does nothing as each sample is treated independently of others::
توجه: >> X = [[ 1., -1., 2.],
... [ 2., 0., 0.], ... [ 0., 1., -1.]]
توجه: >> binarizer = preprocessing.Binarizer().fit(X) # fit does nothing >> binarizer
Binarizer()
توجه: >> binarizer.transform(X)
array([[1., 0., 1.], [1., 0., 0.], [0., 1., 0.]])
It is possible to adjust the threshold of the binarizer::
توجه: >> binarizer = preprocessing.Binarizer(threshold=1.1) >> binarizer.transform(X)
array([[0., 0., 1.], [1., 0., 0.], [0., 0., 0.]])
As for the Normalizer class, the preprocessing module provides a companion function binarize to be used when the transformer API is not necessary.
Note that the Binarizer is similar to the KBinsDiscretizer when `k = 2, and when the bin edge is at the value threshold`.
binarize and Binarizer 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`). To avoid unnecessary memory copies, it is recommended to choose the CSR representation upstream.
Imputation of missing values
Tools for imputing missing values are discussed at impute.
Generating polynomial features
Often it's useful to add complexity to a model by considering nonlinear features of the input data. We show two possibilities that are both based on polynomials: The first one uses pure polynomials, the second one uses splines, i.e. piecewise polynomials.
Polynomial features
A simple and common method to use is polynomial features, which can get features' high-order and interaction terms. It is implemented in PolynomialFeatures::
توجه: >> import numpy as np >> from sklearn.preprocessing import PolynomialFeatures >> X = np.arange(6).reshape(3, 2) >> X
array([[0, 1], [2, 3], [4, 5]])
توجه: >> poly = PolynomialFeatures(2) >> poly.fit_transform(X)
array([[ 1., 0., 1., 0., 0., 1.], [ 1., 2., 3., 4., 6., 9.], [ 1., 4., 5., 16., 20., 25.]])
The features of X have been transformed from (X_1, X_2) to (1, X_1, X_2, X_1^2, X_1X_2, X_2^2).
In some cases, only interaction terms among features are required, and it can be gotten with the setting `interaction_only=True`::
توجه: >> X = np.arange(9).reshape(3, 3) >> X
array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
توجه: >> poly = PolynomialFeatures(degree=3, interaction_only=True) >> poly.fit_transform(X)
array([[ 1., 0., 1., 2., 0., 0., 2., 0.], [ 1., 3., 4., 5., 12., 15., 20., 60.], [ 1., 6., 7., 8., 42., 48., 56., 336.]])
The features of X have been transformed from (X_1, X_2, X_3) to (1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3).
Note that polynomial features are used implicitly in kernel methods <https://en.wikipedia.org/wiki/Kernel_method>_ (e.g., ~sklearn.svm.SVC, ~sklearn.decomposition.KernelPCA) when using polynomial svm_kernels.
See sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py for Ridge regression using created polynomial features.
Spline transformer
Another way to add nonlinear terms instead of pure polynomials of features is to generate spline basis functions for each feature with the SplineTransformer. Splines are piecewise polynomials, parametrized by their polynomial degree and the positions of the knots. The SplineTransformer implements a B-spline basis, cf. the references below.
The SplineTransformer treats each feature separately, i.e. it won't give you interaction terms.
Some of the advantages of splines over polynomials are:
- B-splines are very flexible and robust if you keep a fixed low degree,
usually 3, and parsimoniously adapt the number of knots. Polynomials would need a higher degree, which leads to the next point.
- B-splines do not have oscillatory behaviour at the boundaries as have
polynomials (the higher the degree, the worse). This is known as Runge's phenomenon <https://en.wikipedia.org/wiki/Runge%27s_phenomenon>_.
- B-splines provide good options for extrapolation beyond the boundaries,
i.e. beyond the range of fitted values. Have a look at the option `extrapolation`.
- B-splines generate a feature matrix with a banded structure. For a single
feature, every row contains only `degree + 1 non-zero elements, which occur consecutively and are even positive. This results in a matrix with good numerical properties, e.g. a low condition number, in sharp contrast to a matrix of polynomials, which goes under the name Vandermonde matrix <https://en.wikipedia.org/wiki/Vandermonde_matrix>`_. A low condition number is important for stable algorithms of linear models.
The following code snippet shows splines in action::
توجه: >> import numpy as np >> from sklearn.preprocessing import SplineTransformer >> X = np.arange(5).reshape(5, 1) >> X
array([[0], [1], [2], [3], [4]])
توجه: >> spline = SplineTransformer(degree=2, n_knots=3) >> spline.fit_transform(X)
array([[0.5 , 0.5 , 0. , 0. ], [0.125, 0.75 , 0.125, 0. ], [0. , 0.5 , 0.5 , 0. ], [0. , 0.125, 0.75 , 0.125], [0. , 0. , 0.5 , 0.5 ]])
As the `X is sorted, one can easily see the banded matrix output. Only the three middle diagonals are non-zero for degree=2`. The higher the degree, the more overlapping of the splines.
Interestingly, a SplineTransformer of `degree=0 is the same as ~sklearn.preprocessing.KBinsDiscretizer with encode='onehot-dense' and n_bins = n_knots - 1 if knots = strategy`.
sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.pysphx_glr_auto_examples_applications_plot_cyclical_feature_engineering.py
- Eilers, P., & Marx, B. (1996). :doi:`Flexible Smoothing with B-splines and
Penalties <10.1214/ss/1038425655>`. Statist. Sci. 11 (1996), no. 2, 89--121.
- Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. :doi:`A review of
spline function procedures in R <10.1186/s12874-019-0666-3>`. BMC Med Res Methodol 19, 46 (2019).
Custom transformers
Often, you will want to convert an existing Python function into a transformer to assist in data cleaning or processing. You can implement a transformer from an arbitrary function with FunctionTransformer. For example, to build a transformer that applies a log transformation in a pipeline, do::
توجه: >> import numpy as np >> from sklearn.preprocessing import FunctionTransformer >> transformer = FunctionTransformer(np.log1p, validate=True) >> X = np.array([[0, 1], [2, 3]]) >> # Since FunctionTransformer is no-op during fit, we can call transform directly >> transformer.transform(X)
array([[0. , 0.69314718], [1.09861229, 1.38629436]])
You can ensure that `func and inverse_func are the inverse of each other by setting check_inverse=True and calling fit before transform. Please note that a warning is raised and can be turned into an error with a filterwarnings`::
توجه: >> import warnings >> warnings.filterwarnings("error", message=".*check_inverse*.",
... category=UserWarning, append=False)
For a full code example that demonstrates using a FunctionTransformer to extract features from text data see sphx_glr_auto_examples_compose_plot_column_transformer.py and sphx_glr_auto_examples_applications_plot_cyclical_feature_engineering.py.
اشتباهات رایج
=========================================
Common pitfalls and recommended practices
The purpose of this chapter is to illustrate some common pitfalls and anti-patterns that occur when using scikit-learn. It provides examples of what not to do, along with a corresponding correct example.
Inconsistent preprocessing
scikit-learn provides a library of data-transforms, which may clean (see preprocessing), reduce (see data_reduction), expand (see kernel_approximation) or generate (see feature_extraction) feature representations. If these data transforms are used when training a model, they also must be used on subsequent datasets, whether it's test data or data in a production system. Otherwise, the feature space will change, and the model will not be able to perform effectively.
For the following example, let's create a synthetic dataset with a single feature::
توجه: >> from sklearn.datasets import make_regression >> from sklearn.model_selection import train_test_split
توجه: >> random_state = 42 >> X, y = make_regression(random_state=random_state, n_features=1, noise=1) >> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.4, random_state=random_state)
Wrong
The train dataset is scaled, but not the test dataset, so model performance on the test dataset is worse than expected::
توجه: >> from sklearn.metrics import mean_squared_error >> from sklearn.linear_model import LinearRegression >> from sklearn.preprocessing import StandardScaler
توجه: >> scaler = StandardScaler() >> X_train_transformed = scaler.fit_transform(X_train) >> model = LinearRegression().fit(X_train_transformed, y_train) >> mean_squared_error(y_test, model.predict(X_test))
62.80...
Right
Instead of passing the non-transformed X_test to predict, we should transform the test data, the same way we transformed the training data::
توجه: >> X_test_transformed = scaler.transform(X_test) >> mean_squared_error(y_test, model.predict(X_test_transformed))
0.90...
Alternatively, we recommend using a :class:Pipeline <sklearn.pipeline.Pipeline>, which makes it easier to chain transformations with estimators, and reduces the possibility of forgetting a transformation::
توجه: >> from sklearn.pipeline import make_pipeline
توجه: >> model = make_pipeline(StandardScaler(), LinearRegression()) >> model.fit(X_train, y_train)
Pipeline(steps=[('standardscaler', StandardScaler()), ('linearregression', LinearRegression())])
توجه: >> mean_squared_error(y_test, model.predict(X_test))
0.90...
Pipelines also help avoiding another common pitfall: leaking the test data into the training data.
Data leakage
Data leakage occurs when information that would not be available at prediction time is used when building the model. This results in overly optimistic performance estimates, for example from :ref:cross-validation <cross_validation>, and thus poorer performance when the model is used on actually novel data, for example during production.
A common cause is not keeping the test and train data subsets separate. Test data should never be used to make choices about the model. The general rule is to never call fit on the test data. While this may sound obvious, this is easy to miss in some cases, for example when applying certain pre-processing steps.
Although both train and test data subsets should receive the same preprocessing transformation (as described in the previous section), it is important that these transformations are only learnt from the training data. For example, if you have a normalization step where you divide by the average value, the average should be the average of the train subset, not the average of all the data. If the test subset is included in the average calculation, information from the test subset is influencing the model.
How to avoid data leakage
Below are some tips on avoiding data leakage:
- Always split the data into train and test subsets first, particularly
before any preprocessing steps.
- Never include test data when using the
fitandfit_transform
methods. Using all the data, e.g., fit(X), can result in overly optimistic scores.
Conversely, the transform method should be used on both train and test subsets as the same preprocessing should be applied to all the data. This can be achieved by using fit_transform on the train subset and transform on the test subset.
- The scikit-learn
pipeline <pipeline>is a great way to prevent data
leakage as it ensures that the appropriate method is performed on the correct data subset. The pipeline is ideal for use in cross-validation and hyper-parameter tuning functions.
An example of data leakage during preprocessing is detailed below.
Data leakage during pre-processing
We here choose to illustrate data leakage with a feature selection step. This risk of leakage is however relevant with almost all transformations in scikit-learn, including (but not limited to) ~sklearn.preprocessing.StandardScaler, ~sklearn.impute.SimpleImputer, and ~sklearn.decomposition.PCA.
A number of feature_selection functions are available in scikit-learn. They can help remove irrelevant, redundant and noisy features as well as improve your model build time and performance. As with any other type of preprocessing, feature selection should only use the training data. Including the test data in feature selection will optimistically bias your model.
To demonstrate we will create this binary classification problem with 10,000 randomly generated features::
توجه: >> import numpy as np >> n_samples, n_features, n_classes = 200, 10000, 2 >> rng = np.random.RandomState(42) >> X = rng.standard_normal((n_samples, n_features)) >> y = rng.choice(n_classes, n_samples)
Wrong
Using all the data to perform feature selection results in an accuracy score much higher than chance, even though our targets are completely random. This randomness means that our X and y are independent and we thus expect the accuracy to be around 0.5. However, since the feature selection step 'sees' the test data, the model has an unfair advantage. In the incorrect example below we first use all the data for feature selection and then split the data into training and test subsets for model fitting. The result is a much higher than expected accuracy score::
توجه: >> from sklearn.model_selection import train_test_split >> from sklearn.feature_selection import SelectKBest >> from sklearn.ensemble import HistGradientBoostingClassifier >> from sklearn.metrics import accuracy_score
توجه: >> # Incorrect preprocessing: the entire data is transformed >> X_selected = SelectKBest(k=25).fit_transform(X, y)
توجه: >> X_train, X_test, y_train, y_test = train_test_split(
... X_selected, y, random_state=42)
توجه: >> gbc = HistGradientBoostingClassifier(random_state=1) >> gbc.fit(X_train, y_train)
HistGradientBoostingClassifier(random_state=1)
توجه: >> y_pred = gbc.predict(X_test) >> accuracy_score(y_test, y_pred)
0.76
Right
To prevent data leakage, it is good practice to split your data into train and test subsets first. Feature selection can then be formed using just the train dataset. Notice that whenever we use fit or fit_transform, we only use the train dataset. The score is now what we would expect for the data, close to chance::
توجه: >> X_train, X_test, y_train, y_test = train_test_split(
... X, y, random_state=42)
توجه: >> select = SelectKBest(k=25) >> X_train_selected = select.fit_transform(X_train, y_train)
توجه: >> gbc = HistGradientBoostingClassifier(random_state=1) >> gbc.fit(X_train_selected, y_train)
HistGradientBoostingClassifier(random_state=1)
توجه: >> X_test_selected = select.transform(X_test) >> y_pred = gbc.predict(X_test_selected) >> accuracy_score(y_test, y_pred)
0.5
Here again, we recommend using a ~sklearn.pipeline.Pipeline to chain together the feature selection and model estimators. The pipeline ensures that only the training data is used when performing fit and the test data is used only for calculating the accuracy score::
توجه: >> from sklearn.pipeline import make_pipeline >> X_train, X_test, y_train, y_test = train_test_split(
... X, y, random_state=42)
توجه: >> pipeline = make_pipeline(SelectKBest(k=25),
... HistGradientBoostingClassifier(random_state=1))
توجه: >> pipeline.fit(X_train, y_train)
Pipeline(steps=[('selectkbest', SelectKBest(k=25)), ('histgradientboostingclassifier', HistGradientBoostingClassifier(random_state=1))])
توجه: >> y_pred = pipeline.predict(X_test) >> accuracy_score(y_test, y_pred)
0.5
The pipeline can also be fed into a cross-validation function such as ~sklearn.model_selection.cross_val_score. Again, the pipeline ensures that the correct data subset and estimator method is used during fitting and predicting::
توجه: >> from sklearn.model_selection import cross_val_score >> scores = cross_val_score(pipeline, X, y) >> print(f"Mean accuracy: {scores.mean():.2f}+/-{scores.std():.2f}")
Mean accuracy: 0.43+/-0.05
Controlling randomness
Some scikit-learn objects are inherently random. These are usually estimators (e.g. ~sklearn.ensemble.RandomForestClassifier) and cross-validation splitters (e.g. ~sklearn.model_selection.KFold). The randomness of these objects is controlled via their random_state parameter, as described in the Glossary <random_state>. This section expands on the glossary entry, and describes good practices and common pitfalls w.r.t. this subtle parameter.
For an optimal robustness of cross-validation (CV) results, pass RandomState instances when creating estimators, or leave random_state to None. Passing integers to CV splitters is usually the safest option and is preferable; passing RandomState instances to splitters may sometimes be useful to achieve very specific use-cases. For both estimators and splitters, passing an integer vs passing an instance (or None) leads to subtle but significant differences, especially for CV procedures. These differences are important to understand when reporting results.
For reproducible results across executions, remove any use of random_state=None.
Using None or RandomState instances, and repeated calls to fit and split
The random_state parameter determines whether multiple calls to fit (for estimators) or to split (for CV splitters) will produce the same results, according to these rules:
- If an integer is passed, calling
fitorsplitmultiple times always
yields the same results.
- If
Noneor aRandomStateinstance is passed:fitandsplitwill
yield different results each time they are called, and the succession of calls explores all sources of entropy. None is the default value for all random_state parameters.
We here illustrate these rules for both estimators and CV splitters.
Since passing random_state=None is equivalent to passing the global RandomState instance from numpy (random_state=np.random.mtrand._rand), we will not explicitly mention None here. Everything that applies to instances also applies to using None.
Estimators ..........
Passing instances means that calling fit multiple times will not yield the same results, even if the estimator is fitted on the same data and with the same hyper-parameters::
توجه: >> from sklearn.linear_model import SGDClassifier >> from sklearn.datasets import make_classification >> import numpy as np
توجه: >> rng = np.random.RandomState(0) >> X, y = make_classification(n_features=5, random_state=rng) >> sgd = SGDClassifier(random_state=rng)
توجه: >> sgd.fit(X, y).coef_
array([[ 8.85418642, 4.79084103, -3.13077794, 8.11915045, -0.56479934]])
توجه: >> sgd.fit(X, y).coef_
array([[ 6.70814003, 5.25291366, -7.55212743, 5.18197458, 1.37845099]])
We can see from the snippet above that repeatedly calling sgd.fit has produced different models, even if the data was the same. This is because the Random Number Generator (RNG) of the estimator is consumed (i.e. mutated) when fit is called, and this mutated RNG will be used in the subsequent calls to fit. In addition, the rng object is shared across all objects that use it, and as a consequence, these objects become somewhat inter-dependent. For example, two estimators that share the same RandomState instance will influence each other, as we will see later when we discuss cloning. This point is important to keep in mind when debugging.
If we had passed an integer to the random_state parameter of the ~sklearn.linear_model.SGDClassifier, we would have obtained the same models, and thus the same scores each time. When we pass an integer, the same RNG is used across all calls to fit. What internally happens is that even though the RNG is consumed when fit is called, it is always reset to its original state at the beginning of fit.
CV splitters ............
Randomized CV splitters have a similar behavior when a RandomState instance is passed; calling split multiple times yields different data splits::
توجه: >> from sklearn.model_selection import KFold >> import numpy as np
توجه: >> X = y = np.arange(10) >> rng = np.random.RandomState(0) >> cv = KFold(n_splits=2, shuffle=True, random_state=rng)
توجه: >> for train, test in cv.split(X, y):
... print(train, test) [0 3 5 6 7] [1 2 4 8 9] [1 2 4 8 9] [0 3 5 6 7]
توجه: >> for train, test in cv.split(X, y):
... print(train, test) [0 4 6 7 8] [1 2 3 5 9] [1 2 3 5 9] [0 4 6 7 8]
We can see that the splits are different from the second time split is called. This may lead to unexpected results if you compare the performance of multiple estimators by calling split many times, as we will see in the next section.
Common pitfalls and subtleties
While the rules that govern the random_state parameter are seemingly simple, they do however have some subtle implications. In some cases, this can even lead to wrong conclusions.
Estimators ..........
Different random_state types lead to different cross-validation procedures
Depending on the type of the random_state parameter, estimators will behave differently, especially in cross-validation procedures. Consider the following snippet::
توجه: >> from sklearn.ensemble import RandomForestClassifier >> from sklearn.datasets import make_classification >> from sklearn.model_selection import cross_val_score >> import numpy as np
توجه: >> X, y = make_classification(random_state=0)
توجه: >> rf_123 = RandomForestClassifier(random_state=123) >> cross_val_score(rf_123, X, y)
array([0.85, 0.95, 0.95, 0.9 , 0.9 ])
توجه: >> rf_inst = RandomForestClassifier(random_state=np.random.RandomState(0)) >> cross_val_score(rf_inst, X, y)
array([0.9 , 0.95, 0.95, 0.9 , 0.9 ])
We see that the cross-validated scores of rf_123 and rf_inst are different, as should be expected since we didn't pass the same random_state parameter. However, the difference between these scores is more subtle than it looks, and the cross-validation procedures that were performed by ~sklearn.model_selection.cross_val_score significantly differ in each case:
- Since
rf_123was passed an integer, every call tofituses the same RNG:
this means that all random characteristics of the random forest estimator will be the same for each of the 5 folds of the CV procedure. In particular, the (randomly chosen) subset of features of the estimator will be the same across all folds.
- Since
rf_instwas passed aRandomStateinstance, each call tofit
starts from a different RNG. As a result, the random subset of features will be different for each fold.
While having a constant estimator RNG across folds isn't inherently wrong, we usually want CV results that are robust w.r.t. the estimator's randomness. As a result, passing an instance instead of an integer may be preferable, since it will allow the estimator RNG to vary for each fold.
Here, ~sklearn.model_selection.cross_val_score will use a non-randomized CV splitter (as is the default), so both estimators will be evaluated on the same splits. This section is not about variability in the splits. Also, whether we pass an integer or an instance to ~sklearn.datasets.make_classification isn't relevant for our illustration purpose: what matters is what we pass to the ~sklearn.ensemble.RandomForestClassifier estimator.
Another subtle side effect of passing RandomState instances is how ~sklearn.base.clone will work::
توجه: >> from sklearn import clone >> from sklearn.ensemble import RandomForestClassifier >> import numpy as np
توجه: >> rng = np.random.RandomState(0) >> a = RandomForestClassifier(random_state=rng) >> b = clone(a)
Since a RandomState instance was passed to a, a and b are not clones in the strict sense, but rather clones in the statistical sense: a and b will still be different models, even when calling fit(X, y) on the same data. Moreover, a and b will influence each other since they share the same internal RNG: calling a.fit will consume b's RNG, and calling b.fit will consume a's RNG, since they are the same. This bit is true for any estimators that share a random_state parameter; it is not specific to clones.
If an integer were passed, a and b would be exact clones and they would not influence each other.
Even though ~sklearn.base.clone is rarely used in user code, it is called pervasively throughout scikit-learn codebase: in particular, most meta-estimators that accept non-fitted estimators call ~sklearn.base.clone internally (~sklearn.model_selection.GridSearchCV, ~sklearn.ensemble.StackingClassifier, ~sklearn.calibration.CalibratedClassifierCV, etc.).
CV splitters ............
When passed a RandomState instance, CV splitters yield different splits each time split is called. When comparing different estimators, this can lead to overestimating the variance of the difference in performance between the estimators::
توجه: >> from sklearn.naive_bayes import GaussianNB >> from sklearn.discriminant_analysis import LinearDiscriminantAnalysis >> from sklearn.datasets import make_classification >> from sklearn.model_selection import KFold >> from sklearn.model_selection import cross_val_score >> import numpy as np
توجه: >> rng = np.random.RandomState(0) >> X, y = make_classification(random_state=rng) >> cv = KFold(shuffle=True, random_state=rng) >> lda = LinearDiscriminantAnalysis() >> nb = GaussianNB()
توجه: >> for est in (lda, nb):
... print(cross_val_score(est, X, y, cv=cv)) [0.8 0.75 0.75 0.7 0.85] [0.85 0.95 0.95 0.85 0.95]
Directly comparing the performance of the ~sklearn.discriminant_analysis.LinearDiscriminantAnalysis estimator vs the ~sklearn.naive_bayes.GaussianNB estimator on each fold would be a mistake: the splits on which the estimators are evaluated are different. Indeed, ~sklearn.model_selection.cross_val_score will internally call cv.split on the same ~sklearn.model_selection.KFold instance, but the splits will be different each time. This is also true for any tool that performs model selection via cross-validation, e.g. ~sklearn.model_selection.GridSearchCV and ~sklearn.model_selection.RandomizedSearchCV: scores are not comparable fold-to-fold across different calls to search.fit, since cv.split would have been called multiple times. Within a single call to search.fit, however, fold-to-fold comparison is possible since the search estimator only calls cv.split once.
For comparable fold-to-fold results in all scenarios, one should pass an integer to the CV splitter: cv = KFold(shuffle=True, random_state=0).
While fold-to-fold comparison is not advisable with RandomState instances, one can however expect that average scores allow to conclude whether one estimator is better than another, as long as enough folds and data are used.
What matters in this example is what was passed to ~sklearn.model_selection.KFold. Whether we pass a RandomState instance or an integer to ~sklearn.datasets.make_classification is not relevant for our illustration purpose. Also, neither ~sklearn.discriminant_analysis.LinearDiscriminantAnalysis nor ~sklearn.naive_bayes.GaussianNB are randomized estimators.
General recommendations
Getting reproducible results across multiple executions .......................................................
In order to obtain reproducible (i.e. constant) results across multiple *program executions*, we need to remove all uses of random_state=None, which is the default. The recommended way is to declare a rng variable at the top of the program, and pass it down to any object that accepts a random_state parameter::
توجه: >> from sklearn.ensemble import RandomForestClassifier >> from sklearn.datasets import make_classification >> from sklearn.model_selection import train_test_split >> import numpy as np
توجه: >> rng = np.random.RandomState(0) >> X, y = make_classification(random_state=rng) >> rf = RandomForestClassifier(random_state=rng) >> X_train, X_test, y_train, y_test = train_test_split(X, y,
... random_state=rng)
توجه: >> rf.fit(X_train, y_train).score(X_test, y_test)
0.84
We are now guaranteed that the result of this script will always be 0.84, no matter how many times we run it. Changing the global rng variable to a different value should affect the results, as expected.
It is also possible to declare the rng variable as an integer. This may however lead to less robust cross-validation results, as we will see in the next section.
We do not recommend setting the global numpy seed by calling np.random.seed(0). See here <https://stackoverflow.com/questions/5836335/consistently-create-same-random-numpy-array/5837352#comment6712034_5837352>_ for a discussion.
Robustness of cross-validation results ......................................
When we evaluate a randomized estimator performance by cross-validation, we want to make sure that the estimator can yield accurate predictions for new data, but we also want to make sure that the estimator is robust w.r.t. its random initialization. For example, we would like the random weights initialization of an ~sklearn.linear_model.SGDClassifier to be consistently good across all folds: otherwise, when we train that estimator on new data, we might get unlucky and the random initialization may lead to bad performance. Similarly, we want a random forest to be robust w.r.t. the set of randomly selected features that each tree will be using.
For these reasons, it is preferable to evaluate the cross-validation performance by letting the estimator use a different RNG on each fold. This is done by passing a RandomState instance (or None) to the estimator initialization.
When we pass an integer, the estimator will use the same RNG on each fold: if the estimator performs well (or bad), as evaluated by CV, it might just be because we got lucky (or unlucky) with that specific seed. Passing instances leads to more robust CV results, and makes the comparison between various algorithms fairer. It also helps limiting the temptation to treat the estimator's RNG as a hyper-parameter that can be tuned.
Whether we pass RandomState instances or integers to CV splitters has no impact on robustness, as long as split is only called once. When split is called multiple times, fold-to-fold comparison isn't possible anymore. As a result, passing integer to CV splitters is usually safer and covers most use-cases.