Pipeline of transforms with a final estimator.
Sequentially apply a list of transforms and a final estimator. Intermediate steps of the pipeline must be ‘transforms’, that is, they must implement fit and transform methods. The final estimator only needs to implement fit. The transformers in the pipeline can be cached using memory argument.
The purpose of the pipeline is to assemble several steps that can be cross-validated together while setting different parameters. For this, it enables setting parameters of the various steps using their names and the parameter name separated by a ‘__’, as in the example below. A step’s estimator may be replaced entirely by setting the parameter with its name to another estimator, or a transformer removed by setting it to ‘passthrough’ or None.
Read more in the User Guide.
New in version 0.5.
List of (name, transform) tuples (implementing fit/transform) that are chained, in the order in which they are chained, with the last object an estimator.
Used to cache the fitted transformers of the pipeline. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. Use the attribute named_steps or steps to inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming.
If True, the time elapsed while fitting each step will be printed as it is completed.
Dictionary-like object, with the following attributes. Read-only attribute to access any step parameter by user given name. Keys are step names and values are steps parameters.
See also
Convenience function for simplified pipeline construction.
decision_function(X)
Apply transforms, and decision_function of the final estimator
fit(X[, y])
Fit the model
fit_predict(X[, y])
Applies fit_predict of last step in pipeline after transforms.
fit_transform(X[, y])
Fit the model and transform with the final estimator
get_params([deep])
Get parameters for this estimator.
predict(X, **predict_params)
Apply transforms to the data, and predict with the final estimator
predict_log_proba(X)
Apply transforms, and predict_log_proba of the final estimator
predict_proba(X)
Apply transforms, and predict_proba of the final estimator
score(X[, y, sample_weight])
Apply transforms, and score with the final estimator
score_samples(X)
Apply transforms, and score_samples of the final estimator.
set_params(**kwargs)
Set the parameters of this estimator.
Apply transforms, and decision_function of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Fit the model
Fit all the transforms one after the other and transform the data, then fit the transformed data using the final estimator.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.
This estimator
Applies fit_predict of last step in pipeline after transforms.
Applies fit_transforms of a pipeline to the data, followed by the fit_predict method of the final estimator in the pipeline. Valid only if the final estimator implements fit_predict.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.
Fit the model and transform with the final estimator
Fits all the transforms one after the other and transforms the data, then uses fit_transform on transformed data with the final estimator.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.
Transformed samples
Get parameters for this estimator.
Returns the parameters given in the constructor as well as the estimators contained within the steps of the Pipeline.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Apply inverse transformations in reverse order
All estimators in the pipeline must support inverse_transform.
Data samples, where n_samples is the number of samples and n_features is the number of features. Must fulfill input requirements of last step of pipeline’s inverse_transform method.
Apply transforms to the data, and predict with the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Parameters to the predict called at the end of all transformations in the pipeline. Note that while this may be used to return uncertainties from some models with return_std or return_cov, uncertainties that are generated by the transformations in the pipeline are not propagated to the final estimator.
New in version 0.20.
Apply transforms, and predict_log_proba of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Apply transforms, and predict_proba of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Apply transforms, and score with the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Targets used for scoring. Must fulfill label requirements for all steps of the pipeline.
If not None, this argument is passed as sample_weight keyword argument to the score method of the final estimator.
Apply transforms, and score_samples of the final estimator.
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Set the parameters of this estimator.
Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in steps.
Apply transforms, and transform with the final estimator
This also works where final estimator is None: all prior transformations are applied.
Data to transform. Must fulfill input requirements of first step of the pipeline.


Pipeline of transforms with a final estimator.
Sequentially apply a list of transforms and a final estimator. Intermediate steps of the pipeline must be ‘transforms’, that is, they must implement fit and transform methods. The final estimator only needs to implement fit. The transformers in the pipeline can be cached using memory argument.
The purpose of the pipeline is to assemble several steps that can be cross-validated together while setting different parameters. For this, it enables setting parameters of the various steps using their names and the parameter name separated by a ‘__’, as in the example below. A step’s estimator may be replaced entirely by setting the parameter with its name to another estimator, or a transformer removed by setting it to ‘passthrough’ or None.
Read more in the User Guide.
New in version 0.5.
List of (name, transform) tuples (implementing fit/transform) that are chained, in the order in which they are chained, with the last object an estimator.
Used to cache the fitted transformers of the pipeline. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. Use the attribute named_steps or steps to inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming.
If True, the time elapsed while fitting each step will be printed as it is completed.
Dictionary-like object, with the following attributes. Read-only attribute to access any step parameter by user given name. Keys are step names and values are steps parameters.
See also
Convenience function for simplified pipeline construction.
decision_function(X)
Apply transforms, and decision_function of the final estimator
fit(X[, y])
Fit the model
fit_predict(X[, y])
Applies fit_predict of last step in pipeline after transforms.
fit_transform(X[, y])
Fit the model and transform with the final estimator
get_params([deep])
Get parameters for this estimator.
predict(X, **predict_params)
Apply transforms to the data, and predict with the final estimator
predict_log_proba(X)
Apply transforms, and predict_log_proba of the final estimator
predict_proba(X)
Apply transforms, and predict_proba of the final estimator
score(X[, y, sample_weight])
Apply transforms, and score with the final estimator
score_samples(X)
Apply transforms, and score_samples of the final estimator.
set_params(**kwargs)
Set the parameters of this estimator.
Apply transforms, and decision_function of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Fit the model
Fit all the transforms one after the other and transform the data, then fit the transformed data using the final estimator.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.
This estimator
Applies fit_predict of last step in pipeline after transforms.
Applies fit_transforms of a pipeline to the data, followed by the fit_predict method of the final estimator in the pipeline. Valid only if the final estimator implements fit_predict.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.
Fit the model and transform with the final estimator
Fits all the transforms one after the other and transforms the data, then uses fit_transform on transformed data with the final estimator.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.
Transformed samples
Get parameters for this estimator.
Returns the parameters given in the constructor as well as the estimators contained within the steps of the Pipeline.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Apply inverse transformations in reverse order
All estimators in the pipeline must support inverse_transform.
Data samples, where n_samples is the number of samples and n_features is the number of features. Must fulfill input requirements of last step of pipeline’s inverse_transform method.
Apply transforms to the data, and predict with the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Parameters to the predict called at the end of all transformations in the pipeline. Note that while this may be used to return uncertainties from some models with return_std or return_cov, uncertainties that are generated by the transformations in the pipeline are not propagated to the final estimator.
New in version 0.20.
Apply transforms, and predict_log_proba of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Apply transforms, and predict_proba of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Apply transforms, and score with the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Targets used for scoring. Must fulfill label requirements for all steps of the pipeline.
If not None, this argument is passed as sample_weight keyword argument to the score method of the final estimator.
Apply transforms, and score_samples of the final estimator.
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Set the parameters of this estimator.
Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in steps.
Apply transforms, and transform with the final estimator
This also works where final estimator is None: all prior transformations are applied.
Data to transform. Must fulfill input requirements of first step of the pipeline.
Feature agglomeration vs. univariate selection
Poisson regression and non-normal loss
Permutation Importance vs Random Forest Feature Importance (MDI)
Scalable learning with polynomial kernel aproximation
Explicit feature map approximation for RBF kernels
Underfitting vs. Overfitting
Sample pipeline for text feature extraction and evaluation
Balance model complexity and cross-validated score
Caching nearest neighbors
Comparing Nearest Neighbors with and without Neighborhood Components Analysis
Restricted Boltzmann Machine features for digit classification
Concatenating multiple feature extraction methods
Pipelining: chaining a PCA and a logistic regression
Selecting dimensionality reduction with Pipeline and GridSearchCV
Column Transformer with Mixed Types
Column Transformer with Heterogeneous Data Sources
Semi-supervised Classification on a Text Dataset
SVM-Anova: SVM with univariate feature selection
Classification of text documents using sparse features


Apply transforms, and decision_function of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.


Fit the model
Fit all the transforms one after the other and transform the data, then fit the transformed data using the final estimator.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.
This estimator


Applies fit_predict of last step in pipeline after transforms.
Applies fit_transforms of a pipeline to the data, followed by the fit_predict method of the final estimator in the pipeline. Valid only if the final estimator implements fit_predict.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.


Fit the model and transform with the final estimator
Fits all the transforms one after the other and transforms the data, then uses fit_transform on transformed data with the final estimator.
Training data. Must fulfill input requirements of first step of the pipeline.
Training targets. Must fulfill label requirements for all steps of the pipeline.
Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.
Transformed samples


Get parameters for this estimator.
Returns the parameters given in the constructor as well as the estimators contained within the steps of the Pipeline.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Apply inverse transformations in reverse order
All estimators in the pipeline must support inverse_transform.
Data samples, where n_samples is the number of samples and n_features is the number of features. Must fulfill input requirements of last step of pipeline’s inverse_transform method.


Apply transforms to the data, and predict with the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Parameters to the predict called at the end of all transformations in the pipeline. Note that while this may be used to return uncertainties from some models with return_std or return_cov, uncertainties that are generated by the transformations in the pipeline are not propagated to the final estimator.
New in version 0.20.


Apply transforms, and predict_log_proba of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.


Apply transforms, and predict_proba of the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.


Apply transforms, and score with the final estimator
Data to predict on. Must fulfill input requirements of first step of the pipeline.
Targets used for scoring. Must fulfill label requirements for all steps of the pipeline.
If not None, this argument is passed as sample_weight keyword argument to the score method of the final estimator.


Apply transforms, and score_samples of the final estimator.
Data to predict on. Must fulfill input requirements of first step of the pipeline.


Set the parameters of this estimator.
Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in steps.


Apply transforms, and transform with the final estimator
This also works where final estimator is None: all prior transformations are applied.
Data to transform. Must fulfill input requirements of first step of the pipeline.


Augment dataset with an additional dummy feature.
This is useful for fitting an intercept term with implementations which cannot otherwise fit it directly.
Data.
Value to use for the dummy feature.
Same data with dummy feature added as first column.


Boolean thresholding of array-like or scipy.sparse matrix.
Read more in the User Guide.
The data to binarize, element by element. scipy.sparse matrices should be in CSR or CSC format to avoid an un-necessary copy.
Feature values below or equal to this are replaced by 0, above it by 1. Threshold may not be less than 0 for operations on sparse matrices.
set to False to perform inplace binarization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR / CSC matrix and if axis is 1).
The transformed data.
See also
Performs binarization using the Transformer API (e.g. as part of a preprocessing Pipeline).


Binarize data (set feature values to 0 or 1) according to a threshold.
Values greater than the threshold map to 1, while values less than or equal to the threshold map to 0. With the default threshold of 0, only positive values map to 1.
Binarization is a common operation on text count data where the analyst can decide to only consider the presence or absence of a feature rather than a quantified number of occurrences for instance.
It can also be used as a pre-processing step for estimators that consider boolean random variables (e.g. modelled using the Bernoulli distribution in a Bayesian setting).
Read more in the User Guide.
Feature values below or equal to this are replaced by 0, above it by 1. Threshold may not be less than 0 for operations on sparse matrices.
set to False to perform inplace binarization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix).
See also
Equivalent function without the estimator API.
If the input is a sparse matrix, only the non-zero values are subject to update by the Binarizer class.
This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline.
fit(X[, y])
Do nothing and return the estimator unchanged.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
set_params(**params)
Set the parameters of this estimator.
transform(X[, copy])
Binarize each element of X.
Do nothing and return the estimator unchanged.
This method is just there to implement the usual API and hence work in pipelines.
The data.
Ignored.
Fitted transformer.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Binarize each element of X.
The data to binarize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
Copy the input X or not.
Transformed array.


Do nothing and return the estimator unchanged.
This method is just there to implement the usual API and hence work in pipelines.
The data.
Ignored.
Fitted transformer.


Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Binarize each element of X.
The data to binarize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
Copy the input X or not.
Transformed array.


Constructs a transformer from an arbitrary callable.
A FunctionTransformer forwards its X (and optionally y) arguments to a user-defined function or function object and returns the result of this function. This is useful for stateless transformations such as taking the log of frequencies, doing custom scaling, etc.
Note: If a lambda is used as the function, then the resulting transformer will not be pickleable.
New in version 0.17.
Read more in the User Guide.
The callable to use for the transformation. This will be passed the same arguments as transform, with args and kwargs forwarded. If func is None, then func will be the identity function.
The callable to use for the inverse transformation. This will be passed the same arguments as inverse transform, with args and kwargs forwarded. If inverse_func is None, then inverse_func will be the identity function.
Indicate that the input X array should be checked before calling func. The possibilities are:
Changed in version 0.22: The default of validate changed from True to False.
Indicate that func accepts a sparse matrix as input. If validate is False, this has no effect. Otherwise, if accept_sparse is false, sparse matrix inputs will cause an exception to be raised.
Whether to check that or func followed by inverse_func leads to the original inputs. It can be used for a sanity check, raising a warning when the condition is not fulfilled.
New in version 0.20.
Dictionary of additional keyword arguments to pass to func.
New in version 0.18.
Dictionary of additional keyword arguments to pass to inverse_func.
New in version 0.18.
fit(X[, y])
Fit transformer by checking X.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Transform X using the inverse function.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Transform X using the forward function.
Fit transformer by checking X.
If validate is True, X will be checked.
Input array.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Transform X using the inverse function.
Input array.
Transformed input.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform X using the forward function.
Input array.
Transformed input.


Constructs a transformer from an arbitrary callable.
A FunctionTransformer forwards its X (and optionally y) arguments to a user-defined function or function object and returns the result of this function. This is useful for stateless transformations such as taking the log of frequencies, doing custom scaling, etc.
Note: If a lambda is used as the function, then the resulting transformer will not be pickleable.
New in version 0.17.
Read more in the User Guide.
The callable to use for the transformation. This will be passed the same arguments as transform, with args and kwargs forwarded. If func is None, then func will be the identity function.
The callable to use for the inverse transformation. This will be passed the same arguments as inverse transform, with args and kwargs forwarded. If inverse_func is None, then inverse_func will be the identity function.
Indicate that the input X array should be checked before calling func. The possibilities are:
Changed in version 0.22: The default of validate changed from True to False.
Indicate that func accepts a sparse matrix as input. If validate is False, this has no effect. Otherwise, if accept_sparse is false, sparse matrix inputs will cause an exception to be raised.
Whether to check that or func followed by inverse_func leads to the original inputs. It can be used for a sanity check, raising a warning when the condition is not fulfilled.
New in version 0.20.
Dictionary of additional keyword arguments to pass to func.
New in version 0.18.
Dictionary of additional keyword arguments to pass to inverse_func.
New in version 0.18.
fit(X[, y])
Fit transformer by checking X.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Transform X using the inverse function.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Transform X using the forward function.
Fit transformer by checking X.
If validate is True, X will be checked.
Input array.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Transform X using the inverse function.
Input array.
Transformed input.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform X using the forward function.
Input array.
Transformed input.
Poisson regression and non-normal loss
Tweedie regression on insurance claims
Column Transformer with Heterogeneous Data Sources
Semi-supervised Classification on a Text Dataset


Fit transformer by checking X.
If validate is True, X will be checked.
Input array.


Transform X using the inverse function.
Input array.
Transformed input.


Transform X using the forward function.
Input array.
Transformed input.


Bin continuous data into intervals.
Read more in the User Guide.
New in version 0.20.
The number of bins to produce. Raises ValueError if n_bins < 2.
Method used to encode the transformed result.
Encode the transformed result with one-hot encoding and return a sparse matrix. Ignored features are always stacked to the right.
Encode the transformed result with one-hot encoding and return a dense array. Ignored features are always stacked to the right.
Return the bin identifier encoded as an integer value.
Strategy used to define the widths of the bins.
All bins in each feature have identical widths.
All bins in each feature have the same number of points.
Values in each bin have the same nearest center of a 1D k-means cluster.
The desired data-type for the output. If None, output dtype is consistent with input dtype. Only np.float32 and np.float64 are supported.
New in version 0.24.
Number of bins per feature. Bins whose width are too small (i.e., <= 1e-8) are removed with a warning.
The edges of each bin. Contain arrays of varying shapes (n_bins_, ) Ignored features will have empty arrays.
See also
Class used to bin values as 0 or 1 based on a parameter threshold.
In bin edges for feature i, the first and last values are used only for inverse_transform. During transform, bin edges are extended to:
You can combine KBinsDiscretizer with ColumnTransformer if you only want to preprocess part of the features.
KBinsDiscretizer might produce constant features (e.g., when encode = 'onehot' and certain bins do not contain any data). These features can be removed with feature selection algorithms (e.g., VarianceThreshold).
Sometimes it may be useful to convert the data back into the original feature space. The inverse_transform function converts the binned data into the original feature space. Each value will be equal to the mean of the two bin edges.
fit(X[, y])
Fit the estimator.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(Xt)
Transform discretized data back to original feature space.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Discretize the data.
Fit the estimator.
Data to be discretized.
Ignored. This parameter exists only for compatibility with Pipeline.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Transform discretized data back to original feature space.
Note that this function does not regenerate the original data due to discretization rounding.
Transformed data in the binned space.
Data in the original feature space.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Discretize the data.
Data to be discretized.
Data in the binned space. Will be a sparse matrix if self.encode='onehot' and ndarray otherwise.


Bin continuous data into intervals.
Read more in the User Guide.
New in version 0.20.
The number of bins to produce. Raises ValueError if n_bins < 2.
Method used to encode the transformed result.
Encode the transformed result with one-hot encoding and return a sparse matrix. Ignored features are always stacked to the right.
Encode the transformed result with one-hot encoding and return a dense array. Ignored features are always stacked to the right.
Return the bin identifier encoded as an integer value.
Strategy used to define the widths of the bins.
All bins in each feature have identical widths.
All bins in each feature have the same number of points.
Values in each bin have the same nearest center of a 1D k-means cluster.
The desired data-type for the output. If None, output dtype is consistent with input dtype. Only np.float32 and np.float64 are supported.
New in version 0.24.
Number of bins per feature. Bins whose width are too small (i.e., <= 1e-8) are removed with a warning.
The edges of each bin. Contain arrays of varying shapes (n_bins_, ) Ignored features will have empty arrays.
See also
Class used to bin values as 0 or 1 based on a parameter threshold.
In bin edges for feature i, the first and last values are used only for inverse_transform. During transform, bin edges are extended to:
You can combine KBinsDiscretizer with ColumnTransformer if you only want to preprocess part of the features.
KBinsDiscretizer might produce constant features (e.g., when encode = 'onehot' and certain bins do not contain any data). These features can be removed with feature selection algorithms (e.g., VarianceThreshold).
Sometimes it may be useful to convert the data back into the original feature space. The inverse_transform function converts the binned data into the original feature space. Each value will be equal to the mean of the two bin edges.
fit(X[, y])
Fit the estimator.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(Xt)
Transform discretized data back to original feature space.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Discretize the data.
Fit the estimator.
Data to be discretized.
Ignored. This parameter exists only for compatibility with Pipeline.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Transform discretized data back to original feature space.
Note that this function does not regenerate the original data due to discretization rounding.
Transformed data in the binned space.
Data in the original feature space.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Discretize the data.
Data to be discretized.
Data in the binned space. Will be a sparse matrix if self.encode='onehot' and ndarray otherwise.
Poisson regression and non-normal loss
Tweedie regression on insurance claims
Using KBinsDiscretizer to discretize continuous features
Demonstrating the different strategies of KBinsDiscretizer
Feature discretization


Fit the estimator.
Data to be discretized.
Ignored. This parameter exists only for compatibility with Pipeline.


Transform discretized data back to original feature space.
Note that this function does not regenerate the original data due to discretization rounding.
Transformed data in the binned space.
Data in the original feature space.


Discretize the data.
Data to be discretized.
Data in the binned space. Will be a sparse matrix if self.encode='onehot' and ndarray otherwise.


Center a kernel matrix.
Let K(x, z) be a kernel defined by phi(x)^T phi(z), where phi is a function mapping x to a Hilbert space. KernelCenterer centers (i.e., normalize to have zero mean) the data without explicitly computing phi(x). It is equivalent to centering phi(x) with sklearn.preprocessing.StandardScaler(with_std=False).
Read more in the User Guide.
Average of each column of kernel matrix.
Average of kernel matrix.
fit(K[, y])
Fit KernelCenterer
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
set_params(**params)
Set the parameters of this estimator.
transform(K[, copy])
Center kernel matrix.
Fit KernelCenterer
Kernel matrix.
Ignored.
Fitted transformer.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Center kernel matrix.
Kernel matrix.
Set to False to perform inplace computation.


Fit KernelCenterer
Kernel matrix.
Ignored.
Fitted transformer.


Center kernel matrix.
Kernel matrix.
Set to False to perform inplace computation.


Binarize labels in a one-vs-all fashion.
Several regression and binary classification algorithms are available in scikit-learn. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme.
At learning time, this simply consists in learning one regressor or binary classifier per class. In doing so, one needs to convert multi-class labels to binary labels (belong or does not belong to the class). LabelBinarizer makes this process easy with the transform method.
At prediction time, one assigns the class for which the corresponding model gave the greatest confidence. LabelBinarizer makes this easy with the inverse_transform method.
Read more in the User Guide.
Value with which negative labels must be encoded.
Value with which positive labels must be encoded.
True if the returned array from transform is desired to be in sparse CSR format.
Holds the label for each class.
Represents the type of the target data as evaluated by utils.multiclass.type_of_target. Possible type are ‘continuous’, ‘continuous-multioutput’, ‘binary’, ‘multiclass’, ‘multiclass-multioutput’, ‘multilabel-indicator’, and ‘unknown’.
True if the input data to transform is given as a sparse matrix, False otherwise.
See also
Function to perform the transform operation of LabelBinarizer with fixed classes.
Encode categorical features using a one-hot aka one-of-K scheme.
Binary targets transform to a column vector
Passing a 2D matrix for multilabel classification
fit(y)
Fit label binarizer.
fit_transform(y)
Fit label binarizer and transform multi-class labels to binary labels.
get_params([deep])
Get parameters for this estimator.
inverse_transform(Y[, threshold])
Transform binary labels back to multi-class labels.
set_params(**params)
Set the parameters of this estimator.
transform(y)
Transform multi-class labels to binary labels.
Fit label binarizer.
Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification.
Fit label binarizer and transform multi-class labels to binary labels.
The output of transform is sometimes referred to as the 1-of-K coding scheme.
Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Sparse matrix can be CSR, CSC, COO, DOK, or LIL.
Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Transform binary labels back to multi-class labels.
Target values. All sparse matrices are converted to CSR before inverse transformation.
Threshold used in the binary and multi-label cases.
Use 0 when Y contains the output of decision_function (classifier). Use 0.5 when Y contains the output of predict_proba.
If None, the threshold is assumed to be half way between neg_label and pos_label.
Target values. Sparse matrix will be of CSR format.
In the case when the binary labels are fractional (probabilistic), inverse_transform chooses the class with the greatest value. Typically, this allows to use the output of a linear model’s decision_function method directly as the input of inverse_transform.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform multi-class labels to binary labels.
The output of transform is sometimes referred to by some authors as the 1-of-K coding scheme.
Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Sparse matrix can be CSR, CSC, COO, DOK, or LIL.
Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.


Fit label binarizer.
Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification.


Fit label binarizer and transform multi-class labels to binary labels.
The output of transform is sometimes referred to as the 1-of-K coding scheme.
Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Sparse matrix can be CSR, CSC, COO, DOK, or LIL.
Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Transform binary labels back to multi-class labels.
Target values. All sparse matrices are converted to CSR before inverse transformation.
Threshold used in the binary and multi-label cases.
Use 0 when Y contains the output of decision_function (classifier). Use 0.5 when Y contains the output of predict_proba.
If None, the threshold is assumed to be half way between neg_label and pos_label.
Target values. Sparse matrix will be of CSR format.
In the case when the binary labels are fractional (probabilistic), inverse_transform chooses the class with the greatest value. Typically, this allows to use the output of a linear model’s decision_function method directly as the input of inverse_transform.


Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Transform multi-class labels to binary labels.
The output of transform is sometimes referred to by some authors as the 1-of-K coding scheme.
Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Sparse matrix can be CSR, CSC, COO, DOK, or LIL.
Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.


Encode target labels with value between 0 and n_classes-1.
This transformer should be used to encode target values, i.e. y, and not the input X.
Read more in the User Guide.
New in version 0.12.
Holds the label for each class.
See also
Encode categorical features using an ordinal encoding scheme.
Encode categorical features as a one-hot numeric array.
LabelEncoder can be used to normalize labels.
It can also be used to transform non-numerical labels (as long as they are hashable and comparable) to numerical labels.
fit(y)
Fit label encoder.
fit_transform(y)
Fit label encoder and return encoded labels.
get_params([deep])
Get parameters for this estimator.
inverse_transform(y)
Transform labels back to original encoding.
set_params(**params)
Set the parameters of this estimator.
transform(y)
Transform labels to normalized encoding.
Fit label encoder.
Target values.
Fit label encoder and return encoded labels.
Target values.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Transform labels back to original encoding.
Target values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform labels to normalized encoding.
Target values.


Fit label encoder and return encoded labels.
Target values.


Transform labels back to original encoding.
Target values.


Transform labels to normalized encoding.
Target values.


Binarize labels in a one-vs-all fashion.
Several regression and binary classification algorithms are available in scikit-learn. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme.
This function makes it possible to compute this transformation for a fixed set of class labels known ahead of time.
Sequence of integer labels or multilabel data to encode.
Uniquely holds the label for each class.
Value with which negative labels must be encoded.
Value with which positive labels must be encoded.
Set to true if output binary array is desired in CSR sparse format.
Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.
See also
Class used to wrap the functionality of label_binarize and allow for fitting to classes independently of the transform operation.
The class ordering is preserved:
Binary targets transform to a column vector


Scale each feature by its maximum absolute value.
This estimator scales and translates each feature individually such that the maximal absolute value of each feature in the training set will be 1.0. It does not shift/center the data, and thus does not destroy any sparsity.
This scaler can also be applied to sparse CSR or CSC matrices.
New in version 0.17.
Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).
Per feature relative scaling of the data.
New in version 0.17: scale_ attribute.
Per feature maximum absolute value.
The number of samples processed by the estimator. Will be reset on new calls to fit, but increments across partial_fit calls.
See also
Equivalent function without the estimator API.
NaNs are treated as missing values: disregarded in fit, and maintained in transform.
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.
fit(X[, y])
Compute the maximum absolute value to be used for later scaling.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Scale back the data to the original representation
partial_fit(X[, y])
Online computation of max absolute value of X for later scaling.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Scale the data
Compute the maximum absolute value to be used for later scaling.
The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
Ignored.
Fitted scaler.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Scale back the data to the original representation
The data that should be transformed back.
Transformed array.
Online computation of max absolute value of X for later scaling.
All of X is processed as a single batch. This is intended for cases when fit is not feasible due to very large number of n_samples or because X is read from a continuous stream.
The data used to compute the mean and standard deviation used for later scaling along the features axis.
Ignored.
Fitted scaler.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Scale the data
The data that should be scaled.
Transformed array.


Scale each feature by its maximum absolute value.
This estimator scales and translates each feature individually such that the maximal absolute value of each feature in the training set will be 1.0. It does not shift/center the data, and thus does not destroy any sparsity.
This scaler can also be applied to sparse CSR or CSC matrices.
New in version 0.17.
Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).
Per feature relative scaling of the data.
New in version 0.17: scale_ attribute.
Per feature maximum absolute value.
The number of samples processed by the estimator. Will be reset on new calls to fit, but increments across partial_fit calls.
See also
Equivalent function without the estimator API.
NaNs are treated as missing values: disregarded in fit, and maintained in transform.
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.
fit(X[, y])
Compute the maximum absolute value to be used for later scaling.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Scale back the data to the original representation
partial_fit(X[, y])
Online computation of max absolute value of X for later scaling.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Scale the data
Compute the maximum absolute value to be used for later scaling.
The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
Ignored.
Fitted scaler.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Scale back the data to the original representation
The data that should be transformed back.
Transformed array.
Online computation of max absolute value of X for later scaling.
All of X is processed as a single batch. This is intended for cases when fit is not feasible due to very large number of n_samples or because X is read from a continuous stream.
The data used to compute the mean and standard deviation used for later scaling along the features axis.
Ignored.
Fitted scaler.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Scale the data
The data that should be scaled.
Transformed array.
Compare the effect of different scalers on data with outliers


Compute the maximum absolute value to be used for later scaling.
The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
Ignored.
Fitted scaler.


Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.


Scale back the data to the original representation
The data that should be transformed back.
Transformed array.


Online computation of max absolute value of X for later scaling.
All of X is processed as a single batch. This is intended for cases when fit is not feasible due to very large number of n_samples or because X is read from a continuous stream.
The data used to compute the mean and standard deviation used for later scaling along the features axis.
Ignored.
Fitted scaler.


Scale the data
The data that should be scaled.
Transformed array.


Scale each feature to the [-1, 1] range without breaking the sparsity.
This estimator scales each feature individually such that the maximal absolute value of each feature in the training set will be 1.0.
This scaler can also be applied to sparse CSR or CSC matrices.
The data.
axis used to scale along. If 0, independently scale each feature, otherwise (if 1) scale each sample.
Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).
The transformed data.
Warning
Risk of data leak Do not use maxabs_scale unless you know what you are doing. A common mistake is to apply it to the entire data before splitting into training and test sets. This will bias the model evaluation because information would have leaked from the test set to the training set. In general, we recommend using MaxAbsScaler within a Pipeline in order to prevent most risks of data leaking: pipe = make_pipeline(MaxAbsScaler(), LogisticRegression()).
See also
Performs scaling to the [-1, 1] range using the Transformer API (e.g. as part of a preprocessing Pipeline).
NaNs are treated as missing values: disregarded to compute the statistics, and maintained during the data transformation.
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.


Transform features by scaling each feature to a given range.
This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one.
The transformation is given by:
where min, max = feature_range.
This transformation is often used as an alternative to zero mean, unit variance scaling.
Read more in the User Guide.
Desired range of transformed data.
Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array).
Set to True to clip transformed values of held-out data to provided feature range.
New in version 0.24.
Per feature adjustment for minimum. Equivalent to min - X.min(axis=0) * self.scale_
Per feature relative scaling of the data. Equivalent to (max - min) / (X.max(axis=0) - X.min(axis=0))
New in version 0.17: scale_ attribute.
Per feature minimum seen in the data
New in version 0.17: data_min_
Per feature maximum seen in the data
New in version 0.17: data_max_
Per feature range (data_max_ - data_min_) seen in the data
New in version 0.17: data_range_
The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across partial_fit calls.
See also
Equivalent function without the estimator API.
NaNs are treated as missing values: disregarded in fit, and maintained in transform.
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.
fit(X[, y])
Compute the minimum and maximum to be used for later scaling.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Undo the scaling of X according to feature_range.
partial_fit(X[, y])
Online computation of min and max on X for later scaling.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Scale features of X according to feature_range.
Compute the minimum and maximum to be used for later scaling.
The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
Ignored.
Fitted scaler.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Undo the scaling of X according to feature_range.
Input data that will be transformed. It cannot be sparse.
Transformed data.
Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases when fit is not feasible due to very large number of n_samples or because X is read from a continuous stream.
The data used to compute the mean and standard deviation used for later scaling along the features axis.
Ignored.
Fitted scaler.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Scale features of X according to feature_range.
Input data that will be transformed.
Transformed data.


Transform features by scaling each feature to a given range.
This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one.
The transformation is given by:
where min, max = feature_range.
This transformation is often used as an alternative to zero mean, unit variance scaling.
Read more in the User Guide.
Desired range of transformed data.
Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array).
Set to True to clip transformed values of held-out data to provided feature range.
New in version 0.24.
Per feature adjustment for minimum. Equivalent to min - X.min(axis=0) * self.scale_
Per feature relative scaling of the data. Equivalent to (max - min) / (X.max(axis=0) - X.min(axis=0))
New in version 0.17: scale_ attribute.
Per feature minimum seen in the data
New in version 0.17: data_min_
Per feature maximum seen in the data
New in version 0.17: data_max_
Per feature range (data_max_ - data_min_) seen in the data
New in version 0.17: data_range_
The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across partial_fit calls.
See also
Equivalent function without the estimator API.
NaNs are treated as missing values: disregarded in fit, and maintained in transform.
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.
fit(X[, y])
Compute the minimum and maximum to be used for later scaling.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Undo the scaling of X according to feature_range.
partial_fit(X[, y])
Online computation of min and max on X for later scaling.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Scale features of X according to feature_range.
Compute the minimum and maximum to be used for later scaling.
The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
Ignored.
Fitted scaler.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Undo the scaling of X according to feature_range.
Input data that will be transformed. It cannot be sparse.
Transformed data.
Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases when fit is not feasible due to very large number of n_samples or because X is read from a continuous stream.
The data used to compute the mean and standard deviation used for later scaling along the features axis.
Ignored.
Fitted scaler.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Scale features of X according to feature_range.
Input data that will be transformed.
Transformed data.
Release Highlights for scikit-learn 0.24
Univariate Feature Selection
Scalable learning with polynomial kernel aproximation
Compare Stochastic learning strategies for MLPClassifier
Compare the effect of different scalers on data with outliers


Compute the minimum and maximum to be used for later scaling.
The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
Ignored.
Fitted scaler.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Undo the scaling of X according to feature_range.
Input data that will be transformed. It cannot be sparse.
Transformed data.


Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases when fit is not feasible due to very large number of n_samples or because X is read from a continuous stream.
The data used to compute the mean and standard deviation used for later scaling along the features axis.
Ignored.
Fitted scaler.


Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Scale features of X according to feature_range.
Input data that will be transformed.
Transformed data.


Transform features by scaling each feature to a given range.
This estimator scales and translates each feature individually such that it is in the given range on the training set, i.e. between zero and one.
The transformation is given by (when axis=0):
where min, max = feature_range.
The transformation is calculated as (when axis=0):
This transformation is often used as an alternative to zero mean, unit variance scaling.
Read more in the User Guide.
New in version 0.17: minmax_scale function interface to MinMaxScaler.
The data.
Desired range of transformed data.
Axis used to scale along. If 0, independently scale each feature, otherwise (if 1) scale each sample.
Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).
The transformed data.
Warning
Risk of data leak Do not use minmax_scale unless you know what you are doing. A common mistake is to apply it to the entire data before splitting into training and test sets. This will bias the model evaluation because information would have leaked from the test set to the training set. In general, we recommend using MinMaxScaler within a Pipeline in order to prevent most risks of data leaking: pipe = make_pipeline(MinMaxScaler(), LogisticRegression()).
See also
Performs scaling to a given range using the Transformer API (e.g. as part of a preprocessing Pipeline).
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.


Transform between iterable of iterables and a multilabel format.
Although a list of sets or tuples is a very intuitive format for multilabel data, it is unwieldy to process. This transformer converts between this intuitive format and the supported multilabel format: a (samples x classes) binary matrix indicating the presence of a class label.
Indicates an ordering for the class labels. All entries should be unique (cannot contain duplicate classes).
Set to True if output binary array is desired in CSR sparse format.
A copy of the classes parameter when provided. Otherwise it corresponds to the sorted set of classes found when fitting.
See also
Encode categorical features using a one-hot aka one-of-K scheme.
A common mistake is to pass in a list, which leads to the following issue:
To correct this, the list of labels should be passed in as:
fit(y)
Fit the label sets binarizer, storing classes_.
fit_transform(y)
Fit the label sets binarizer and transform the given label sets.
get_params([deep])
Get parameters for this estimator.
inverse_transform(yt)
Transform the given indicator matrix into label sets.
set_params(**params)
Set the parameters of this estimator.
transform(y)
Transform the given label sets.
Fit the label sets binarizer, storing classes_.
A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.
Fit the label sets binarizer and transform the given label sets.
A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.
A matrix such that y_indicator[i, j] = 1 i.f.f. classes_[j] is in y[i], and 0 otherwise. Sparse matrix will be of CSR format.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Transform the given indicator matrix into label sets.
A matrix containing only 1s ands 0s.
The set of labels for each sample such that y[i] consists of classes_[j] for each yt[i, j] == 1.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform the given label sets.
A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.
A matrix such that y_indicator[i, j] = 1 iff classes_[j] is in y[i], and 0 otherwise.


Fit the label sets binarizer, storing classes_.
A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.


Fit the label sets binarizer and transform the given label sets.
A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.
A matrix such that y_indicator[i, j] = 1 i.f.f. classes_[j] is in y[i], and 0 otherwise. Sparse matrix will be of CSR format.


Transform the given indicator matrix into label sets.
A matrix containing only 1s ands 0s.
The set of labels for each sample such that y[i] consists of classes_[j] for each yt[i, j] == 1.


Transform the given label sets.
A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.
A matrix such that y_indicator[i, j] = 1 iff classes_[j] is in y[i], and 0 otherwise.


Scale input vectors individually to unit norm (vector length).
Read more in the User Guide.
The data to normalize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
The norm to use to normalize each non zero sample (or each non-zero feature if axis is 0).
axis used to normalize the data along. If 1, independently normalize each sample, otherwise (if 0) normalize each feature.
set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix and if axis is 1).
whether to return the computed norms
Normalized input X.
An array of norms along given axis for X. When X is sparse, a NotImplementedError will be raised for norm ‘l1’ or ‘l2’.
See also
Performs normalization using the Transformer API (e.g. as part of a preprocessing Pipeline).
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.


Normalize samples individually to unit norm.
Each sample (i.e. each row of the data matrix) with at least one non zero component is rescaled independently of other samples so that its norm (l1, l2 or inf) equals one.
This transformer is able to work both with dense numpy arrays and scipy.sparse matrix (use CSR format if you want to avoid the burden of a copy / conversion).
Scaling inputs to unit norms is a common operation for text classification or clustering for instance. For instance the dot product of two l2-normalized TF-IDF vectors is the cosine similarity of the vectors and is the base similarity metric for the Vector Space Model commonly used by the Information Retrieval community.
Read more in the User Guide.
The norm to use to normalize each non zero sample. If norm=’max’ is used, values will be rescaled by the maximum of the absolute values.
set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix).
See also
Equivalent function without the estimator API.
This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline.
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.
fit(X[, y])
Do nothing and return the estimator unchanged
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
set_params(**params)
Set the parameters of this estimator.
transform(X[, copy])
Scale each non zero row of X to unit norm
Do nothing and return the estimator unchanged
This method is just there to implement the usual API and hence work in pipelines.
The data to estimate the normalization parameters.
Ignored.
Fitted transformer.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Scale each non zero row of X to unit norm
The data to normalize, row by row. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
Copy the input X or not.
Transformed array.


Normalize samples individually to unit norm.
Each sample (i.e. each row of the data matrix) with at least one non zero component is rescaled independently of other samples so that its norm (l1, l2 or inf) equals one.
This transformer is able to work both with dense numpy arrays and scipy.sparse matrix (use CSR format if you want to avoid the burden of a copy / conversion).
Scaling inputs to unit norms is a common operation for text classification or clustering for instance. For instance the dot product of two l2-normalized TF-IDF vectors is the cosine similarity of the vectors and is the base similarity metric for the Vector Space Model commonly used by the Information Retrieval community.
Read more in the User Guide.
The norm to use to normalize each non zero sample. If norm=’max’ is used, values will be rescaled by the maximum of the absolute values.
set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix).
See also
Equivalent function without the estimator API.
This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline.
For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.
fit(X[, y])
Do nothing and return the estimator unchanged
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
set_params(**params)
Set the parameters of this estimator.
transform(X[, copy])
Scale each non zero row of X to unit norm
Do nothing and return the estimator unchanged
This method is just there to implement the usual API and hence work in pipelines.
The data to estimate the normalization parameters.
Ignored.
Fitted transformer.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Scale each non zero row of X to unit norm
The data to normalize, row by row. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
Copy the input X or not.
Transformed array.
Scalable learning with polynomial kernel aproximation
Compare the effect of different scalers on data with outliers
Clustering text documents using k-means


Do nothing and return the estimator unchanged
This method is just there to implement the usual API and hence work in pipelines.
The data to estimate the normalization parameters.
Ignored.
Fitted transformer.


Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.


Scale each non zero row of X to unit norm
The data to normalize, row by row. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
Copy the input X or not.
Transformed array.


Encode categorical features as a one-hot numeric array.
The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka ‘one-of-K’ or ‘dummy’) encoding scheme. This creates a binary column for each category and returns a sparse matrix or dense array (depending on the sparse parameter)
By default, the encoder derives the categories based on the unique values in each feature. Alternatively, you can also specify the categories manually.
This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels.
Note: a one-hot encoding of y labels should use a LabelBinarizer instead.
Read more in the User Guide.
Changed in version 0.20.
Categories (unique values) per feature:
The used categories can be found in the categories_ attribute.
New in version 0.20.
Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into a neural network or an unregularized regression.
However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models.
Changed in version 0.23: Added option ‘if_binary’.
Will return sparse matrix if set True else will return an array.
Desired dtype of output.
Whether to raise an error or ignore if an unknown categorical feature is present during transform (default is to raise). When this parameter is set to ‘ignore’ and an unknown category is encountered during transform, 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.
The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of transform). This includes the category specified in drop (if any).
Changed in version 0.23: Added the possibility to contain None values.
See also
Performs an ordinal (integer) encoding of the categorical features.
Performs a one-hot encoding of dictionary items (also handles string-valued features).
Performs an approximate one-hot encoding of dictionary items or strings.
Binarizes labels in a one-vs-all fashion.
Transforms between iterable of iterables and a multilabel format, e.g. a (samples x classes) binary matrix indicating the presence of a class label.
Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to a binary one-hot encoding.
One can discard categories not seen during fit:
One can always drop the first column for each feature:
Or drop a column for feature only having 2 categories:
fit(X[, y])
Fit OneHotEncoder to X.
fit_transform(X[, y])
Fit OneHotEncoder to X, then transform X.
get_feature_names([input_features])
Return feature names for output features.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Convert the data back to the original representation.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Transform X using one-hot encoding.
Fit OneHotEncoder to X.
The data to determine the categories of each feature.
Ignored. This parameter exists only for compatibility with Pipeline.
Fit OneHotEncoder to X, then transform X.
Equivalent to fit(X).transform(X) but more convenient.
The data to encode.
Ignored. This parameter exists only for compatibility with Pipeline.
Transformed input.
Return feature names for output features.
String names for input features if available. By default, “x0”, “x1”, … “xn_features” is used.
Array of feature names.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Convert the data back to the original representation.
In case unknown categories are encountered (all zeros in the one-hot encoding), None is used to represent this category.
The transformed data.
Inverse transformed array.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform X using one-hot encoding.
The data to encode.
Transformed input.


Encode categorical features as a one-hot numeric array.
The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka ‘one-of-K’ or ‘dummy’) encoding scheme. This creates a binary column for each category and returns a sparse matrix or dense array (depending on the sparse parameter)
By default, the encoder derives the categories based on the unique values in each feature. Alternatively, you can also specify the categories manually.
This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels.
Note: a one-hot encoding of y labels should use a LabelBinarizer instead.
Read more in the User Guide.
Changed in version 0.20.
Categories (unique values) per feature:
The used categories can be found in the categories_ attribute.
New in version 0.20.
Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into a neural network or an unregularized regression.
However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models.
Changed in version 0.23: Added option ‘if_binary’.
Will return sparse matrix if set True else will return an array.
Desired dtype of output.
Whether to raise an error or ignore if an unknown categorical feature is present during transform (default is to raise). When this parameter is set to ‘ignore’ and an unknown category is encountered during transform, 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.
The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of transform). This includes the category specified in drop (if any).
Changed in version 0.23: Added the possibility to contain None values.
See also
Performs an ordinal (integer) encoding of the categorical features.
Performs a one-hot encoding of dictionary items (also handles string-valued features).
Performs an approximate one-hot encoding of dictionary items or strings.
Binarizes labels in a one-vs-all fashion.
Transforms between iterable of iterables and a multilabel format, e.g. a (samples x classes) binary matrix indicating the presence of a class label.
Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to a binary one-hot encoding.
One can discard categories not seen during fit:
One can always drop the first column for each feature:
Or drop a column for feature only having 2 categories:
fit(X[, y])
Fit OneHotEncoder to X.
fit_transform(X[, y])
Fit OneHotEncoder to X, then transform X.
get_feature_names([input_features])
Return feature names for output features.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Convert the data back to the original representation.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Transform X using one-hot encoding.
Fit OneHotEncoder to X.
The data to determine the categories of each feature.
Ignored. This parameter exists only for compatibility with Pipeline.
Fit OneHotEncoder to X, then transform X.
Equivalent to fit(X).transform(X) but more convenient.
The data to encode.
Ignored. This parameter exists only for compatibility with Pipeline.
Transformed input.
Return feature names for output features.
String names for input features if available. By default, “x0”, “x1”, … “xn_features” is used.
Array of feature names.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Convert the data back to the original representation.
In case unknown categories are encountered (all zeros in the one-hot encoding), None is used to represent this category.
The transformed data.
Inverse transformed array.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform X using one-hot encoding.
The data to encode.
Transformed input.
Release Highlights for scikit-learn 0.23
Feature transformations with ensembles of trees
Categorical Feature Support in Gradient Boosting
Combine predictors using stacking
Poisson regression and non-normal loss
Tweedie regression on insurance claims
Permutation Importance vs Random Forest Feature Importance (MDI)
Common pitfalls in interpretation of coefficients of linear models
Column Transformer with Mixed Types


Fit OneHotEncoder to X.
The data to determine the categories of each feature.
Ignored. This parameter exists only for compatibility with Pipeline.


Fit OneHotEncoder to X, then transform X.
Equivalent to fit(X).transform(X) but more convenient.
The data to encode.
Ignored. This parameter exists only for compatibility with Pipeline.
Transformed input.


Return feature names for output features.
String names for input features if available. By default, “x0”, “x1”, … “xn_features” is used.
Array of feature names.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Convert the data back to the original representation.
In case unknown categories are encountered (all zeros in the one-hot encoding), None is used to represent this category.
The transformed data.
Inverse transformed array.


Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Transform X using one-hot encoding.
The data to encode.
Transformed input.


Encode categorical features as an integer array.
The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature.
Read more in the User Guide.
New in version 0.20.
Categories (unique values) per feature:
The used categories can be found in the categories_ attribute.
Desired dtype of output.
When set to ‘error’ an error will be raised in case an unknown categorical feature is present during transform. When set to ‘use_encoded_value’, the encoded value of unknown categories will be set to the value given for the parameter unknown_value. In inverse_transform, an unknown category will be denoted as None.
New in version 0.24.
When the parameter handle_unknown is set to ‘use_encoded_value’, this parameter is required and will set the encoded value of unknown categories. It has to be distinct from the values used to encode any of the categories in fit. If set to np.nan, the dtype parameter must be a float dtype.
New in version 0.24.
The categories of each feature determined during fit (in order of the features in X and corresponding with the output of transform). This does not include categories that weren’t seen during fit.
See also
Performs a one-hot encoding of categorical features.
Encodes target labels with values between 0 and n_classes-1.
Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to an ordinal encoding.
fit(X[, y])
Fit the OrdinalEncoder to X.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Convert the data back to the original representation.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Transform X to ordinal codes.
Fit the OrdinalEncoder to X.
The data to determine the categories of each feature.
Ignored. This parameter exists only for compatibility with Pipeline.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Convert the data back to the original representation.
The transformed data.
Inverse transformed array.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform X to ordinal codes.
The data to encode.
Transformed input.


Encode categorical features as an integer array.
The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature.
Read more in the User Guide.
New in version 0.20.
Categories (unique values) per feature:
The used categories can be found in the categories_ attribute.
Desired dtype of output.
When set to ‘error’ an error will be raised in case an unknown categorical feature is present during transform. When set to ‘use_encoded_value’, the encoded value of unknown categories will be set to the value given for the parameter unknown_value. In inverse_transform, an unknown category will be denoted as None.
New in version 0.24.
When the parameter handle_unknown is set to ‘use_encoded_value’, this parameter is required and will set the encoded value of unknown categories. It has to be distinct from the values used to encode any of the categories in fit. If set to np.nan, the dtype parameter must be a float dtype.
New in version 0.24.
The categories of each feature determined during fit (in order of the features in X and corresponding with the output of transform). This does not include categories that weren’t seen during fit.
See also
Performs a one-hot encoding of categorical features.
Encodes target labels with values between 0 and n_classes-1.
Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to an ordinal encoding.
fit(X[, y])
Fit the OrdinalEncoder to X.
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Convert the data back to the original representation.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Transform X to ordinal codes.
Fit the OrdinalEncoder to X.
The data to determine the categories of each feature.
Ignored. This parameter exists only for compatibility with Pipeline.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Convert the data back to the original representation.
The transformed data.
Inverse transformed array.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform X to ordinal codes.
The data to encode.
Transformed input.
Categorical Feature Support in Gradient Boosting
Combine predictors using stacking
Poisson regression and non-normal loss


Fit the OrdinalEncoder to X.
The data to determine the categories of each feature.
Ignored. This parameter exists only for compatibility with Pipeline.


Convert the data back to the original representation.
The transformed data.
Inverse transformed array.


Transform X to ordinal codes.
The data to encode.
Transformed input.


Generate polynomial and interaction features.
Generate a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. For example, if an input sample is two dimensional and of the form [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2].
The degree of the polynomial features.
If true, only interaction features are produced: features that are products of at most degree distinct input features (so not x[1] ** 2, x[0] * x[2] ** 3, etc.).
If True (default), then include a bias column, the feature in which all polynomial powers are zero (i.e. a column of ones - acts as an intercept term in a linear model).
Order of output array in the dense case. ‘F’ order is faster to compute, but may slow down subsequent estimators.
New in version 0.21.
powers_[i, j] is the exponent of the jth input in the ith output.
The total number of input features.
The total number of polynomial output features. The number of output features is computed by iterating over all suitably sized combinations of input features.
Be aware that the number of features in the output array scales polynomially in the number of features of the input array, and exponentially in the degree. High degrees can cause overfitting.
See examples/linear_model/plot_polynomial_interpolation.py
fit(X[, y])
Compute number of output features.
fit_transform(X[, y])
Fit to data, then transform it.
get_feature_names([input_features])
Return feature names for output features
get_params([deep])
Get parameters for this estimator.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Transform data to polynomial features
Compute number of output features.
The data.
Ignored.
Fitted transformer.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Return feature names for output features
String names for input features if available. By default, “x0”, “x1”, … “xn_features” is used.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform data to polynomial features
The data to transform, row by row.
Prefer CSR over CSC for sparse input (for speed), but CSC is required if the degree is 4 or higher. If the degree is less than 4 and the input format is CSC, it will be converted to CSR, have its polynomial features generated, then converted back to CSC.
If the degree is 2 or 3, the method described in “Leveraging Sparsity to Speed Up Polynomial Feature Expansions of CSR Matrices Using K-Simplex Numbers” by Andrew Nystrom and John Hughes is used, which is much faster than the method used on CSC input. For this reason, a CSC input will be converted to CSR, and the output will be converted back to CSC prior to being returned, hence the preference of CSR.
The matrix of features, where NP is the number of polynomial features generated from the combination of inputs. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.


Generate polynomial and interaction features.
Generate a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. For example, if an input sample is two dimensional and of the form [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2].
The degree of the polynomial features.
If true, only interaction features are produced: features that are products of at most degree distinct input features (so not x[1] ** 2, x[0] * x[2] ** 3, etc.).
If True (default), then include a bias column, the feature in which all polynomial powers are zero (i.e. a column of ones - acts as an intercept term in a linear model).
Order of output array in the dense case. ‘F’ order is faster to compute, but may slow down subsequent estimators.
New in version 0.21.
powers_[i, j] is the exponent of the jth input in the ith output.
The total number of input features.
The total number of polynomial output features. The number of output features is computed by iterating over all suitably sized combinations of input features.
Be aware that the number of features in the output array scales polynomially in the number of features of the input array, and exponentially in the degree. High degrees can cause overfitting.
See examples/linear_model/plot_polynomial_interpolation.py
fit(X[, y])
Compute number of output features.
fit_transform(X[, y])
Fit to data, then transform it.
get_feature_names([input_features])
Return feature names for output features
get_params([deep])
Get parameters for this estimator.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Transform data to polynomial features
Compute number of output features.
The data.
Ignored.
Fitted transformer.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Return feature names for output features
String names for input features if available. By default, “x0”, “x1”, … “xn_features” is used.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Transform data to polynomial features
The data to transform, row by row.
Prefer CSR over CSC for sparse input (for speed), but CSC is required if the degree is 4 or higher. If the degree is less than 4 and the input format is CSC, it will be converted to CSR, have its polynomial features generated, then converted back to CSC.
If the degree is 2 or 3, the method described in “Leveraging Sparsity to Speed Up Polynomial Feature Expansions of CSR Matrices Using K-Simplex Numbers” by Andrew Nystrom and John Hughes is used, which is much faster than the method used on CSC input. For this reason, a CSC input will be converted to CSR, and the output will be converted back to CSC prior to being returned, hence the preference of CSR.
The matrix of features, where NP is the number of polynomial features generated from the combination of inputs. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
Release Highlights for scikit-learn 0.24
Polynomial interpolation
Robust linear estimator fitting
Poisson regression and non-normal loss
Underfitting vs. Overfitting


Compute number of output features.
The data.
Ignored.
Fitted transformer.