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, learning algorithms benefit from standardization of the data set. If
some outliers are present in the set, robust scalers or transformers are 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.

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) assume that
all features are centered around zero and 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 function scale provides a quick and easy way to perform this
operation on a single array-like dataset:

The preprocessing module further provides a utility class
StandardScaler that implements the Transformer API to compute
the mean and standard deviation on a training set so as to be
able to later reapply the same transformation on the testing set.
This class is hence suitable for use in the early steps of a
sklearn.pipeline.Pipeline:

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 include robustness to very small
standard deviations of features and preserving zero entries in sparse data.

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:

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:

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 and maxabs_scale were specifically designed
for scaling sparse data, and are the recommended way to go about this.
However, scale and 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.

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
robust_scale and RobustScaler as drop-in replacements
instead. They use more robust estimates for the center and range of your
data.

If you have a kernel matrix of a kernel \(K\) that computes a dot product
in a feature space defined by function \(phi\),
a KernelCenterer can transform the kernel matrix
so that it contains inner products in the feature space
defined by \(phi\) followed by removal of the mean in that space.

Like scalers, QuantileTransformer puts all features into the same,
known range or distribution. However, by performing a rank transformation, it
smooths out unusual distributions and is less influenced by outliers than
scaling methods. It does, however, distort correlations and distances within
and across features.

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.

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:

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.

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:

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 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 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 or l2
norms:

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).

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.

Often features are not given as continuous values but categorical.
For example a person could have features ["male","female"],
["fromEurope","fromUS","fromAsia"],
["usesFirefox","usesChrome","usesSafari","usesInternetExplorer"].
Such features can be efficiently coded as integers, for instance
["male","fromUS","usesInternetExplorer"] could be expressed as
[0,1,3] while ["female","fromAsia","usesChrome"] 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):

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).

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.

If there is a possibility that the training data might have missing categorical
features, it can often be better to specify handle_unknown='ignore' instead
of setting the categories manually as above. When
handle_unknown='ignore' 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
(handle_unknown='ignore' is only supported for one-hot encoding):

Discretization
(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.

By default the output is one-hot encoded into a sparse matrix
(See Encoding 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:

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.

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. 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.

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.

Often it’s useful to add complexity to the model by considering nonlinear features of the input data. A simple and common method to use is polynomial features, which can get features’ high-order and interaction terms. It is implemented in PolynomialFeatures:

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:

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: