sklearn.preprocessing.Binarizer
class sklearn.preprocessing.Binarizer(*, threshold=0.0, copy=True) [source]

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

thresholdfloat, default=0.0

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.
copybool, default=True

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
binarize

Equivalent function without the estimator API.    Notes 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. Examples >>> from sklearn.preprocessing import Binarizer
>>> X = [[ 1., -1.,  2.],
...      [ 2.,  0.,  0.],
...      [ 0.,  1., -1.]]
>>> transformer = Binarizer().fit(X)  # fit does nothing.
>>> transformer
Binarizer()
>>> transformer.transform(X)
array([[1., 0., 1.],
       [1., 0., 0.],
       [0., 1., 0.]])
 Methods
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.
fit(X, y=None) [source]

Do nothing and return the estimator unchanged. This method is just there to implement the usual API and hence work in pipelines.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data.
yNone

Ignored.    Returns

selfobject

Fitted transformer.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X, copy=None) [source]

Binarize each element of X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data to binarize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
copybool

Copy the input X or not.    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

Transformed array.


fit(X, y=None) [source]

Do nothing and return the estimator unchanged. This method is just there to implement the usual API and hence work in pipelines.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data.
yNone

Ignored.    Returns

selfobject

Fitted transformer.


fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


transform(X, copy=None) [source]

Binarize each element of X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data to binarize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
copybool

Copy the input X or not.    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

Transformed array.


class sklearn.preprocessing.FunctionTransformer(func=None, inverse_func=None, *, validate=False, accept_sparse=False, check_inverse=True, kw_args=None, inv_kw_args=None) [source]

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

funccallable, default=None

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.
inverse_funccallable, default=None

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.
validatebool, default=False

Indicate that the input X array should be checked before calling func. The possibilities are:  If False, there is no input validation. If True, then X will be converted to a 2-dimensional NumPy array or sparse matrix. If the conversion is not possible an exception is raised.   Changed in version 0.22: The default of validate changed from True to False.
accept_sparsebool, default=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.
check_inversebool, default=True

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.
kw_argsdict, default=None

Dictionary of additional keyword arguments to pass to func.  New in version 0.18.
inv_kw_argsdict, default=None

Dictionary of additional keyword arguments to pass to inverse_func.  New in version 0.18.      Examples >>> import numpy as np
>>> from sklearn.preprocessing import FunctionTransformer
>>> transformer = FunctionTransformer(np.log1p)
>>> X = np.array([[0, 1], [2, 3]])
>>> transformer.transform(X)
array([[0.       , 0.6931...],
       [1.0986..., 1.3862...]])
 Methods
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(X, y=None) [source]

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

Xarray-like, shape (n_samples, n_features)

Input array.    Returns
 self

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(X) [source]

Transform X using the inverse function.  Parameters

Xarray-like, shape (n_samples, n_features)

Input array.    Returns

X_outarray-like, shape (n_samples, n_features)

Transformed input.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Transform X using the forward function.  Parameters

Xarray-like, shape (n_samples, n_features)

Input array.    Returns

X_outarray-like, shape (n_samples, n_features)

Transformed input.


sklearn.preprocessing.FunctionTransformer
class sklearn.preprocessing.FunctionTransformer(func=None, inverse_func=None, *, validate=False, accept_sparse=False, check_inverse=True, kw_args=None, inv_kw_args=None) [source]

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

funccallable, default=None

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.
inverse_funccallable, default=None

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.
validatebool, default=False

Indicate that the input X array should be checked before calling func. The possibilities are:  If False, there is no input validation. If True, then X will be converted to a 2-dimensional NumPy array or sparse matrix. If the conversion is not possible an exception is raised.   Changed in version 0.22: The default of validate changed from True to False.
accept_sparsebool, default=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.
check_inversebool, default=True

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.
kw_argsdict, default=None

Dictionary of additional keyword arguments to pass to func.  New in version 0.18.
inv_kw_argsdict, default=None

Dictionary of additional keyword arguments to pass to inverse_func.  New in version 0.18.      Examples >>> import numpy as np
>>> from sklearn.preprocessing import FunctionTransformer
>>> transformer = FunctionTransformer(np.log1p)
>>> X = np.array([[0, 1], [2, 3]])
>>> transformer.transform(X)
array([[0.       , 0.6931...],
       [1.0986..., 1.3862...]])
 Methods
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(X, y=None) [source]

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

Xarray-like, shape (n_samples, n_features)

Input array.    Returns
 self

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(X) [source]

Transform X using the inverse function.  Parameters

Xarray-like, shape (n_samples, n_features)

Input array.    Returns

X_outarray-like, shape (n_samples, n_features)

Transformed input.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Transform X using the forward function.  Parameters

Xarray-like, shape (n_samples, n_features)

Input array.    Returns

X_outarray-like, shape (n_samples, n_features)

Transformed input.

 Examples using sklearn.preprocessing.FunctionTransformer

  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(X, y=None) [source]

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

Xarray-like, shape (n_samples, n_features)

Input array.    Returns
 self


inverse_transform(X) [source]

Transform X using the inverse function.  Parameters

Xarray-like, shape (n_samples, n_features)

Input array.    Returns

X_outarray-like, shape (n_samples, n_features)

Transformed input.


transform(X) [source]

Transform X using the forward function.  Parameters

Xarray-like, shape (n_samples, n_features)

Input array.    Returns

X_outarray-like, shape (n_samples, n_features)

Transformed input.


class sklearn.preprocessing.KBinsDiscretizer(n_bins=5, *, encode='onehot', strategy='quantile', dtype=None) [source]

Bin continuous data into intervals. Read more in the User Guide.  New in version 0.20.   Parameters

n_binsint or array-like of shape (n_features,), default=5

The number of bins to produce. Raises ValueError if n_bins < 2.
encode{‘onehot’, ‘onehot-dense’, ‘ordinal’}, default=’onehot’

Method used to encode the transformed result.  onehot

Encode the transformed result with one-hot encoding and return a sparse matrix. Ignored features are always stacked to the right.  onehot-dense

Encode the transformed result with one-hot encoding and return a dense array. Ignored features are always stacked to the right.  ordinal

Return the bin identifier encoded as an integer value.
strategy{‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’

Strategy used to define the widths of the bins.  uniform

All bins in each feature have identical widths.  quantile

All bins in each feature have the same number of points.  kmeans

Values in each bin have the same nearest center of a 1D k-means cluster.
dtype{np.float32, np.float64}, default=None

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

n_bins_ndarray of shape (n_features,), dtype=np.int_

Number of bins per feature. Bins whose width are too small (i.e., <= 1e-8) are removed with a warning.
bin_edges_ndarray of ndarray of shape (n_features,)

The edges of each bin. Contain arrays of varying shapes (n_bins_, ) Ignored features will have empty arrays.      See also
Binarizer

Class used to bin values as 0 or 1 based on a parameter threshold.    Notes In bin edges for feature i, the first and last values are used only for inverse_transform. During transform, bin edges are extended to: np.concatenate([-np.inf, bin_edges_[i][1:-1], np.inf])
 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). Examples >>> X = [[-2, 1, -4,   -1],
...      [-1, 2, -3, -0.5],
...      [ 0, 3, -2,  0.5],
...      [ 1, 4, -1,    2]]
>>> est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform')
>>> est.fit(X)
KBinsDiscretizer(...)
>>> Xt = est.transform(X)
>>> Xt
array([[ 0., 0., 0., 0.],
       [ 1., 1., 1., 0.],
       [ 2., 2., 2., 1.],
       [ 2., 2., 2., 2.]])
 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. >>> est.bin_edges_[0]
array([-2., -1.,  0.,  1.])
>>> est.inverse_transform(Xt)
array([[-1.5,  1.5, -3.5, -0.5],
       [-0.5,  2.5, -2.5, -0.5],
       [ 0.5,  3.5, -1.5,  0.5],
       [ 0.5,  3.5, -1.5,  1.5]])
 Methods
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(X, y=None) [source]

Fit the estimator.  Parameters

Xarray-like of shape (n_samples, n_features)

Data to be discretized.
yNone

Ignored. This parameter exists only for compatibility with Pipeline.    Returns
 self

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(Xt) [source]

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

Xtarray-like of shape (n_samples, n_features)

Transformed data in the binned space.    Returns

Xinvndarray, dtype={np.float32, np.float64}

Data in the original feature space.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Discretize the data.  Parameters

Xarray-like of shape (n_samples, n_features)

Data to be discretized.    Returns

Xt{ndarray, sparse matrix}, dtype={np.float32, np.float64}

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


sklearn.preprocessing.KBinsDiscretizer
class sklearn.preprocessing.KBinsDiscretizer(n_bins=5, *, encode='onehot', strategy='quantile', dtype=None) [source]

Bin continuous data into intervals. Read more in the User Guide.  New in version 0.20.   Parameters

n_binsint or array-like of shape (n_features,), default=5

The number of bins to produce. Raises ValueError if n_bins < 2.
encode{‘onehot’, ‘onehot-dense’, ‘ordinal’}, default=’onehot’

Method used to encode the transformed result.  onehot

Encode the transformed result with one-hot encoding and return a sparse matrix. Ignored features are always stacked to the right.  onehot-dense

Encode the transformed result with one-hot encoding and return a dense array. Ignored features are always stacked to the right.  ordinal

Return the bin identifier encoded as an integer value.
strategy{‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’

Strategy used to define the widths of the bins.  uniform

All bins in each feature have identical widths.  quantile

All bins in each feature have the same number of points.  kmeans

Values in each bin have the same nearest center of a 1D k-means cluster.
dtype{np.float32, np.float64}, default=None

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

n_bins_ndarray of shape (n_features,), dtype=np.int_

Number of bins per feature. Bins whose width are too small (i.e., <= 1e-8) are removed with a warning.
bin_edges_ndarray of ndarray of shape (n_features,)

The edges of each bin. Contain arrays of varying shapes (n_bins_, ) Ignored features will have empty arrays.      See also
Binarizer

Class used to bin values as 0 or 1 based on a parameter threshold.    Notes In bin edges for feature i, the first and last values are used only for inverse_transform. During transform, bin edges are extended to: np.concatenate([-np.inf, bin_edges_[i][1:-1], np.inf])
 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). Examples >>> X = [[-2, 1, -4,   -1],
...      [-1, 2, -3, -0.5],
...      [ 0, 3, -2,  0.5],
...      [ 1, 4, -1,    2]]
>>> est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform')
>>> est.fit(X)
KBinsDiscretizer(...)
>>> Xt = est.transform(X)
>>> Xt
array([[ 0., 0., 0., 0.],
       [ 1., 1., 1., 0.],
       [ 2., 2., 2., 1.],
       [ 2., 2., 2., 2.]])
 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. >>> est.bin_edges_[0]
array([-2., -1.,  0.,  1.])
>>> est.inverse_transform(Xt)
array([[-1.5,  1.5, -3.5, -0.5],
       [-0.5,  2.5, -2.5, -0.5],
       [ 0.5,  3.5, -1.5,  0.5],
       [ 0.5,  3.5, -1.5,  1.5]])
 Methods
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(X, y=None) [source]

Fit the estimator.  Parameters

Xarray-like of shape (n_samples, n_features)

Data to be discretized.
yNone

Ignored. This parameter exists only for compatibility with Pipeline.    Returns
 self

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(Xt) [source]

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

Xtarray-like of shape (n_samples, n_features)

Transformed data in the binned space.    Returns

Xinvndarray, dtype={np.float32, np.float64}

Data in the original feature space.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Discretize the data.  Parameters

Xarray-like of shape (n_samples, n_features)

Data to be discretized.    Returns

Xt{ndarray, sparse matrix}, dtype={np.float32, np.float64}

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

 Examples using sklearn.preprocessing.KBinsDiscretizer

  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(X, y=None) [source]

Fit the estimator.  Parameters

Xarray-like of shape (n_samples, n_features)

Data to be discretized.
yNone

Ignored. This parameter exists only for compatibility with Pipeline.    Returns
 self


inverse_transform(Xt) [source]

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

Xtarray-like of shape (n_samples, n_features)

Transformed data in the binned space.    Returns

Xinvndarray, dtype={np.float32, np.float64}

Data in the original feature space.


transform(X) [source]

Discretize the data.  Parameters

Xarray-like of shape (n_samples, n_features)

Data to be discretized.    Returns

Xt{ndarray, sparse matrix}, dtype={np.float32, np.float64}

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


sklearn.preprocessing.KernelCenterer
class sklearn.preprocessing.KernelCenterer [source]

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

K_fit_rows_array of shape (n_samples,)

Average of each column of kernel matrix.
K_fit_all_float

Average of kernel matrix.     Examples >>> from sklearn.preprocessing import KernelCenterer
>>> from sklearn.metrics.pairwise import pairwise_kernels
>>> X = [[ 1., -2.,  2.],
...      [ -2.,  1.,  3.],
...      [ 4.,  1., -2.]]
>>> K = pairwise_kernels(X, metric='linear')
>>> K
array([[  9.,   2.,  -2.],
       [  2.,  14., -13.],
       [ -2., -13.,  21.]])
>>> transformer = KernelCenterer().fit(K)
>>> transformer
KernelCenterer()
>>> transformer.transform(K)
array([[  5.,   0.,  -5.],
       [  0.,  14., -14.],
       [ -5., -14.,  19.]])
 Methods
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(K, y=None) [source]

Fit KernelCenterer  Parameters

Kndarray of shape (n_samples, n_samples)

Kernel matrix.
yNone

Ignored.    Returns

selfobject

Fitted transformer.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(K, copy=True) [source]

Center kernel matrix.  Parameters

Kndarray of shape (n_samples1, n_samples2)

Kernel matrix.
copybool, default=True

Set to False to perform inplace computation.    Returns

K_newndarray of shape (n_samples1, n_samples2)


class sklearn.preprocessing.KernelCenterer [source]

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

K_fit_rows_array of shape (n_samples,)

Average of each column of kernel matrix.
K_fit_all_float

Average of kernel matrix.     Examples >>> from sklearn.preprocessing import KernelCenterer
>>> from sklearn.metrics.pairwise import pairwise_kernels
>>> X = [[ 1., -2.,  2.],
...      [ -2.,  1.,  3.],
...      [ 4.,  1., -2.]]
>>> K = pairwise_kernels(X, metric='linear')
>>> K
array([[  9.,   2.,  -2.],
       [  2.,  14., -13.],
       [ -2., -13.,  21.]])
>>> transformer = KernelCenterer().fit(K)
>>> transformer
KernelCenterer()
>>> transformer.transform(K)
array([[  5.,   0.,  -5.],
       [  0.,  14., -14.],
       [ -5., -14.,  19.]])
 Methods
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(K, y=None) [source]

Fit KernelCenterer  Parameters

Kndarray of shape (n_samples, n_samples)

Kernel matrix.
yNone

Ignored.    Returns

selfobject

Fitted transformer.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(K, copy=True) [source]

Center kernel matrix.  Parameters

Kndarray of shape (n_samples1, n_samples2)

Kernel matrix.
copybool, default=True

Set to False to perform inplace computation.    Returns

K_newndarray of shape (n_samples1, n_samples2)


fit(K, y=None) [source]

Fit KernelCenterer  Parameters

Kndarray of shape (n_samples, n_samples)

Kernel matrix.
yNone

Ignored.    Returns

selfobject

Fitted transformer.


fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


transform(K, copy=True) [source]

Center kernel matrix.  Parameters

Kndarray of shape (n_samples1, n_samples2)

Kernel matrix.
copybool, default=True

Set to False to perform inplace computation.    Returns

K_newndarray of shape (n_samples1, n_samples2)


class sklearn.preprocessing.LabelBinarizer(*, neg_label=0, pos_label=1, sparse_output=False) [source]

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

neg_labelint, default=0

Value with which negative labels must be encoded.
pos_labelint, default=1

Value with which positive labels must be encoded.
sparse_outputbool, default=False

True if the returned array from transform is desired to be in sparse CSR format.    Attributes

classes_ndarray of shape (n_classes,)

Holds the label for each class.
y_type_str

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

True if the input data to transform is given as a sparse matrix, False otherwise.      See also
label_binarize

Function to perform the transform operation of LabelBinarizer with fixed classes.
OneHotEncoder

Encode categorical features using a one-hot aka one-of-K scheme.    Examples >>> from sklearn import preprocessing
>>> lb = preprocessing.LabelBinarizer()
>>> lb.fit([1, 2, 6, 4, 2])
LabelBinarizer()
>>> lb.classes_
array([1, 2, 4, 6])
>>> lb.transform([1, 6])
array([[1, 0, 0, 0],
       [0, 0, 0, 1]])
 Binary targets transform to a column vector >>> lb = preprocessing.LabelBinarizer()
>>> lb.fit_transform(['yes', 'no', 'no', 'yes'])
array([[1],
       [0],
       [0],
       [1]])
 Passing a 2D matrix for multilabel classification >>> import numpy as np
>>> lb.fit(np.array([[0, 1, 1], [1, 0, 0]]))
LabelBinarizer()
>>> lb.classes_
array([0, 1, 2])
>>> lb.transform([0, 1, 2, 1])
array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0]])
 Methods
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(y) [source]

Fit label binarizer.  Parameters

yndarray of shape (n_samples,) or (n_samples, n_classes)

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

selfreturns an instance of self.

fit_transform(y) [source]

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

y{ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)

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

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(Y, threshold=None) [source]

Transform binary labels back to multi-class labels.  Parameters

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Target values. All sparse matrices are converted to CSR before inverse transformation.
thresholdfloat, default=None

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

y{ndarray, sparse matrix} of shape (n_samples,)

Target values. Sparse matrix will be of CSR format.     Notes 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_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(y) [source]

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

y{array, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)

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

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.


sklearn.preprocessing.LabelBinarizer
class sklearn.preprocessing.LabelBinarizer(*, neg_label=0, pos_label=1, sparse_output=False) [source]

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

neg_labelint, default=0

Value with which negative labels must be encoded.
pos_labelint, default=1

Value with which positive labels must be encoded.
sparse_outputbool, default=False

True if the returned array from transform is desired to be in sparse CSR format.    Attributes

classes_ndarray of shape (n_classes,)

Holds the label for each class.
y_type_str

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

True if the input data to transform is given as a sparse matrix, False otherwise.      See also
label_binarize

Function to perform the transform operation of LabelBinarizer with fixed classes.
OneHotEncoder

Encode categorical features using a one-hot aka one-of-K scheme.    Examples >>> from sklearn import preprocessing
>>> lb = preprocessing.LabelBinarizer()
>>> lb.fit([1, 2, 6, 4, 2])
LabelBinarizer()
>>> lb.classes_
array([1, 2, 4, 6])
>>> lb.transform([1, 6])
array([[1, 0, 0, 0],
       [0, 0, 0, 1]])
 Binary targets transform to a column vector >>> lb = preprocessing.LabelBinarizer()
>>> lb.fit_transform(['yes', 'no', 'no', 'yes'])
array([[1],
       [0],
       [0],
       [1]])
 Passing a 2D matrix for multilabel classification >>> import numpy as np
>>> lb.fit(np.array([[0, 1, 1], [1, 0, 0]]))
LabelBinarizer()
>>> lb.classes_
array([0, 1, 2])
>>> lb.transform([0, 1, 2, 1])
array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0]])
 Methods
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(y) [source]

Fit label binarizer.  Parameters

yndarray of shape (n_samples,) or (n_samples, n_classes)

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

selfreturns an instance of self.

fit_transform(y) [source]

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

y{ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)

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

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(Y, threshold=None) [source]

Transform binary labels back to multi-class labels.  Parameters

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Target values. All sparse matrices are converted to CSR before inverse transformation.
thresholdfloat, default=None

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

y{ndarray, sparse matrix} of shape (n_samples,)

Target values. Sparse matrix will be of CSR format.     Notes 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_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(y) [source]

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

y{array, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)

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

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.


fit(y) [source]

Fit label binarizer.  Parameters

yndarray of shape (n_samples,) or (n_samples, n_classes)

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

selfreturns an instance of self.


fit_transform(y) [source]

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

y{ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)

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

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.


inverse_transform(Y, threshold=None) [source]

Transform binary labels back to multi-class labels.  Parameters

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Target values. All sparse matrices are converted to CSR before inverse transformation.
thresholdfloat, default=None

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

y{ndarray, sparse matrix} of shape (n_samples,)

Target values. Sparse matrix will be of CSR format.     Notes 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.


transform(y) [source]

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

y{array, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)

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

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.


class sklearn.preprocessing.LabelEncoder [source]

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

classes_ndarray of shape (n_classes,)

Holds the label for each class.      See also
OrdinalEncoder

Encode categorical features using an ordinal encoding scheme.
OneHotEncoder

Encode categorical features as a one-hot numeric array.    Examples LabelEncoder can be used to normalize labels. >>> from sklearn import preprocessing
>>> le = preprocessing.LabelEncoder()
>>> le.fit([1, 2, 2, 6])
LabelEncoder()
>>> le.classes_
array([1, 2, 6])
>>> le.transform([1, 1, 2, 6])
array([0, 0, 1, 2]...)
>>> le.inverse_transform([0, 0, 1, 2])
array([1, 1, 2, 6])
 It can also be used to transform non-numerical labels (as long as they are hashable and comparable) to numerical labels. >>> le = preprocessing.LabelEncoder()
>>> le.fit(["paris", "paris", "tokyo", "amsterdam"])
LabelEncoder()
>>> list(le.classes_)
['amsterdam', 'paris', 'tokyo']
>>> le.transform(["tokyo", "tokyo", "paris"])
array([2, 2, 1]...)
>>> list(le.inverse_transform([2, 2, 1]))
['tokyo', 'tokyo', 'paris']
 Methods
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(y) [source]

Fit label encoder.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

selfreturns an instance of self.

fit_transform(y) [source]

Fit label encoder and return encoded labels.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

yarray-like of shape (n_samples,)

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(y) [source]

Transform labels back to original encoding.  Parameters

yndarray of shape (n_samples,)

Target values.    Returns

yndarray of shape (n_samples,)

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(y) [source]

Transform labels to normalized encoding.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

yarray-like of shape (n_samples,)


sklearn.preprocessing.LabelEncoder
class sklearn.preprocessing.LabelEncoder [source]

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

classes_ndarray of shape (n_classes,)

Holds the label for each class.      See also
OrdinalEncoder

Encode categorical features using an ordinal encoding scheme.
OneHotEncoder

Encode categorical features as a one-hot numeric array.    Examples LabelEncoder can be used to normalize labels. >>> from sklearn import preprocessing
>>> le = preprocessing.LabelEncoder()
>>> le.fit([1, 2, 2, 6])
LabelEncoder()
>>> le.classes_
array([1, 2, 6])
>>> le.transform([1, 1, 2, 6])
array([0, 0, 1, 2]...)
>>> le.inverse_transform([0, 0, 1, 2])
array([1, 1, 2, 6])
 It can also be used to transform non-numerical labels (as long as they are hashable and comparable) to numerical labels. >>> le = preprocessing.LabelEncoder()
>>> le.fit(["paris", "paris", "tokyo", "amsterdam"])
LabelEncoder()
>>> list(le.classes_)
['amsterdam', 'paris', 'tokyo']
>>> le.transform(["tokyo", "tokyo", "paris"])
array([2, 2, 1]...)
>>> list(le.inverse_transform([2, 2, 1]))
['tokyo', 'tokyo', 'paris']
 Methods
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(y) [source]

Fit label encoder.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

selfreturns an instance of self.

fit_transform(y) [source]

Fit label encoder and return encoded labels.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

yarray-like of shape (n_samples,)

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(y) [source]

Transform labels back to original encoding.  Parameters

yndarray of shape (n_samples,)

Target values.    Returns

yndarray of shape (n_samples,)

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(y) [source]

Transform labels to normalized encoding.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

yarray-like of shape (n_samples,)


fit(y) [source]

Fit label encoder.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

selfreturns an instance of self.


fit_transform(y) [source]

Fit label encoder and return encoded labels.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

yarray-like of shape (n_samples,)


inverse_transform(y) [source]

Transform labels back to original encoding.  Parameters

yndarray of shape (n_samples,)

Target values.    Returns

yndarray of shape (n_samples,)


transform(y) [source]

Transform labels to normalized encoding.  Parameters

yarray-like of shape (n_samples,)

Target values.    Returns

yarray-like of shape (n_samples,)


sklearn.preprocessing.label_binarize(y, *, classes, neg_label=0, pos_label=1, sparse_output=False) [source]

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

yarray-like

Sequence of integer labels or multilabel data to encode.
classesarray-like of shape (n_classes,)

Uniquely holds the label for each class.
neg_labelint, default=0

Value with which negative labels must be encoded.
pos_labelint, default=1

Value with which positive labels must be encoded.
sparse_outputbool, default=False,

Set to true if output binary array is desired in CSR sparse format.    Returns

Y{ndarray, sparse matrix} of shape (n_samples, n_classes)

Shape will be (n_samples, 1) for binary problems. Sparse matrix will be of CSR format.      See also
LabelBinarizer

Class used to wrap the functionality of label_binarize and allow for fitting to classes independently of the transform operation.    Examples >>> from sklearn.preprocessing import label_binarize
>>> label_binarize([1, 6], classes=[1, 2, 4, 6])
array([[1, 0, 0, 0],
       [0, 0, 0, 1]])
 The class ordering is preserved: >>> label_binarize([1, 6], classes=[1, 6, 4, 2])
array([[1, 0, 0, 0],
       [0, 1, 0, 0]])
 Binary targets transform to a column vector >>> label_binarize(['yes', 'no', 'no', 'yes'], classes=['no', 'yes'])
array([[1],
       [0],
       [0],
       [1]])


class sklearn.preprocessing.MaxAbsScaler(*, copy=True) [source]

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

copybool, default=True

Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).    Attributes

scale_ndarray of shape (n_features,)

Per feature relative scaling of the data.  New in version 0.17: scale_ attribute.
max_abs_ndarray of shape (n_features,)

Per feature maximum absolute value.
n_samples_seen_int

The number of samples processed by the estimator. Will be reset on new calls to fit, but increments across partial_fit calls.      See also
maxabs_scale

Equivalent function without the estimator API.    Notes 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. Examples >>> from sklearn.preprocessing import MaxAbsScaler
>>> X = [[ 1., -1.,  2.],
...      [ 2.,  0.,  0.],
...      [ 0.,  1., -1.]]
>>> transformer = MaxAbsScaler().fit(X)
>>> transformer
MaxAbsScaler()
>>> transformer.transform(X)
array([[ 0.5, -1. ,  1. ],
       [ 1. ,  0. ,  0. ],
       [ 0. ,  1. , -0.5]])
 Methods
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
fit(X, y=None) [source]

Compute the maximum absolute value to be used for later scaling.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(X) [source]

Scale back the data to the original representation  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data that should be transformed back.    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

Transformed array.

partial_fit(X, y=None) [source]

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

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data used to compute the mean and standard deviation used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Scale the data  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data that should be scaled.    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

Transformed array.


sklearn.preprocessing.MaxAbsScaler
class sklearn.preprocessing.MaxAbsScaler(*, copy=True) [source]

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

copybool, default=True

Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).    Attributes

scale_ndarray of shape (n_features,)

Per feature relative scaling of the data.  New in version 0.17: scale_ attribute.
max_abs_ndarray of shape (n_features,)

Per feature maximum absolute value.
n_samples_seen_int

The number of samples processed by the estimator. Will be reset on new calls to fit, but increments across partial_fit calls.      See also
maxabs_scale

Equivalent function without the estimator API.    Notes 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. Examples >>> from sklearn.preprocessing import MaxAbsScaler
>>> X = [[ 1., -1.,  2.],
...      [ 2.,  0.,  0.],
...      [ 0.,  1., -1.]]
>>> transformer = MaxAbsScaler().fit(X)
>>> transformer
MaxAbsScaler()
>>> transformer.transform(X)
array([[ 0.5, -1. ,  1. ],
       [ 1. ,  0. ,  0. ],
       [ 0. ,  1. , -0.5]])
 Methods
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
fit(X, y=None) [source]

Compute the maximum absolute value to be used for later scaling.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(X) [source]

Scale back the data to the original representation  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data that should be transformed back.    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

Transformed array.

partial_fit(X, y=None) [source]

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

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data used to compute the mean and standard deviation used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Scale the data  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data that should be scaled.    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

Transformed array.

 Examples using sklearn.preprocessing.MaxAbsScaler

  Compare the effect of different scalers on data with outliers


fit(X, y=None) [source]

Compute the maximum absolute value to be used for later scaling.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.


fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


inverse_transform(X) [source]

Scale back the data to the original representation  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data that should be transformed back.    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

Transformed array.


partial_fit(X, y=None) [source]

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

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data used to compute the mean and standard deviation used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.


set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


transform(X) [source]

Scale the data  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data that should be scaled.    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

Transformed array.


sklearn.preprocessing.maxabs_scale(X, *, axis=0, copy=True) [source]

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

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data.
axisint, default=0

axis used to scale along. If 0, independently scale each feature, otherwise (if 1) scale each sample.
copybool, default=True

Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).    Returns

X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)

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
MaxAbsScaler

Performs scaling to the [-1, 1] range using the Transformer API (e.g. as part of a preprocessing Pipeline).    Notes 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.


class sklearn.preprocessing.MinMaxScaler(feature_range=0, 1, *, copy=True, clip=False) [source]

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: X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
 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.  Parameters

feature_rangetuple (min, max), default=(0, 1)

Desired range of transformed data.
copybool, default=True

Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array).  clip: bool, default=False

Set to True to clip transformed values of held-out data to provided feature range.  New in version 0.24.     Attributes

min_ndarray of shape (n_features,)

Per feature adjustment for minimum. Equivalent to min - X.min(axis=0) * self.scale_
scale_ndarray of shape (n_features,)

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.
data_min_ndarray of shape (n_features,)

Per feature minimum seen in the data  New in version 0.17: data_min_
data_max_ndarray of shape (n_features,)

Per feature maximum seen in the data  New in version 0.17: data_max_
data_range_ndarray of shape (n_features,)

Per feature range (data_max_ - data_min_) seen in the data  New in version 0.17: data_range_
n_samples_seen_int

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
minmax_scale

Equivalent function without the estimator API.    Notes 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. Examples >>> from sklearn.preprocessing import MinMaxScaler
>>> data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
>>> scaler = MinMaxScaler()
>>> print(scaler.fit(data))
MinMaxScaler()
>>> print(scaler.data_max_)
[ 1. 18.]
>>> print(scaler.transform(data))
[[0.   0.  ]
 [0.25 0.25]
 [0.5  0.5 ]
 [1.   1.  ]]
>>> print(scaler.transform([[2, 2]]))
[[1.5 0. ]]
 Methods
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.
fit(X, y=None) [source]

Compute the minimum and maximum to be used for later scaling.  Parameters

Xarray-like of shape (n_samples, n_features)

The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(X) [source]

Undo the scaling of X according to feature_range.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data that will be transformed. It cannot be sparse.    Returns

Xtndarray of shape (n_samples, n_features)

Transformed data.

partial_fit(X, y=None) [source]

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

Xarray-like of shape (n_samples, n_features)

The data used to compute the mean and standard deviation used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Scale features of X according to feature_range.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data that will be transformed.    Returns

Xtndarray of shape (n_samples, n_features)

Transformed data.


sklearn.preprocessing.MinMaxScaler
class sklearn.preprocessing.MinMaxScaler(feature_range=0, 1, *, copy=True, clip=False) [source]

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: X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
 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.  Parameters

feature_rangetuple (min, max), default=(0, 1)

Desired range of transformed data.
copybool, default=True

Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array).  clip: bool, default=False

Set to True to clip transformed values of held-out data to provided feature range.  New in version 0.24.     Attributes

min_ndarray of shape (n_features,)

Per feature adjustment for minimum. Equivalent to min - X.min(axis=0) * self.scale_
scale_ndarray of shape (n_features,)

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.
data_min_ndarray of shape (n_features,)

Per feature minimum seen in the data  New in version 0.17: data_min_
data_max_ndarray of shape (n_features,)

Per feature maximum seen in the data  New in version 0.17: data_max_
data_range_ndarray of shape (n_features,)

Per feature range (data_max_ - data_min_) seen in the data  New in version 0.17: data_range_
n_samples_seen_int

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
minmax_scale

Equivalent function without the estimator API.    Notes 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. Examples >>> from sklearn.preprocessing import MinMaxScaler
>>> data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
>>> scaler = MinMaxScaler()
>>> print(scaler.fit(data))
MinMaxScaler()
>>> print(scaler.data_max_)
[ 1. 18.]
>>> print(scaler.transform(data))
[[0.   0.  ]
 [0.25 0.25]
 [0.5  0.5 ]
 [1.   1.  ]]
>>> print(scaler.transform([[2, 2]]))
[[1.5 0. ]]
 Methods
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.
fit(X, y=None) [source]

Compute the minimum and maximum to be used for later scaling.  Parameters

Xarray-like of shape (n_samples, n_features)

The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(X) [source]

Undo the scaling of X according to feature_range.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data that will be transformed. It cannot be sparse.    Returns

Xtndarray of shape (n_samples, n_features)

Transformed data.

partial_fit(X, y=None) [source]

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

Xarray-like of shape (n_samples, n_features)

The data used to compute the mean and standard deviation used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Scale features of X according to feature_range.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data that will be transformed.    Returns

Xtndarray of shape (n_samples, n_features)

Transformed data.

 Examples using sklearn.preprocessing.MinMaxScaler

  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


fit(X, y=None) [source]

Compute the minimum and maximum to be used for later scaling.  Parameters

Xarray-like of shape (n_samples, n_features)

The data used to compute the per-feature minimum and maximum used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.


inverse_transform(X) [source]

Undo the scaling of X according to feature_range.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data that will be transformed. It cannot be sparse.    Returns

Xtndarray of shape (n_samples, n_features)

Transformed data.


partial_fit(X, y=None) [source]

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

Xarray-like of shape (n_samples, n_features)

The data used to compute the mean and standard deviation used for later scaling along the features axis.
yNone

Ignored.    Returns

selfobject

Fitted scaler.


transform(X) [source]

Scale features of X according to feature_range.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data that will be transformed.    Returns

Xtndarray of shape (n_samples, n_features)

Transformed data.


sklearn.preprocessing.minmax_scale(X, feature_range=0, 1, *, axis=0, copy=True) [source]

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): X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
 where min, max = feature_range. The transformation is calculated as (when axis=0): X_scaled = scale * X + min - X.min(axis=0) * scale
where scale = (max - min) / (X.max(axis=0) - X.min(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.   Parameters

Xarray-like of shape (n_samples, n_features)

The data.
feature_rangetuple (min, max), default=(0, 1)

Desired range of transformed data.
axisint, default=0

Axis used to scale along. If 0, independently scale each feature, otherwise (if 1) scale each sample.
copybool, default=True

Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).    Returns

X_trndarray of shape (n_samples, n_features)

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
MinMaxScaler

Performs scaling to a given range using the Transformer API (e.g. as part of a preprocessing Pipeline).    Notes For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.


class sklearn.preprocessing.MultiLabelBinarizer(*, classes=None, sparse_output=False) [source]

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

classesarray-like of shape (n_classes,), default=None

Indicates an ordering for the class labels. All entries should be unique (cannot contain duplicate classes).
sparse_outputbool, default=False

Set to True if output binary array is desired in CSR sparse format.    Attributes

classes_ndarray of shape (n_classes,)

A copy of the classes parameter when provided. Otherwise it corresponds to the sorted set of classes found when fitting.      See also
OneHotEncoder

Encode categorical features using a one-hot aka one-of-K scheme.    Examples >>> from sklearn.preprocessing import MultiLabelBinarizer
>>> mlb = MultiLabelBinarizer()
>>> mlb.fit_transform([(1, 2), (3,)])
array([[1, 1, 0],
       [0, 0, 1]])
>>> mlb.classes_
array([1, 2, 3])
 >>> mlb.fit_transform([{'sci-fi', 'thriller'}, {'comedy'}])
array([[0, 1, 1],
       [1, 0, 0]])
>>> list(mlb.classes_)
['comedy', 'sci-fi', 'thriller']
 A common mistake is to pass in a list, which leads to the following issue: >>> mlb = MultiLabelBinarizer()
>>> mlb.fit(['sci-fi', 'thriller', 'comedy'])
MultiLabelBinarizer()
>>> mlb.classes_
array(['-', 'c', 'd', 'e', 'f', 'h', 'i', 'l', 'm', 'o', 'r', 's', 't',
    'y'], dtype=object)
 To correct this, the list of labels should be passed in as: >>> mlb = MultiLabelBinarizer()
>>> mlb.fit([['sci-fi', 'thriller', 'comedy']])
MultiLabelBinarizer()
>>> mlb.classes_
array(['comedy', 'sci-fi', 'thriller'], dtype=object)
 Methods
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(y) [source]

Fit the label sets binarizer, storing classes_.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

selfreturns this MultiLabelBinarizer instance

fit_transform(y) [source]

Fit the label sets binarizer and transform the given label sets.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

y_indicator{ndarray, sparse matrix} of shape (n_samples, n_classes)

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_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(yt) [source]

Transform the given indicator matrix into label sets.  Parameters

yt{ndarray, sparse matrix} of shape (n_samples, n_classes)

A matrix containing only 1s ands 0s.    Returns

ylist of tuples

The set of labels for each sample such that y[i] consists of classes_[j] for each yt[i, j] == 1.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(y) [source]

Transform the given label sets.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

y_indicatorarray or CSR matrix, shape (n_samples, n_classes)

A matrix such that y_indicator[i, j] = 1 iff classes_[j] is in y[i], and 0 otherwise.


sklearn.preprocessing.MultiLabelBinarizer
class sklearn.preprocessing.MultiLabelBinarizer(*, classes=None, sparse_output=False) [source]

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

classesarray-like of shape (n_classes,), default=None

Indicates an ordering for the class labels. All entries should be unique (cannot contain duplicate classes).
sparse_outputbool, default=False

Set to True if output binary array is desired in CSR sparse format.    Attributes

classes_ndarray of shape (n_classes,)

A copy of the classes parameter when provided. Otherwise it corresponds to the sorted set of classes found when fitting.      See also
OneHotEncoder

Encode categorical features using a one-hot aka one-of-K scheme.    Examples >>> from sklearn.preprocessing import MultiLabelBinarizer
>>> mlb = MultiLabelBinarizer()
>>> mlb.fit_transform([(1, 2), (3,)])
array([[1, 1, 0],
       [0, 0, 1]])
>>> mlb.classes_
array([1, 2, 3])
 >>> mlb.fit_transform([{'sci-fi', 'thriller'}, {'comedy'}])
array([[0, 1, 1],
       [1, 0, 0]])
>>> list(mlb.classes_)
['comedy', 'sci-fi', 'thriller']
 A common mistake is to pass in a list, which leads to the following issue: >>> mlb = MultiLabelBinarizer()
>>> mlb.fit(['sci-fi', 'thriller', 'comedy'])
MultiLabelBinarizer()
>>> mlb.classes_
array(['-', 'c', 'd', 'e', 'f', 'h', 'i', 'l', 'm', 'o', 'r', 's', 't',
    'y'], dtype=object)
 To correct this, the list of labels should be passed in as: >>> mlb = MultiLabelBinarizer()
>>> mlb.fit([['sci-fi', 'thriller', 'comedy']])
MultiLabelBinarizer()
>>> mlb.classes_
array(['comedy', 'sci-fi', 'thriller'], dtype=object)
 Methods
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(y) [source]

Fit the label sets binarizer, storing classes_.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

selfreturns this MultiLabelBinarizer instance

fit_transform(y) [source]

Fit the label sets binarizer and transform the given label sets.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

y_indicator{ndarray, sparse matrix} of shape (n_samples, n_classes)

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_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(yt) [source]

Transform the given indicator matrix into label sets.  Parameters

yt{ndarray, sparse matrix} of shape (n_samples, n_classes)

A matrix containing only 1s ands 0s.    Returns

ylist of tuples

The set of labels for each sample such that y[i] consists of classes_[j] for each yt[i, j] == 1.

set_params(**params) [source]

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

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(y) [source]

Transform the given label sets.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

y_indicatorarray or CSR matrix, shape (n_samples, n_classes)

A matrix such that y_indicator[i, j] = 1 iff classes_[j] is in y[i], and 0 otherwise.


fit(y) [source]

Fit the label sets binarizer, storing classes_.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

selfreturns this MultiLabelBinarizer instance


fit_transform(y) [source]

Fit the label sets binarizer and transform the given label sets.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

y_indicator{ndarray, sparse matrix} of shape (n_samples, n_classes)

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_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


inverse_transform(yt) [source]

Transform the given indicator matrix into label sets.  Parameters

yt{ndarray, sparse matrix} of shape (n_samples, n_classes)

A matrix containing only 1s ands 0s.    Returns

ylist of tuples

The set of labels for each sample such that y[i] consists of classes_[j] for each yt[i, j] == 1.


transform(y) [source]

Transform the given label sets.  Parameters

yiterable of iterables

A set of labels (any orderable and hashable object) for each sample. If the classes parameter is set, y will not be iterated.    Returns

y_indicatorarray or CSR matrix, shape (n_samples, n_classes)

A matrix such that y_indicator[i, j] = 1 iff classes_[j] is in y[i], and 0 otherwise.


sklearn.preprocessing.normalize(X, norm='l2', *, axis=1, copy=True, return_norm=False) [source]

Scale input vectors individually to unit norm (vector length). Read more in the User Guide.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

The data to normalize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
norm{‘l1’, ‘l2’, ‘max’}, default=’l2’

The norm to use to normalize each non zero sample (or each non-zero feature if axis is 0).
axis{0, 1}, default=1

axis used to normalize the data along. If 1, independently normalize each sample, otherwise (if 0) normalize each feature.
copybool, default=True

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).
return_normbool, default=False

whether to return the computed norms    Returns

X{ndarray, sparse matrix} of shape (n_samples, n_features)

Normalized input X.
normsndarray of shape (n_samples, ) if axis=1 else (n_features, )

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
Normalizer

Performs normalization using the Transformer API (e.g. as part of a preprocessing Pipeline).    Notes For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py.