7.3.Preprocessing data#
Thesklearn.preprocessing package provides several commonutility functions and transformer classes to change raw feature vectorsinto 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(seeImportance of Feature Scaling).If some outliers are present in the set, robust scalers or other transformers canbe more appropriate. The behaviors of the different scalers, transformers, andnormalizers on a dataset containing marginal outliers are highlighted inCompare the effect of different scalers on data with outliers.
7.3.1.Standardization, or mean removal and variance scaling#
Standardization of datasets is acommon requirement for manymachine learning estimators implemented in scikit-learn; they might behavebadly if the individual features do not more or less look like standardnormally distributed data: Gaussian withzero mean and unit variance.
In practice we often ignore the shape of the distribution and justtransform the data to center it by removing the mean value of eachfeature, then scale it by dividing non-constant features by theirstandard deviation.
For instance, many elements used in the objective function ofa learning algorithm (such as the RBF kernel of Support VectorMachines or the l1 and l2 regularizers of linear models) may assume thatall features are centered around zero or have variance in the sameorder. If a feature has a variance that is orders of magnitude largerthan others, it might dominate the objective function and make theestimator unable to learn from other features correctly as expected.
Thepreprocessing module provides theStandardScaler utility class, which is a quick andeasy way to perform the following operation on an array-likedataset:
>>>fromsklearnimportpreprocessing>>>importnumpyasnp>>>X_train=np.array([[1.,-1.,2.],...[2.,0.,0.],...[0.,1.,-1.]])>>>scaler=preprocessing.StandardScaler().fit(X_train)>>>scalerStandardScaler()>>>scaler.mean_array([1., 0., 0.33])>>>scaler.scale_array([0.81, 0.81, 1.24])>>>X_scaled=scaler.transform(X_train)>>>X_scaledarray([[ 0. , -1.22, 1.33 ], [ 1.22, 0. , -0.267], [-1.22, 1.22, -1.06 ]])
Scaled data has zero mean and unit variance:
>>>X_scaled.mean(axis=0)array([0., 0., 0.])>>>X_scaled.std(axis=0)array([1., 1., 1.])
This class implements theTransformer API to compute the mean andstandard deviation on a training set so as to be able to later re-apply thesame transformation on the testing set. This class is hence suitable foruse in the early steps of aPipeline:
>>>fromsklearn.datasetsimportmake_classification>>>fromsklearn.linear_modelimportLogisticRegression>>>fromsklearn.model_selectionimporttrain_test_split>>>fromsklearn.pipelineimportmake_pipeline>>>fromsklearn.preprocessingimportStandardScaler>>>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 dataPipeline(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 eitherpassingwith_mean=False orwith_std=False to the constructorofStandardScaler.
7.3.1.1.Scaling features to a range#
An alternative standardization is scaling features tolie 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 usingMinMaxScaler orMaxAbsScaler,respectively.
The motivation to use this scaling includes robustness to very smallstandard 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_minmaxarray([[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 dataunseen during the fit call: the same scaling and shifting operations will beapplied 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_minmaxarray([[-1.5 , 0. , 1.66666667]])
It is possible to introspect the scaler attributes to find about the exactnature 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])
IfMinMaxScaler is given an explicitfeature_range=(min,max) thefull 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 waythat the training data lies within the range[-1,1] by dividing throughthe largest maximum value in each feature. It is meant for datathat 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_maxabsarray([[ 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_maxabsarray([[-1.5, -1. , 2. ]])>>>max_abs_scaler.scale_array([2., 1., 2.])
7.3.1.2.Scaling sparse data#
Centering sparse data would destroy the sparseness structure in the data, andthus rarely is a sensible thing to do. However, it can make sense to scalesparse inputs, especially if features are on different scales.
MaxAbsScaler was specifically designed for scalingsparse data, and is the recommended way to go about this.However,StandardScaler can acceptscipy.sparsematrices as input, as long aswith_mean=False is explicitly passedto the constructor. Otherwise aValueError will be raised assilently centering would break the sparsity and would often crash theexecution by allocating excessive amounts of memory unintentionally.RobustScaler cannot be fitted to sparse inputs, but you can usethetransform method on sparse inputs.
Note that the scalers accept both Compressed Sparse Rows and CompressedSparse Columns format (seescipy.sparse.csr_matrix andscipy.sparse.csc_matrix). Any other sparse input will beconverted tothe Compressed Sparse Rows representation. To avoid unnecessary memorycopies, it is recommended to choose the CSR or CSC representation upstream.
Finally, if the centered data is expected to be small enough, explicitlyconverting the input to an array using thetoarray method of sparse matricesis another option.
7.3.1.3.Scaling data with outliers#
If your data contains many outliers, scaling using the mean and varianceof the data is likely to not work very well. In these cases, you can useRobustScaler as a drop-in replacement instead. It usesmore robust estimates for the center and range of your data.
References#
Further discussion on the importance of centering and scaling data isavailable on this FAQ:Should I normalize/standardize/rescale the data?
Scaling vs Whitening#
It is sometimes not enough to center and scale the featuresindependently, since a downstream model can further make some assumptionon the linear independence of the features.
To address this issue you can usePCA withwhiten=True to further remove the linear correlation across features.
7.3.1.4.Centering kernel matrices#
If you have a kernel matrix of a kernel\(K\) that computes a dot productin a feature space (possibly implicitly) defined by a function\(\phi(\cdot)\), aKernelCenterer can transform the kernel matrixso 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 apositive semidefinite kernel\(K\).
Mathematical formulation#
We can have a look at the mathematical formulation now that we have theintuition. 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 thefit step.\(K\) is defined by
\(\phi(X)\) is a function mapping of\(X\) to a Hilbert space. Acentered kernel\(\tilde{K}\) is defined as:
where\(\tilde{\phi}(X)\) results from centering\(\phi(X)\) in theHilbert space.
Thus, one could compute\(\tilde{K}\) by mapping\(X\) using thefunction\(\phi(\cdot)\) and center the data in this new space. However,kernels are often used because they allow some algebra calculations thatavoid computing explicitly this mapping using\(\phi(\cdot)\). Indeed, onecan implicitly center as shown in Appendix B in[Scholkopf1998]:
\(1_{\text{n}_{samples}}\) is a matrix of(n_samples,n_samples) whereall entries are equal to\(\frac{1}{\text{n}_{samples}}\). In thetransform step, the kernel becomes\(K_{test}(X, Y)\) defined as:
\(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:
\(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}}\).
References
B. Schölkopf, A. Smola, and K.R. Müller,“Nonlinear component analysis as a kernel eigenvalue problem.”Neural computation 10.5 (1998): 1299-1319.
7.3.2.Non-linear transformation#
Two types of transformations are available: quantile transforms and powertransforms. Both quantile and power transforms are based on monotonictransformations of the features and thus preserve the rank of the valuesalong each feature.
Quantile transforms put all features into the same desired distribution basedon the formula\(G^{-1}(F(X))\) where\(F\) is the cumulativedistribution function of the feature and\(G^{-1}\) thequantile function of thedesired output distribution\(G\). This formula is using the two followingfacts: (i) if\(X\) is a random variable with a continuous cumulativedistribution function\(F\) then\(F(X)\) is uniformly distributed on\([0,1]\); (ii) if\(U\) is a random variable with uniform distributionon\([0,1]\) then\(G^{-1}(U)\) has distribution\(G\). By performinga rank transformation, a quantile transform smooths out unusual distributionsand 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 mapdata from any distribution to as close to a Gaussian distribution.
7.3.2.1.Mapping to a Uniform distribution#
QuantileTransformer provides a non-parametrictransformation to map the data to a uniform distributionwith values between 0 and 1:
>>>fromsklearn.datasetsimportload_iris>>>fromsklearn.model_selectionimporttrain_test_split>>>X,y=load_iris(return_X_y=True)>>>X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0)>>>quantile_transformer=preprocessing.QuantileTransformer(random_state=0)>>>X_train_trans=quantile_transformer.fit_transform(X_train)>>>X_test_trans=quantile_transformer.transform(X_test)>>>np.percentile(X_train[:,0],[0,25,50,75,100])array([ 4.3, 5.1, 5.8, 6.5, 7.9])
This feature corresponds to the sepal length in cm. Once the quantiletransformation is applied, those landmarks approach closely the percentilespreviously defined:
>>>np.percentile(X_train_trans[:,0],[0,25,50,75,100])...array([ 0.00 , 0.24, 0.49, 0.73, 0.99 ])
This can be confirmed on an independent testing set with similar remarks:
>>>np.percentile(X_test[:,0],[0,25,50,75,100])...array([ 4.4 , 5.125, 5.75 , 6.175, 7.3 ])>>>np.percentile(X_test_trans[:,0],[0,25,50,75,100])...array([ 0.01, 0.25, 0.46, 0.60 , 0.94])
7.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 aimto map data from any distribution to as close to a Gaussian distribution aspossible in order to stabilize variance and minimize skewness.
PowerTransformer currently provides two such power transformations,the Yeo-Johnson transform and the Box-Cox transform.
Yeo-Johnson transform#
Box-Cox transform#
Box-Cox can only be applied to strictly positive data. In both methods, thetransformation is parameterized by\(\lambda\), which is determined throughmaximum likelihood estimation. Here is an example of using Box-Cox to mapsamples 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_lognormalarray([[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 thestandardize option toFalse,PowerTransformer will apply zero-mean, unit-variance normalizationto the transformed output by default.
Below are examples of Box-Cox and Yeo-Johnson applied to various probabilitydistributions. Note that when applied to certain distributions, the powertransforms achieve very Gaussian-like results, but with others, they areineffective. This highlights the importance of visualizing the data before andafter transformation.

It is also possible to map data to a normal distribution usingQuantileTransformer by settingoutput_distribution='normal'.Using the earlier example with the iris dataset:
>>>quantile_transformer=preprocessing.QuantileTransformer(...output_distribution='normal',random_state=0)>>>X_trans=quantile_transformer.fit_transform(X)>>>quantile_transformer.quantiles_array([[4.3, 2. , 1. , 0.1], [4.4, 2.2, 1.1, 0.1], [4.4, 2.2, 1.2, 0.1], ..., [7.7, 4.1, 6.7, 2.5], [7.7, 4.2, 6.7, 2.5], [7.9, 4.4, 6.9, 2.5]])
Thus the median of the input becomes the mean of the output, centered at 0. Thenormal output is clipped so that the input’s minimum and maximum —corresponding to the 1e-7 and 1 - 1e-7 quantiles respectively — do notbecome infinite under the transformation.
7.3.3.Normalization#
Normalization is the process ofscaling individual samples to haveunit norm. This process can be useful if you plan to use a quadratic formsuch as the dot-product or any other kernel to quantify the similarityof any pair of samples.
This assumption is the base of theVector Space Model often used in textclassification and clustering contexts.
The functionnormalize provides a quick and easy way to perform thisoperation on a single array-like dataset, either using thel1,l2, ormax norms:
>>>X=[[1.,-1.,2.],...[2.,0.,0.],...[0.,1.,-1.]]>>>X_normalized=preprocessing.normalize(X,norm='l2')>>>X_normalizedarray([[ 0.408, -0.408, 0.812], [ 1. , 0. , 0. ], [ 0. , 0.707, -0.707]])
Thepreprocessing module further provides a utility classNormalizer that implements the same operation using theTransformer API (even though thefit 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 aPipeline:
>>>normalizer=preprocessing.Normalizer().fit(X)# fit does nothing>>>normalizerNormalizer()
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.
Sparse input#
normalize andNormalizer acceptboth dense array-likeand sparse matrices from scipy.sparse as input.
For sparse input the data isconverted to the Compressed Sparse Rowsrepresentation (seescipy.sparse.csr_matrix) before being fed toefficient Cython routines. To avoid unnecessary memory copies, it isrecommended to choose the CSR representation upstream.
7.3.4.Encoding categorical features#
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 theOrdinalEncoder. This estimator transforms each categorical feature to onenew 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 allscikit-learn estimators, as these expect continuous input, and would interpretthe categories as being ordered, which is often not desired (i.e. the set ofbrowsers was ordered arbitrarily).
By default,OrdinalEncoder will also passthrough missing values thatare indicated bynp.nan.
>>>enc=preprocessing.OrdinalEncoder()>>>X=[['male'],['female'],[np.nan],['female']]>>>enc.fit_transform(X)array([[ 1.], [ 0.], [nan], [ 0.]])
OrdinalEncoder provides a parameterencoded_missing_value to encodethe missing values without the need to create a pipeline and usingSimpleImputer.
>>>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:
>>>fromsklearn.pipelineimportPipeline>>>fromsklearn.imputeimportSimpleImputer>>>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 usedwith scikit-learn estimators is to use a one-of-K, also known as one-hot ordummy encoding.This type of encoding can be obtained with theOneHotEncoder,which transforms each categorical feature withn_categories possible values inton_categories binary features, withone 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 automaticallyfrom the dataset and can be found in thecategories_ 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 parametercategories.There are two genders, four possible continents and four web browsers in ourdataset:
>>>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 categoricalfeatures, it can often be better to specifyhandle_unknown='infrequent_if_exist' instead of setting thecategoriesmanually as above. Whenhandle_unknown='infrequent_if_exist' is specifiedand unknown categories are encountered during transform, no error will beraised but the resulting one-hot encoded columns for this feature will be allzeros or considered as an infrequent category if enabled.(handle_unknown='infrequent_if_exist' is only supported for one-hotencoding):
>>>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 inton_categories-1 columnsinstead ofn_categories columns by using thedrop parameter. Thisparameter 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-regularizedregression (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 2categories. In this case, you can set the parameterdrop='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 transformedX, the first column is the encoding of the feature withcategories “male”/”female”, while the remaining 6 columns are the encoding ofthe 2 features with respectively 3 categories each.
Whenhandle_unknown='ignore' anddrop is not None, unknown categories willbe 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 inX_test are unknown during transform and will be mappedto all zeros. This means that unknown categories will have the same mapping asthe dropped category.OneHotEncoder.inverse_transform will map all zerosto the dropped category if a category is dropped andNone if a category isnot 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_transarray([[0., 0., 0., 0., 0., 0., 0.]])>>>drop_enc.inverse_transform(X_trans)array([['female', None, None]], dtype=object)
Support of categorical features with missing values#
OneHotEncoder supports categorical features with missing values byconsidering 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 bothnp.nan andNone, they will be consideredseparate 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.]])
SeeLoading features from dicts for categorical features that arerepresented as a dict, not as scalars.
7.3.4.1.Infrequent categories#
OneHotEncoder andOrdinalEncoder support aggregatinginfrequent categories into a single output for each feature. The parameters toenable the gathering of infrequent categories aremin_frequency andmax_categories.
min_frequencyis either an integer greater or equal to 1, or a float inthe interval(0.0,1.0). Ifmin_frequencyis an integer, categories witha cardinality smaller thanmin_frequencywill be considered infrequent.Ifmin_frequencyis a float, categories with a cardinality smaller thanthis 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. Thisparameter sets an upper limit to the number of output features for eachinput feature.max_categoriesincludes the feature that combinesinfrequent categories.
In the following example withOrdinalEncoder, 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’smax_categories donot take into account missingor unknown categories. Settingunknown_value orencoded_missing_value to aninteger will increase the number of unique integer codes by one each. This canresult in up tomax_categories+2 integer codes. In the following example,“a” and “d” are considered infrequent and grouped together into a singlecategory, “b” and “c” are their own categories, unknown values are encoded as 3and 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 infrequentcategories:
>>>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 willbe 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 infrequentfeature 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 unknowncategory is encountered in transform:
If infrequent category support was not configured or there was noinfrequent category during training, the resulting one-hot encoded columnsfor this feature will be all zeros. In the inverse transform, an unknowncategory will be denoted as
None.If there is an infrequent category during training, the unknown categorywill be considered infrequent. In the inverse transform, ‘infrequent_sklearn’will be used to represent the infrequent category.
Infrequent categories can also be configured usingmax_categories. In thefollowing example, we setmax_categories=2 to limit the number of features inthe output. This will result in all but the'cat' category to be consideredinfrequent, leading to two features, one for'cat' and one for infrequentcategories - 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 bothmax_categories andmin_frequency are non-default values, thencategories are selected based onmin_frequency first andmax_categoriescategories are kept. In the following example,min_frequency=4 considersonlysnake to be infrequent, butmax_categories=3, forcesdog to also beinfrequent:
>>>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 ofmax_categories, then the firstmax_categories are taken based on lexiconordering. In the following example, “b”, “c”, and “d”, have the same cardinalityand withmax_categories=2, “b” and “c” are infrequent because they have a higherlexicon 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)]
7.3.4.2.Target Encoder#
TheTargetEncoder uses the target mean conditioned on the categoricalfeature for encoding unordered categories, i.e. nominal categories[PAR][MIC]. This encoding scheme is useful with categorical features with highcardinality, where one-hot encoding would inflate the feature space making itmore expensive for a downstream model to process. A classical example of highcardinality categories are location based such as zip code or region.
Binary classification targets#
For the binary classification target, the target encoding is given by:
where\(S_i\) is the encoding for category\(i\),\(n_{iY}\) is thenumber of observations with\(Y=1\) and category\(i\),\(n_i\) isthe number of observations with category\(i\),\(n_Y\) is the number ofobservations with\(Y=1\),\(n\) is the number of observations, and\(\lambda_i\) is a shrinkage factor for category\(i\). The shrinkagefactor is given by:
where\(m\) is a smoothing factor, which is controlled with thesmoothparameter inTargetEncoder. Large smoothing factors will put moreweight on the global mean. Whensmooth="auto", the smoothing factor iscomputed as an empirical Bayes estimate:\(m=\sigma_i^2/\tau^2\), where\(\sigma_i^2\) is the variance ofy with category\(i\) and\(\tau^2\) is the global variance ofy.
Multiclass classification targets#
For multiclass classification targets, the formulation is similar to binaryclassification:
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 thenumber of observations, and\(\lambda_i\) is a shrinkage factor for category\(i\).
Continuous targets#
For continuous targets, the formulation is similar to binary classification:
where\(L_i\) is the set of observations with category\(i\) and\(n_i\) is the number of observations with category\(i\).
fit_transform internally relies on across fittingscheme to prevent target information from leaking into the train-timerepresentation, especially for non-informative high-cardinality categoricalvariables, and help prevent the downstream model from overfitting spuriouscorrelations. Note that as a result,fit(X,y).transform(X) does not equalfit_transform(X,y). Infit_transform, the trainingdata is split intok folds (determined by thecv parameter) and each fold isencoded using the encodings learnt using the otherk-1 folds. The followingdiagram shows thecross fitting scheme infit_transform with the defaultcv=5:
fit_transform also learns a ‘full data’ encoding usingthe whole training set. This is never used infit_transform but is saved to the attributeencodings_,for use whentransform is called. Note that the encodingslearned for each fold during thecross fitting scheme are not saved toan attribute.
Thefit method doesnot use anycross fittingschemes and learns one encoding on the entire training set, which is used toencode categories intransform.This encoding is the same as the ‘full data’encoding learned infit_transform.
Note
TargetEncoder considers missing values, such asnp.nan orNone,as another category and encodes them like any other category. Categoriesthat are not seen duringfit are encoded with the target mean, i.e.target_mean_.
Examples
References
7.3.5.Discretization#
Discretization(otherwise known as quantization or binning) provides a way to partition continuousfeatures into discrete values. Certain datasets with continuous featuresmay benefit from discretization, because discretization can transform the datasetof continuous attributes to one with only nominal attributes.
One-hot encoded discretized features can make a model more expressive, whilemaintaining interpretability. For instance, pre-processing with a discretizercan introduce nonlinearity to linear models. For more advanced possibilities,in particular smooth ones, seeGenerating polynomial features furtherbelow.
7.3.5.1.K-bins discretization#
KBinsDiscretizer discretizes features intok 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(SeeEncoding categorical features)and this can be configured with theencode parameter.For each feature, the bin edges are computed duringfit and together withthe number of bins, they will define the intervals. Therefore, for the currentexample, 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)array([[ 0., 1., 1.], [ 1., 1., 1.], [ 2., 0., 0.]])
The resulting dataset contains ordinal attributes which can be further usedin aPipeline.
Discretization is similar to constructing histograms for continuous data.However, histograms focus on counting features which fall into particularbins, whereas discretization focuses on assigning feature values to these bins.
KBinsDiscretizer implements different binning strategies, which can beselected with thestrategy parameter. The ‘uniform’ strategy usesconstant-width bins. The ‘quantile’ strategy uses the quantiles values to haveequally populated bins in each feature. The ‘kmeans’ strategy defines bins basedon a k-means clustering procedure performed on each feature independently.
Be aware that one can specify custom bins by passing a callable defining thediscretization strategy toFunctionTransformer.For instance, we can use the Pandas functionpandas.cut:
>>>importpandasaspd>>>importnumpyasnp>>>fromsklearnimportpreprocessing>>>>>>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, object): ['infant' < 'kid' < 'teen' < 'adult' < 'senior citizen']
Examples
7.3.5.2.Feature binarization#
Feature binarization is the process ofthresholding numericalfeatures to get boolean values. This can be useful for downstreamprobabilistic estimators that make assumption that the input datais distributed according to a multi-variateBernoulli distribution. For instance,this is the case for theBernoulliRBM.
It is also common among the text processing community to use binaryfeature values (probably to simplify the probabilistic reasoning) evenif normalized counts (a.k.a. term frequencies) or TF-IDF valued featuresoften perform slightly better in practice.
As for theNormalizer, the utility classBinarizer is meant to be used in the early stages ofPipeline. Thefit method does nothingas 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>>>binarizerBinarizer()>>>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 theNormalizer class, the preprocessing moduleprovides a companion functionbinarizeto be used when the transformer API is not necessary.
Note that theBinarizer is similar to theKBinsDiscretizerwhenk=2, and when the bin edge is at the valuethreshold.
Sparse input
binarize andBinarizer acceptboth dense array-likeand sparse matrices from scipy.sparse as input.
For sparse input the data isconverted to the Compressed Sparse Rowsrepresentation (seescipy.sparse.csr_matrix).To avoid unnecessary memory copies, it is recommended to choose the CSRrepresentation upstream.
7.3.6.Imputation of missing values#
Tools for imputing missing values are discussed atImputation of missing values.
7.3.7.Generating polynomial features#
Often it’s useful to add complexity to a model by considering nonlinearfeatures of the input data. We show two possibilities that are both based onpolynomials: The first one uses pure polynomials, the second one uses splines,i.e. piecewise polynomials.
7.3.7.1.Polynomial features#
A simple and common method to use is polynomial features, which can getfeatures’ high-order and interaction terms. It is implemented inPolynomialFeatures:
>>>importnumpyasnp>>>fromsklearn.preprocessingimportPolynomialFeatures>>>X=np.arange(6).reshape(3,2)>>>Xarray([[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 canbe gotten with the settinginteraction_only=True:
>>>X=np.arange(9).reshape(3,3)>>>Xarray([[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 inkernel methods (e.g.,SVC,KernelPCA) when using polynomialKernel functions.
SeePolynomial and Spline interpolationfor Ridge regression using created polynomial features.
7.3.7.2.Spline transformer#
Another way to add nonlinear terms instead of pure polynomials of features isto generate spline basis functions for each feature with theSplineTransformer. Splines are piecewise polynomials, parametrized bytheir polynomial degree and the positions of the knots. TheSplineTransformer implements a B-spline basis, cf. the referencesbelow.
Note
TheSplineTransformer treats each feature separately, i.e. itwon’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. Polynomialswould need a higher degree, which leads to the next point.
B-splines do not have oscillatory behaviour at the boundaries as havepolynomials (the higher the degree, the worse). This is known asRunge’sphenomenon.
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 singlefeature, every row contains only
degree+1non-zero elements, whichoccur consecutively and are even positive. This results in a matrix withgood numerical properties, e.g. a low condition number, in sharp contrastto a matrix of polynomials, which goes under the nameVandermonde matrix.A low condition number is important for stable algorithms of linearmodels.
The following code snippet shows splines in action:
>>>importnumpyasnp>>>fromsklearn.preprocessingimportSplineTransformer>>>X=np.arange(5).reshape(5,1)>>>Xarray([[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 theX is sorted, one can easily see the banded matrix output. Only thethree middle diagonals are non-zero fordegree=2. The higher the degree,the more overlapping of the splines.
Interestingly, aSplineTransformer ofdegree=0 is the same asKBinsDiscretizer withencode='onehot-dense' andn_bins=n_knots-1 ifknots=strategy.
Examples
References#
Eilers, P., & Marx, B. (1996).Flexible Smoothing with B-splines andPenalties. Statist. Sci. 11 (1996), no. 2, 89–121.
Perperoglou, A., Sauerbrei, W., Abrahamowicz, M. et al.A review ofspline function procedures in R.BMC Med Res Methodol 19, 46 (2019).
7.3.8.Custom transformers#
Often, you will want to convert an existing Python function into a transformerto assist in data cleaning or processing. You can implement a transformer froman arbitrary function withFunctionTransformer. For example, to builda transformer that applies a log transformation in a pipeline, do:
>>>importnumpyasnp>>>fromsklearn.preprocessingimportFunctionTransformer>>>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 thatfunc andinverse_func are the inverse of each otherby settingcheck_inverse=True and callingfit beforetransform. Please note that a warning is raised and can be turned into anerror with afilterwarnings:
>>>importwarnings>>>warnings.filterwarnings("error",message=".*check_inverse*.",...category=UserWarning,append=False)
For a full code example that demonstrates using aFunctionTransformerto extract features from text data seeColumn Transformer with Heterogeneous Data Sources andTime-related feature engineering.
