Name already in use
machine-learning-articles / how-to-normalize-or-standardize-a-dataset-in-python.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
1 contributor
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Training a Supervised Machine Learning model involves feeding forward data from a training dataset, through the model, generating predictions. These predictions are then compared with what is known as the ground truth, or the corresponding targets for the training data. Subsequently, the model is improved, by minimizing a cost, error or loss function.
It is important to prepare your dataset before feeding it to your model. When you pass through data without doing so, the model may show some very interesting behavior — and training can become really difficult, if not impossible. In those cases, when inspecting your model code, it could very well be the case that you forgot to apply normalization or standardization. What are they? Why are they necessary? And how do they work? Precisely that is what we will look at in this article.
Firstly, we will take a look at why you need a normalized or standardized dataset. Subsequently, we’ll move forward and see how those techniques actually work. Finally, we give a lot of step-by-step examples by using Scikit-learn and Python for making your dataset ready for Machine Learning models.
Let’s take a look! 🙂
Update 08/Dec/2020: added references to PCA article.
Normalization and Standardization for Feature Scaling
Before studying the what of something, I always think that it helps studying the why first. At least, it makes you understand why you have to apply certain techniques or methods. The same is true for Normalization and Standardization. Why are they necessary? Let’s take a look at this in more detail.
They are required by Machine Learning algorithms
When you are training a Supervised Machine Learning model, you are feeding forward data through the model, generating predictions, and subsequently improving the model. As you read in the introduction, this is achieved by minimizing a cost/error/loss function, and it allows us to optimize models in their unique ways.
For example, a Support Vector Machine is optimized by finding support vectors that support the decision boundary with the greatest margin between two classes, effectively computing a distance metric. Neural networks use gradient descent for optimization, which involves walking down the loss landscape into the direction where loss improves most. And there are many other ways. Now, here are some insights about why datasets must be scaled for Machine Learning algorithms (Wikipedia, 2011):
- Gradient descent converges much faster when the dataset is scaled.
- If the model depends on measuring distance (think SVM), the distances are comparable after the dataset was scaled. In fact, if it is not scaled, computation of the loss can be «governed by this particular feature» if the feature has a really big scale compared to other features (Wikipedia, 2011).
- If you apply regularization, you must also apply scaling, because otherwise some features may be penalized more than strictly necessary.
They help Feature Selection too
Suppose that we given a dataset of a runner’s diary and that our goal is to learn a predictive model between some of the variables and runner performance. What we would normally do in those cases is perform a feature selection procedure, because we cannot simply feed all samples due to two reasons:
- The curse of dimensionality: if we look at our dataset as a feature space with each feature (i.e., column) representing one dimension, our space would be multidimensional if we use many features. The more dimensions we add, the more training data we need; this need increases exponentially. By consequence, although we should use sufficient features, we don’t want to use every one of them.
- We don’t want to use features that contribute insignificantly. Some features (columns) contribute to the output less significantly than others. It could be that when removed, the model will still be able to perform, but at a significantly lower computational cost. We therefore want to be able to select the features that contribute most significantly.
In machine learning problems that involve learning a «state-of-nature» from a finite number of data samples in a high-dimensional feature space with each feature having a range of possible values, typically an enormous amount of training data is required to ensure that there are several samples with each combination of values.
Wikipedia (n.d.) about the curse of dimensionality
We would e.g. apply algorithms such as Principal Component Analysis (PCA) to help us determine which features are most important. If we look at how these algorithms work, we see that e.g. PCA extracts new features based on the principal directions in the dataset, i.e. the directions in your data where variance is largest (Scikit-learn, n.d.).
Variance is the expectation of the squared deviation of a random variable from its mean. Informally, it measures how far a set of numbers is spread out from their average value.
Wikipedia (2001)
Let’s keep this in mind when looking at the following dataset:

Here, the variance of the variable Time offset is larger than that of the variable Distance run.
PCA will therefore naturally select the Time offset variable over the Distance run variable, because the eigenpairs are more significant there.
However, this does not necessarily mean that it is in fact more important — because we cannot compare variance. Only if variance is comparable, and hence the scales are equal in the unit they represent, we can confidently use algorithms like PCA for feature selection. That’s why we must find a way to make our variables comparable.
Introducing Feature Scaling
And, to be speaking most generally, that method is called feature scaling — and it is applied during the data preprocessing step.
Feature scaling is a method used to normalize the range of independent variables or features of data. In data processing, it is also known as data normalization and is generally performed during the data preprocessing step.
Wikipedia (2011)
There are two primary ways for feature scaling which we will cover in the remainder of this article:
- Rescaling, or min-max normalization: we scale the data into one of two ranges: [latex][0, 1][/latex] or [latex][a, b][/latex], often [latex][-1, 1][/latex].
- Standardization, or Z-score normalization: we scale the data so that the mean is zero and variance is 1.
Let’s now cover each of the three methods in more detail, find out how they work, and identify when they are used best.
Rescaling (min-max normalization)
Rescaling, or min-max normalization, is a simple method for bringing your data into one out of two ranges: [latex][0, 1][/latex] or [latex][a, b][/latex]. It highly involves the minimum and maximum values from the dataset in normalizing the data.
How it works — the [0, 1] way
Suppose that we have the following array:
Min-max normalization for the range [latex][0, 1][/latex] can be defined as follows:
In a naïve way, using Numpy, we can therefore normalize our data into the [latex][0, 1][/latex] range in the following way:
This indeed yields an array where the lowest value is now 0.0 and the biggest is 1.0 :
How it works — the [a, b] way
If instead we wanted to scale it to some other arbitrary range — say [latex][0, 1.5][/latex], we can apply min-max normalization but then for the [latex][a, b][/latex] range, where [latex]a[/latex] and [latex]b[/latex] can be chosen yourself.
We can use the following formula for normalization:
Or, for the dataset from the previous section, using a naïve Python implementation:
Applying the MinMaxScaler from Scikit-learn
Scikit-learn, the popular machine learning library used frequently for training many traditional Machine Learning algorithms provides a module called MinMaxScaler , and it is part of the sklearn.preprocessing API.
It allows us to fit a scaler with a predefined range to our dataset, and subsequently perform a transformation for the data. The code below gives an example of how to use it.
- We import numpy as a whole and the MinMaxScaler from sklearn.preprocessing .
- We define the NumPy array that we just defined before, but now, we have to reshape it: .reshape(-1, 1) . This is a Scikit-learn requirement for arrays with just one feature per array item (which in our case is true, because we are using scalar values).
- We then initialize the MinMaxScaler and here we also specify our [latex][a, b][/latex] range: feature_range=(0, 1.5) . Of course, as [latex][0, 1][/latex] is also an [latex][a, b][/latex] range, we can implement that one as well using MinMaxScaler .
- We then fit the data to our scaler, using scaler.fit(dataset) . This way, it becomes capable of transforming datasets.
- We finally transform the dataset using scaler.transform(dataset) and print the result.
And indeed, after printing, we can see that the outcome is the same as obtained with our naïve approach:
Standardization (Z-scale normalization)
In the previous example, we normalized our dataset based on the minimum and maximum values. Mean and standard deviation are however not standard, meaning that the mean is zero and that the standard deviation is one.
Because the bounds of our normalizations would not be equal, it would still be (slightly) unfair to compare the outcomes e.g. with PCA.
For example, if we used a different dataset, our results would be different:
This is where standardization or Z-score normalization comes into the picture. Rather than using the minimum and maximum values, we use the mean and standard deviation from the data. By consequence, all our features will now have zero mean and unit variance, meaning that we can now compare the variances between the features.
The formula for standardization is as follows:
In other words, for each sample from the dataset, we subtract the mean and divide by the standard deviation. By removing the mean from each sample, we effectively move the samples towards a mean of 0 (after all, we removed it from all samples). In addition, by dividing by the standard deviation, we yield a dataset where the values describe by how much of the standard deviation they are offset from the mean.
This can also be implemented with Python:
In Scikit-learn, the sklearn.preprocessing module provides the StandardScaler which helps us perform the same action in an efficient way.
With as outcome:
We see that the mean is really close to 0 ([latex]3.17 \times 10^<-17>[/latex]) and that standard deviation is one.
Normalization vs Standardization: when to use which one?
Many people have the question when to use normalization, and when to use standardization? This is a valid question — and I had it as well.
Most generally, the rule of thumb would be to use min-max normalization if you want to normalize the data while keeping some differences in scales (because units remain different), and use standardization if you want to make scales comparable (through standard deviations).
The example below illustrates the effects of standardization. In it, we create Gaussian data, stretch one of the axes with some value to make them relatively incomparable, and plot the data. This clearly indicates the stretched blobs in an absolute sense. Then, we use standardization and plot the data again. We now see that both the mean has moved to [latex](0, 0)[/latex] and that when the data is standardized, the variance of the axes is pretty similar!
If we hadn’t applied feature scaling here, algorithms like PCA would have pretty much fooled us. 😉


In this article, we looked at Feature Scaling for Machine Learning. More specifically, we looked at Normalization (min-max normalization) which brings the dataset into the [latex][a, b][/latex] range. In addition to Normalization, we also looked at Standardization, which allows us to convert the scales into amounts of standard deviation, making the axes comparable for e.g. algorithms like PCA.
We illustrated our reasoning with step-by-step Python examples, including some with standard Scikit-learn functionality.
I hope that you have learned something from this article! If you did, feel free to leave a message in the comments section Please do the same if you have questions or other comments. I’d love to hear from you! Thank you for reading MachineCurve today and happy engineering
6.3. 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, 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 .
6.3.1. 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 preprocessing module provides the StandardScaler utility class, which is a quick and easy way to perform the following operation on an array-like dataset:
Scaled data has zero mean and unit variance:
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 :
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¶
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.
Here is an example to scale a toy data matrix to the [0, 1] range:
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:
It is possible to introspect the scaler attributes to find about the exact nature of the transformation learned on the training data:
If MinMaxScaler is given an explicit feature_range=(min, max) the full formula is:
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:
6.3.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.
6.3.1.3. 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?
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¶
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\) .
Mathematical formulation
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
\(\phi(X)\) is a function mapping of \(X\) to a Hilbert space. A centered kernel \(\tilde
where \(\tilde<\phi>(X)\) results from centering \(\phi(X)\) in the Hilbert space.
Thus, one could compute \(\tilde
\(1_<\text
\(Y\) is the test dataset of shape (n_samples_test, n_features) and thus \(K_
\(1’_<\text
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¶
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 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.
6.3.2.1. 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:
This feature corresponds to the sepal length in cm. Once the quantile transformation applied, those landmarks approach closely the percentiles previously defined:
This can be confirmed on a independent testing set with similar remarks:
6.3.2.2. 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.
The Yeo-Johnson transform is given by:
while the Box-Cox transform is given by:
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.
6.3.3. 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 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:
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 Pipeline :
The normalizer instance can then be used on sample vectors as any transformer:
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.
6.3.4. 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):
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 .
OrdinalEncoder provides a parameter encoded_missing_value to encode the missing values without the need to create a pipeline and using SimpleImputer .
The above processing is equivalent to the following pipeline:
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:
By default, the values each feature can take is inferred automatically from the dataset and can be found in the categories_ attribute:
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:
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):
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:
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’ .
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.
When handle_unknown=’ignore’ and drop is not None, unknown categories will be encoded as all zeros:
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:
OneHotEncoder supports categorical features with missing values by considering the missing values as an additional category:
If a feature contains both np.nan and None , they will be considered separate categories:
See Loading features from dicts for categorical features that are represented as a dict, not as scalars.
6.3.4.1. Infrequent categories¶
OneHotEncoder supports 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) . 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_categories is either None 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.
In the following example, the categories, ‘dog’, ‘snake’ are considered infrequent:
By setting handle_unknown to ‘infrequent_if_exist’ , unknown categories will be considered infrequent:
OneHotEncoder.get_feature_names_out uses ‘infrequent’ as the infrequent feature name:
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:
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:
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.
6.3.5. Discretization¶
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. For more advanced possibilities, in particular smooth ones, see Generating polynomial features further below.
6.3.5.1. K-bins discretization¶
KBinsDiscretizer discretizes features into k bins:
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:
-
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:
The resulting dataset contains ordinal attributes which can be further used in a 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 FunctionTransformer . For instance, we can use the Pandas function pandas.cut :
6.3.5.2. 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. For instance, this is the case for the 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 Pipeline . The fit method does nothing as each sample is treated independently of others:
It is possible to adjust the threshold of the binarizer:
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.
6.3.6. Imputation of missing values¶
Tools for imputing missing values are discussed at Imputation of missing values .
6.3.7. 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.
6.3.7.1. 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 :
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 :
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 (e.g., SVC , KernelPCA ) when using polynomial Kernel functions .
See Polynomial and Spline interpolation for Ridge regression using created polynomial features.
6.3.7.2. 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.
-
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. A low condition number is important for stable algorithms of linear models.
The following code snippet shows splines in action:
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 KBinsDiscretizer with encode=’onehot-dense’ and n_bins = n_knots — 1 if knots = strategy .
Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al. A review of spline function procedures in R. BMC Med Res Methodol 19, 46 (2019).
6.3.8. 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:
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 :
For a full code example that demonstrates using a FunctionTransformer to extract features from text data see Column Transformer with Heterogeneous Data Sources and Time-related feature engineering .
Функция StandardScaler() в Python
В этой статье мы сосредоточимся на одном из наиболее важных методов предварительной обработки в Python – стандартизации с использованием функции StandardScaler().
Необходимость стандартизации
Прежде чем перейти к стандартизации, давайте сначала разберемся с концепцией масштабирования.
Масштабирование функций – важный шаг в моделировании алгоритмов с помощью наборов данных. Данные, которые обычно используются для моделирования, получают с помощью различных средств, таких как:
- опросный лист;
- обзоры;
- исследование;
- очистка и др.
Итак, полученные данные содержат в совокупности признаки разного размера и масштаба. Различные масштабы функций данных отрицательно влияют на моделирование набора данных.
Это приводит к предвзятому результату прогнозов с точки зрения ошибок классификации и показателей точности. Таким образом, перед моделированием необходимо масштабировать данные.
Вот тут-то и появляется стандартизация.
Стандартизация – это метод масштабирования, при котором данные не масштабируются путем преобразования статистического распределения данных в следующий формат:
- среднее – 0 (ноль);
- стандартное отклонение – 1.

Таким образом, весь набор данных масштабируется вместе с нулевым значением и единичной дисперсией.
Давайте теперь попробуем реализовать концепцию стандартизации в следующих разделах.
Библиотека sklearn
Библиотека sklearn в Python предлагает нам функцию StandardScaler() для стандартизации значений данных в стандартный формат.
Согласно приведенному выше синтаксису мы изначально создаем объект функции StandardScaler(). Кроме того, мы используем fit_transform() вместе с назначенным объектом для преобразования данных и их стандартизации.
Примечание. Стандартизация применима только к значениям данных, которые соответствуют нормальному распределению.
2 Простые способы стандартизации данных в Python для машинного обучения
Эй, читатели. В этой статье мы будем сосредоточиться на 2 важных методах стандартизации данных в Python. Итак, давайте начнем !!
- Автор записи
2 Простые способы стандартизации данных в Python для машинного обучения
Эй, читатели. В этой статье мы будем сосредоточиться на 2 Важных методика для стандартизации данных в Python Отказ Итак, давайте начнем !!
Почему нам нужно стандартизировать данные в Python?
Перед погружением глубоко в концепцию стандартизации, для нас очень важно знать необходимость в этом.
Итак, вы видите, что наборы данных, которые мы используем для создания модели для определенного оператора проблемы, обычно построены из различных источников. Таким образом, можно предположить, что набор данных содержит переменные/особенности разных масштабов.
Для того, чтобы наше машинное обучение или глубокую модель обучения работать хорошо, данные очень необходимо иметь одинаковую масштаб с точки зрения функции, чтобы избежать смещения в результате.
Таким образом, Функция масштабирования считается важным шагом до моделирования.
Масштабирование функций может быть широко классифицировано на следующих категориях:
- Нормализация
- Стандартизация
Стандартизация используется на значениях данных, которые являются нормально распределен Отказ Кроме того, применяя стандартизацию, мы склонны вносить среднее значение набора данных, а стандартное отклонение, эквивалентное 1.
То есть путем стандартизации значений мы получаем следующую статистику распределения данных
- иметь в виду
- стандартный
Таким образом, этим набор данных становится самоснабжением и легко анализировать как значит отказывается до 0 И это происходит, чтобы иметь Устройство дисперсии Отказ
Способы стандартизации данных в Python
Давайте сейчас сосредоточимся на различных способах внедрения стандартизации в предстоящем разделе.
1. Использование предварительной обработки. Функция ()
Предварительная обработка. Функция (данные). Может использоваться для стандартизации значений данных к значению, имеющему средне эквивалентное нулю и стандартное отклонение как 1.
Здесь мы загрузили DataSet Iris в окружающую среду, используя линию ниже:
Кроме того, мы сохранили набор данных IRIS к объекту данных, как создано ниже.
После сегрегирования зависимого и переменной/целевой переменной мы использовали Предварительная обработка. Функция ()) Функция в зависимых переменных для стандартизации данных.
2. Использование стандартного баланса () функции
Python Библиотека Sklearn предлагает нам Стандартный класс () Функция выполнять стандартизацию на набор данных.
Здесь, опять же мы использовали набор данных IRIS.
Кроме того, мы создали объект стандартного баланса (), а затем применил fit_transform () Функция Чтобы применить стандартизацию на набор данных.
Выход :
Заключение
По этому, мы подошли к концу этой темы. Не стесняйтесь комментировать ниже, если вы столкнетесь с любым вопросом.