doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
predict_proba(X) [source]
Apply transforms, and predict_proba of the final estimator Parameters
Xiterable
Data to predict on. Must fulfill input requirements of first step of the pipeline. Returns
y_probaarray-like of shape (n_samples, n_classes) | sklearn.modules.generated.sklearn.pipeline.pipeline#sklearn.pipeline.Pipeline.predict_proba |
score(X, y=None, sample_weight=None) [source]
Apply transforms, and score with the final estimator Parameters
Xiterable
Data to predict on. Must fulfill input requirements of first step of the pipeline.
yiterable, default=None
Targets used for scoring. Must fulfill label requirements for all steps of the pipeline.
sample_weightarray-like, default=None
If not None, this argument is passed as sample_weight keyword argument to the score method of the final estimator. Returns
scorefloat | sklearn.modules.generated.sklearn.pipeline.pipeline#sklearn.pipeline.Pipeline.score |
score_samples(X) [source]
Apply transforms, and score_samples of the final estimator. Parameters
Xiterable
Data to predict on. Must fulfill input requirements of first step of the pipeline. Returns
y_scorendarray of shape (n_samples,) | sklearn.modules.generated.sklearn.pipeline.pipeline#sklearn.pipeline.Pipeline.score_samples |
set_params(**kwargs) [source]
Set the parameters of this estimator. Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in steps. Returns
self | sklearn.modules.generated.sklearn.pipeline.pipeline#sklearn.pipeline.Pipeline.set_params |
property transform
Apply transforms, and transform with the final estimator This also works where final estimator is None: all prior transformations are applied. Parameters
Xiterable
Data to transform. Must fulfill input requirements of first step of the pipeline. Returns
Xtarray-like of shape (n_samples, n_transformed_features) | sklearn.modules.generated.sklearn.pipeline.pipeline#sklearn.pipeline.Pipeline.transform |
sklearn.preprocessing.add_dummy_feature(X, value=1.0) [source]
Augment dataset with an additional dummy feature. This is useful for fitting an intercept term with implementations which cannot otherwise fit it directly. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Data.
valuefloat
Value to use for the dummy feature. Returns
X{ndarray, sparse matrix} of shape (n_samples, n_features + 1)
Same data with dummy feature added as first column. Examples >>> from sklearn.preprocessing import add_dummy_feature
>>> add_dummy_feature([[0, 1], [1, 0]])
array([[1., 0., 1.],
[1., 1., 0.]]) | sklearn.modules.generated.sklearn.preprocessing.add_dummy_feature#sklearn.preprocessing.add_dummy_feature |
sklearn.preprocessing.binarize(X, *, threshold=0.0, copy=True) [source]
Boolean thresholding of array-like or scipy.sparse matrix. Read more in the User Guide. 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 or CSC format to avoid an un-necessary copy.
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 / CSC matrix and if axis is 1). Returns
X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)
The transformed data. See also
Binarizer
Performs binarization using the Transformer API (e.g. as part of a preprocessing Pipeline). | sklearn.modules.generated.sklearn.preprocessing.binarize#sklearn.preprocessing.binarize |
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. | sklearn.modules.generated.sklearn.preprocessing.binarizer#sklearn.preprocessing.Binarizer |
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. | sklearn.modules.generated.sklearn.preprocessing.binarizer |
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. | sklearn.modules.generated.sklearn.preprocessing.binarizer#sklearn.preprocessing.Binarizer.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.binarizer#sklearn.preprocessing.Binarizer.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.binarizer#sklearn.preprocessing.Binarizer.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.binarizer#sklearn.preprocessing.Binarizer.set_params |
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. | sklearn.modules.generated.sklearn.preprocessing.binarizer#sklearn.preprocessing.Binarizer.transform |
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.modules.generated.sklearn.preprocessing.functiontransformer#sklearn.preprocessing.FunctionTransformer |
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 | sklearn.modules.generated.sklearn.preprocessing.functiontransformer |
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 | sklearn.modules.generated.sklearn.preprocessing.functiontransformer#sklearn.preprocessing.FunctionTransformer.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.functiontransformer#sklearn.preprocessing.FunctionTransformer.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.functiontransformer#sklearn.preprocessing.FunctionTransformer.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.functiontransformer#sklearn.preprocessing.FunctionTransformer.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. | sklearn.modules.generated.sklearn.preprocessing.functiontransformer#sklearn.preprocessing.FunctionTransformer.set_params |
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.modules.generated.sklearn.preprocessing.functiontransformer#sklearn.preprocessing.FunctionTransformer.transform |
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.modules.generated.sklearn.preprocessing.kbinsdiscretizer#sklearn.preprocessing.KBinsDiscretizer |
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 | sklearn.modules.generated.sklearn.preprocessing.kbinsdiscretizer |
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 | sklearn.modules.generated.sklearn.preprocessing.kbinsdiscretizer#sklearn.preprocessing.KBinsDiscretizer.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.kbinsdiscretizer#sklearn.preprocessing.KBinsDiscretizer.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.kbinsdiscretizer#sklearn.preprocessing.KBinsDiscretizer.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.kbinsdiscretizer#sklearn.preprocessing.KBinsDiscretizer.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. | sklearn.modules.generated.sklearn.preprocessing.kbinsdiscretizer#sklearn.preprocessing.KBinsDiscretizer.set_params |
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.modules.generated.sklearn.preprocessing.kbinsdiscretizer#sklearn.preprocessing.KBinsDiscretizer.transform |
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) | sklearn.modules.generated.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) | sklearn.modules.generated.sklearn.preprocessing.kernelcenterer#sklearn.preprocessing.KernelCenterer |
fit(K, y=None) [source]
Fit KernelCenterer Parameters
Kndarray of shape (n_samples, n_samples)
Kernel matrix.
yNone
Ignored. Returns
selfobject
Fitted transformer. | sklearn.modules.generated.sklearn.preprocessing.kernelcenterer#sklearn.preprocessing.KernelCenterer.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.kernelcenterer#sklearn.preprocessing.KernelCenterer.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.kernelcenterer#sklearn.preprocessing.KernelCenterer.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.kernelcenterer#sklearn.preprocessing.KernelCenterer.set_params |
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) | sklearn.modules.generated.sklearn.preprocessing.kernelcenterer#sklearn.preprocessing.KernelCenterer.transform |
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.modules.generated.sklearn.preprocessing.labelbinarizer#sklearn.preprocessing.LabelBinarizer |
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. | sklearn.modules.generated.sklearn.preprocessing.labelbinarizer |
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. | sklearn.modules.generated.sklearn.preprocessing.labelbinarizer#sklearn.preprocessing.LabelBinarizer.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.labelbinarizer#sklearn.preprocessing.LabelBinarizer.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.labelbinarizer#sklearn.preprocessing.LabelBinarizer.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.labelbinarizer#sklearn.preprocessing.LabelBinarizer.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. | sklearn.modules.generated.sklearn.preprocessing.labelbinarizer#sklearn.preprocessing.LabelBinarizer.set_params |
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.modules.generated.sklearn.preprocessing.labelbinarizer#sklearn.preprocessing.LabelBinarizer.transform |
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.modules.generated.sklearn.preprocessing.labelencoder#sklearn.preprocessing.LabelEncoder |
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,) | sklearn.modules.generated.sklearn.preprocessing.labelencoder |
fit(y) [source]
Fit label encoder. Parameters
yarray-like of shape (n_samples,)
Target values. Returns
selfreturns an instance of self. | sklearn.modules.generated.sklearn.preprocessing.labelencoder#sklearn.preprocessing.LabelEncoder.fit |
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,) | sklearn.modules.generated.sklearn.preprocessing.labelencoder#sklearn.preprocessing.LabelEncoder.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.labelencoder#sklearn.preprocessing.LabelEncoder.get_params |
inverse_transform(y) [source]
Transform labels back to original encoding. Parameters
yndarray of shape (n_samples,)
Target values. Returns
yndarray of shape (n_samples,) | sklearn.modules.generated.sklearn.preprocessing.labelencoder#sklearn.preprocessing.LabelEncoder.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. | sklearn.modules.generated.sklearn.preprocessing.labelencoder#sklearn.preprocessing.LabelEncoder.set_params |
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.modules.generated.sklearn.preprocessing.labelencoder#sklearn.preprocessing.LabelEncoder.transform |
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]]) | sklearn.modules.generated.sklearn.preprocessing.label_binarize#sklearn.preprocessing.label_binarize |
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.modules.generated.sklearn.preprocessing.maxabsscaler#sklearn.preprocessing.MaxAbsScaler |
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 | sklearn.modules.generated.sklearn.preprocessing.maxabsscaler |
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. | sklearn.modules.generated.sklearn.preprocessing.maxabsscaler#sklearn.preprocessing.MaxAbsScaler.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.maxabsscaler#sklearn.preprocessing.MaxAbsScaler.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.maxabsscaler#sklearn.preprocessing.MaxAbsScaler.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.maxabsscaler#sklearn.preprocessing.MaxAbsScaler.inverse_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.maxabsscaler#sklearn.preprocessing.MaxAbsScaler.partial_fit |
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. | sklearn.modules.generated.sklearn.preprocessing.maxabsscaler#sklearn.preprocessing.MaxAbsScaler.set_params |
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.modules.generated.sklearn.preprocessing.maxabsscaler#sklearn.preprocessing.MaxAbsScaler.transform |
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. | sklearn.modules.generated.sklearn.preprocessing.maxabs_scale#sklearn.preprocessing.maxabs_scale |
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.modules.generated.sklearn.preprocessing.minmaxscaler#sklearn.preprocessing.MinMaxScaler |
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 | sklearn.modules.generated.sklearn.preprocessing.minmaxscaler |
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. | sklearn.modules.generated.sklearn.preprocessing.minmaxscaler#sklearn.preprocessing.MinMaxScaler.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.minmaxscaler#sklearn.preprocessing.MinMaxScaler.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.minmaxscaler#sklearn.preprocessing.MinMaxScaler.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.minmaxscaler#sklearn.preprocessing.MinMaxScaler.inverse_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.minmaxscaler#sklearn.preprocessing.MinMaxScaler.partial_fit |
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. | sklearn.modules.generated.sklearn.preprocessing.minmaxscaler#sklearn.preprocessing.MinMaxScaler.set_params |
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.modules.generated.sklearn.preprocessing.minmaxscaler#sklearn.preprocessing.MinMaxScaler.transform |
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. | sklearn.modules.generated.sklearn.preprocessing.minmax_scale#sklearn.preprocessing.minmax_scale |
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.modules.generated.sklearn.preprocessing.multilabelbinarizer#sklearn.preprocessing.MultiLabelBinarizer |
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. | sklearn.modules.generated.sklearn.preprocessing.multilabelbinarizer |
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 | sklearn.modules.generated.sklearn.preprocessing.multilabelbinarizer#sklearn.preprocessing.MultiLabelBinarizer.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.multilabelbinarizer#sklearn.preprocessing.MultiLabelBinarizer.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.multilabelbinarizer#sklearn.preprocessing.MultiLabelBinarizer.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.multilabelbinarizer#sklearn.preprocessing.MultiLabelBinarizer.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. | sklearn.modules.generated.sklearn.preprocessing.multilabelbinarizer#sklearn.preprocessing.MultiLabelBinarizer.set_params |
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.modules.generated.sklearn.preprocessing.multilabelbinarizer#sklearn.preprocessing.MultiLabelBinarizer.transform |
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. | sklearn.modules.generated.sklearn.preprocessing.normalize#sklearn.preprocessing.normalize |
class sklearn.preprocessing.Normalizer(norm='l2', *, copy=True) [source]
Normalize samples individually to unit norm. Each sample (i.e. each row of the data matrix) with at least one non zero component is rescaled independently of other samples so that its norm (l1, l2 or inf) equals one. This transformer is able to work both with dense numpy arrays and scipy.sparse matrix (use CSR format if you want to avoid the burden of a copy / conversion). Scaling inputs to unit norms is a common operation for text classification or clustering for instance. For instance the dot product of two l2-normalized TF-IDF vectors is the cosine similarity of the vectors and is the base similarity metric for the Vector Space Model commonly used by the Information Retrieval community. Read more in the User Guide. Parameters
norm{‘l1’, ‘l2’, ‘max’}, default=’l2’
The norm to use to normalize each non zero sample. If norm=’max’ is used, values will be rescaled by the maximum of the absolute values.
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). See also
normalize
Equivalent function without the estimator API. Notes This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline. For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py. Examples >>> from sklearn.preprocessing import Normalizer
>>> X = [[4, 1, 2, 2],
... [1, 3, 9, 3],
... [5, 7, 5, 1]]
>>> transformer = Normalizer().fit(X) # fit does nothing.
>>> transformer
Normalizer()
>>> transformer.transform(X)
array([[0.8, 0.2, 0.4, 0.4],
[0.1, 0.3, 0.9, 0.3],
[0.5, 0.7, 0.5, 0.1]])
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]) Scale each non zero row of X to unit norm
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 to estimate the normalization parameters.
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]
Scale each non zero row of X to unit norm Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The data to normalize, row by row. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
copybool, default=None
Copy the input X or not. Returns
X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)
Transformed array. | sklearn.modules.generated.sklearn.preprocessing.normalizer#sklearn.preprocessing.Normalizer |
sklearn.preprocessing.Normalizer
class sklearn.preprocessing.Normalizer(norm='l2', *, copy=True) [source]
Normalize samples individually to unit norm. Each sample (i.e. each row of the data matrix) with at least one non zero component is rescaled independently of other samples so that its norm (l1, l2 or inf) equals one. This transformer is able to work both with dense numpy arrays and scipy.sparse matrix (use CSR format if you want to avoid the burden of a copy / conversion). Scaling inputs to unit norms is a common operation for text classification or clustering for instance. For instance the dot product of two l2-normalized TF-IDF vectors is the cosine similarity of the vectors and is the base similarity metric for the Vector Space Model commonly used by the Information Retrieval community. Read more in the User Guide. Parameters
norm{‘l1’, ‘l2’, ‘max’}, default=’l2’
The norm to use to normalize each non zero sample. If norm=’max’ is used, values will be rescaled by the maximum of the absolute values.
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). See also
normalize
Equivalent function without the estimator API. Notes This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline. For a comparison of the different scalers, transformers, and normalizers, see examples/preprocessing/plot_all_scaling.py. Examples >>> from sklearn.preprocessing import Normalizer
>>> X = [[4, 1, 2, 2],
... [1, 3, 9, 3],
... [5, 7, 5, 1]]
>>> transformer = Normalizer().fit(X) # fit does nothing.
>>> transformer
Normalizer()
>>> transformer.transform(X)
array([[0.8, 0.2, 0.4, 0.4],
[0.1, 0.3, 0.9, 0.3],
[0.5, 0.7, 0.5, 0.1]])
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]) Scale each non zero row of X to unit norm
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 to estimate the normalization parameters.
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]
Scale each non zero row of X to unit norm Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The data to normalize, row by row. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
copybool, default=None
Copy the input X or not. Returns
X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)
Transformed array.
Examples using sklearn.preprocessing.Normalizer
Scalable learning with polynomial kernel aproximation
Compare the effect of different scalers on data with outliers
Clustering text documents using k-means | sklearn.modules.generated.sklearn.preprocessing.normalizer |
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 to estimate the normalization parameters.
yNone
Ignored. Returns
selfobject
Fitted transformer. | sklearn.modules.generated.sklearn.preprocessing.normalizer#sklearn.preprocessing.Normalizer.fit |
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. | sklearn.modules.generated.sklearn.preprocessing.normalizer#sklearn.preprocessing.Normalizer.fit_transform |
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. | sklearn.modules.generated.sklearn.preprocessing.normalizer#sklearn.preprocessing.Normalizer.get_params |
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. | sklearn.modules.generated.sklearn.preprocessing.normalizer#sklearn.preprocessing.Normalizer.set_params |
transform(X, copy=None) [source]
Scale each non zero row of X to unit norm Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The data to normalize, row by row. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy.
copybool, default=None
Copy the input X or not. Returns
X_tr{ndarray, sparse matrix} of shape (n_samples, n_features)
Transformed array. | sklearn.modules.generated.sklearn.preprocessing.normalizer#sklearn.preprocessing.Normalizer.transform |
class sklearn.preprocessing.OneHotEncoder(*, categories='auto', drop=None, sparse=True, dtype=<class 'numpy.float64'>, handle_unknown='error') [source]
Encode categorical features as a one-hot numeric array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka ‘one-of-K’ or ‘dummy’) encoding scheme. This creates a binary column for each category and returns a sparse matrix or dense array (depending on the sparse parameter) By default, the encoder derives the categories based on the unique values in each feature. Alternatively, you can also specify the categories manually. This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels. Note: a one-hot encoding of y labels should use a LabelBinarizer instead. Read more in the User Guide. Changed in version 0.20. Parameters
categories‘auto’ or a list of array-like, default=’auto’
Categories (unique values) per feature: ‘auto’ : Determine categories automatically from the training data. list : categories[i] holds the categories expected in the ith column. The passed categories should not mix strings and numeric values within a single feature, and should be sorted in case of numeric values. The used categories can be found in the categories_ attribute. New in version 0.20.
drop{‘first’, ‘if_binary’} or a array-like of shape (n_features,), default=None
Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into a neural network or an unregularized regression. However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models. None : retain all features (the default). ‘first’ : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. ‘if_binary’ : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. array : drop[i] is the category in feature X[:, i] that should be dropped. Changed in version 0.23: Added option ‘if_binary’.
sparsebool, default=True
Will return sparse matrix if set True else will return an array.
dtypenumber type, default=float
Desired dtype of output.
handle_unknown{‘error’, ‘ignore’}, default=’error’
Whether to raise an error or ignore if an unknown categorical feature is present during transform (default is to raise). When this parameter is set to ‘ignore’ and an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as None. Attributes
categories_list of arrays
The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of transform). This includes the category specified in drop (if any).
drop_idx_array of shape (n_features,)
drop_idx_[i] is the index in categories_[i] of the category to be dropped for each feature.
drop_idx_[i] = None if no category is to be dropped from the feature with index i, e.g. when drop='if_binary' and the feature isn’t binary.
drop_idx_ = None if all the transformed features will be retained. Changed in version 0.23: Added the possibility to contain None values. See also
OrdinalEncoder
Performs an ordinal (integer) encoding of the categorical features.
sklearn.feature_extraction.DictVectorizer
Performs a one-hot encoding of dictionary items (also handles string-valued features).
sklearn.feature_extraction.FeatureHasher
Performs an approximate one-hot encoding of dictionary items or strings.
LabelBinarizer
Binarizes labels in a one-vs-all fashion.
MultiLabelBinarizer
Transforms between iterable of iterables and a multilabel format, e.g. a (samples x classes) binary matrix indicating the presence of a class label. Examples Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to a binary one-hot encoding. >>> from sklearn.preprocessing import OneHotEncoder
One can discard categories not seen during fit: >>> enc = OneHotEncoder(handle_unknown='ignore')
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
OneHotEncoder(handle_unknown='ignore')
>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 1], ['Male', 4]]).toarray()
array([[1., 0., 1., 0., 0.],
[0., 1., 0., 0., 0.]])
>>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]])
array([['Male', 1],
[None, 2]], dtype=object)
>>> enc.get_feature_names(['gender', 'group'])
array(['gender_Female', 'gender_Male', 'group_1', 'group_2', 'group_3'],
dtype=object)
One can always drop the first column for each feature: >>> drop_enc = OneHotEncoder(drop='first').fit(X)
>>> drop_enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> drop_enc.transform([['Female', 1], ['Male', 2]]).toarray()
array([[0., 0., 0.],
[1., 1., 0.]])
Or drop a column for feature only having 2 categories: >>> drop_binary_enc = OneHotEncoder(drop='if_binary').fit(X)
>>> drop_binary_enc.transform([['Female', 1], ['Male', 2]]).toarray()
array([[0., 1., 0., 0.],
[1., 0., 1., 0.]])
Methods
fit(X[, y]) Fit OneHotEncoder to X.
fit_transform(X[, y]) Fit OneHotEncoder to X, then transform X.
get_feature_names([input_features]) Return feature names for output features.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Convert the data back to the original representation.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X using one-hot encoding.
fit(X, y=None) [source]
Fit OneHotEncoder to X. Parameters
Xarray-like, shape [n_samples, n_features]
The data to determine the categories of each feature.
yNone
Ignored. This parameter exists only for compatibility with Pipeline. Returns
self
fit_transform(X, y=None) [source]
Fit OneHotEncoder to X, then transform X. Equivalent to fit(X).transform(X) but more convenient. Parameters
Xarray-like, shape [n_samples, n_features]
The data to encode.
yNone
Ignored. This parameter exists only for compatibility with Pipeline. Returns
X_outsparse matrix if sparse=True else a 2-d array
Transformed input.
get_feature_names(input_features=None) [source]
Return feature names for output features. Parameters
input_featureslist of str of shape (n_features,)
String names for input features if available. By default, “x0”, “x1”, … “xn_features” is used. Returns
output_feature_namesndarray of shape (n_output_features,)
Array of feature names.
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]
Convert the data back to the original representation. In case unknown categories are encountered (all zeros in the one-hot encoding), None is used to represent this category. Parameters
Xarray-like or sparse matrix, shape [n_samples, n_encoded_features]
The transformed data. Returns
X_trarray-like, shape [n_samples, n_features]
Inverse transformed array.
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 one-hot encoding. Parameters
Xarray-like, shape [n_samples, n_features]
The data to encode. Returns
X_outsparse matrix if sparse=True else a 2-d array
Transformed input. | sklearn.modules.generated.sklearn.preprocessing.onehotencoder#sklearn.preprocessing.OneHotEncoder |
sklearn.preprocessing.OneHotEncoder
class sklearn.preprocessing.OneHotEncoder(*, categories='auto', drop=None, sparse=True, dtype=<class 'numpy.float64'>, handle_unknown='error') [source]
Encode categorical features as a one-hot numeric array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka ‘one-of-K’ or ‘dummy’) encoding scheme. This creates a binary column for each category and returns a sparse matrix or dense array (depending on the sparse parameter) By default, the encoder derives the categories based on the unique values in each feature. Alternatively, you can also specify the categories manually. This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels. Note: a one-hot encoding of y labels should use a LabelBinarizer instead. Read more in the User Guide. Changed in version 0.20. Parameters
categories‘auto’ or a list of array-like, default=’auto’
Categories (unique values) per feature: ‘auto’ : Determine categories automatically from the training data. list : categories[i] holds the categories expected in the ith column. The passed categories should not mix strings and numeric values within a single feature, and should be sorted in case of numeric values. The used categories can be found in the categories_ attribute. New in version 0.20.
drop{‘first’, ‘if_binary’} or a array-like of shape (n_features,), default=None
Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into a neural network or an unregularized regression. However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models. None : retain all features (the default). ‘first’ : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. ‘if_binary’ : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. array : drop[i] is the category in feature X[:, i] that should be dropped. Changed in version 0.23: Added option ‘if_binary’.
sparsebool, default=True
Will return sparse matrix if set True else will return an array.
dtypenumber type, default=float
Desired dtype of output.
handle_unknown{‘error’, ‘ignore’}, default=’error’
Whether to raise an error or ignore if an unknown categorical feature is present during transform (default is to raise). When this parameter is set to ‘ignore’ and an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as None. Attributes
categories_list of arrays
The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of transform). This includes the category specified in drop (if any).
drop_idx_array of shape (n_features,)
drop_idx_[i] is the index in categories_[i] of the category to be dropped for each feature.
drop_idx_[i] = None if no category is to be dropped from the feature with index i, e.g. when drop='if_binary' and the feature isn’t binary.
drop_idx_ = None if all the transformed features will be retained. Changed in version 0.23: Added the possibility to contain None values. See also
OrdinalEncoder
Performs an ordinal (integer) encoding of the categorical features.
sklearn.feature_extraction.DictVectorizer
Performs a one-hot encoding of dictionary items (also handles string-valued features).
sklearn.feature_extraction.FeatureHasher
Performs an approximate one-hot encoding of dictionary items or strings.
LabelBinarizer
Binarizes labels in a one-vs-all fashion.
MultiLabelBinarizer
Transforms between iterable of iterables and a multilabel format, e.g. a (samples x classes) binary matrix indicating the presence of a class label. Examples Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to a binary one-hot encoding. >>> from sklearn.preprocessing import OneHotEncoder
One can discard categories not seen during fit: >>> enc = OneHotEncoder(handle_unknown='ignore')
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
OneHotEncoder(handle_unknown='ignore')
>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 1], ['Male', 4]]).toarray()
array([[1., 0., 1., 0., 0.],
[0., 1., 0., 0., 0.]])
>>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]])
array([['Male', 1],
[None, 2]], dtype=object)
>>> enc.get_feature_names(['gender', 'group'])
array(['gender_Female', 'gender_Male', 'group_1', 'group_2', 'group_3'],
dtype=object)
One can always drop the first column for each feature: >>> drop_enc = OneHotEncoder(drop='first').fit(X)
>>> drop_enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> drop_enc.transform([['Female', 1], ['Male', 2]]).toarray()
array([[0., 0., 0.],
[1., 1., 0.]])
Or drop a column for feature only having 2 categories: >>> drop_binary_enc = OneHotEncoder(drop='if_binary').fit(X)
>>> drop_binary_enc.transform([['Female', 1], ['Male', 2]]).toarray()
array([[0., 1., 0., 0.],
[1., 0., 1., 0.]])
Methods
fit(X[, y]) Fit OneHotEncoder to X.
fit_transform(X[, y]) Fit OneHotEncoder to X, then transform X.
get_feature_names([input_features]) Return feature names for output features.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Convert the data back to the original representation.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X using one-hot encoding.
fit(X, y=None) [source]
Fit OneHotEncoder to X. Parameters
Xarray-like, shape [n_samples, n_features]
The data to determine the categories of each feature.
yNone
Ignored. This parameter exists only for compatibility with Pipeline. Returns
self
fit_transform(X, y=None) [source]
Fit OneHotEncoder to X, then transform X. Equivalent to fit(X).transform(X) but more convenient. Parameters
Xarray-like, shape [n_samples, n_features]
The data to encode.
yNone
Ignored. This parameter exists only for compatibility with Pipeline. Returns
X_outsparse matrix if sparse=True else a 2-d array
Transformed input.
get_feature_names(input_features=None) [source]
Return feature names for output features. Parameters
input_featureslist of str of shape (n_features,)
String names for input features if available. By default, “x0”, “x1”, … “xn_features” is used. Returns
output_feature_namesndarray of shape (n_output_features,)
Array of feature names.
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]
Convert the data back to the original representation. In case unknown categories are encountered (all zeros in the one-hot encoding), None is used to represent this category. Parameters
Xarray-like or sparse matrix, shape [n_samples, n_encoded_features]
The transformed data. Returns
X_trarray-like, shape [n_samples, n_features]
Inverse transformed array.
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 one-hot encoding. Parameters
Xarray-like, shape [n_samples, n_features]
The data to encode. Returns
X_outsparse matrix if sparse=True else a 2-d array
Transformed input.
Examples using sklearn.preprocessing.OneHotEncoder
Release Highlights for scikit-learn 0.23
Feature transformations with ensembles of trees
Categorical Feature Support in Gradient Boosting
Combine predictors using stacking
Poisson regression and non-normal loss
Tweedie regression on insurance claims
Permutation Importance vs Random Forest Feature Importance (MDI)
Common pitfalls in interpretation of coefficients of linear models
Column Transformer with Mixed Types | sklearn.modules.generated.sklearn.preprocessing.onehotencoder |
fit(X, y=None) [source]
Fit OneHotEncoder to X. Parameters
Xarray-like, shape [n_samples, n_features]
The data to determine the categories of each feature.
yNone
Ignored. This parameter exists only for compatibility with Pipeline. Returns
self | sklearn.modules.generated.sklearn.preprocessing.onehotencoder#sklearn.preprocessing.OneHotEncoder.fit |
fit_transform(X, y=None) [source]
Fit OneHotEncoder to X, then transform X. Equivalent to fit(X).transform(X) but more convenient. Parameters
Xarray-like, shape [n_samples, n_features]
The data to encode.
yNone
Ignored. This parameter exists only for compatibility with Pipeline. Returns
X_outsparse matrix if sparse=True else a 2-d array
Transformed input. | sklearn.modules.generated.sklearn.preprocessing.onehotencoder#sklearn.preprocessing.OneHotEncoder.fit_transform |
get_feature_names(input_features=None) [source]
Return feature names for output features. Parameters
input_featureslist of str of shape (n_features,)
String names for input features if available. By default, “x0”, “x1”, … “xn_features” is used. Returns
output_feature_namesndarray of shape (n_output_features,)
Array of feature names. | sklearn.modules.generated.sklearn.preprocessing.onehotencoder#sklearn.preprocessing.OneHotEncoder.get_feature_names |
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. | sklearn.modules.generated.sklearn.preprocessing.onehotencoder#sklearn.preprocessing.OneHotEncoder.get_params |
inverse_transform(X) [source]
Convert the data back to the original representation. In case unknown categories are encountered (all zeros in the one-hot encoding), None is used to represent this category. Parameters
Xarray-like or sparse matrix, shape [n_samples, n_encoded_features]
The transformed data. Returns
X_trarray-like, shape [n_samples, n_features]
Inverse transformed array. | sklearn.modules.generated.sklearn.preprocessing.onehotencoder#sklearn.preprocessing.OneHotEncoder.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. | sklearn.modules.generated.sklearn.preprocessing.onehotencoder#sklearn.preprocessing.OneHotEncoder.set_params |
transform(X) [source]
Transform X using one-hot encoding. Parameters
Xarray-like, shape [n_samples, n_features]
The data to encode. Returns
X_outsparse matrix if sparse=True else a 2-d array
Transformed input. | sklearn.modules.generated.sklearn.preprocessing.onehotencoder#sklearn.preprocessing.OneHotEncoder.transform |
class sklearn.preprocessing.OrdinalEncoder(*, categories='auto', dtype=<class 'numpy.float64'>, handle_unknown='error', unknown_value=None) [source]
Encode categorical features as an integer array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature. Read more in the User Guide. New in version 0.20. Parameters
categories‘auto’ or a list of array-like, default=’auto’
Categories (unique values) per feature: ‘auto’ : Determine categories automatically from the training data. list : categories[i] holds the categories expected in the ith column. The passed categories should not mix strings and numeric values, and should be sorted in case of numeric values. The used categories can be found in the categories_ attribute.
dtypenumber type, default np.float64
Desired dtype of output.
handle_unknown{‘error’, ‘use_encoded_value’}, default=’error’
When set to ‘error’ an error will be raised in case an unknown categorical feature is present during transform. When set to ‘use_encoded_value’, the encoded value of unknown categories will be set to the value given for the parameter unknown_value. In inverse_transform, an unknown category will be denoted as None. New in version 0.24.
unknown_valueint or np.nan, default=None
When the parameter handle_unknown is set to ‘use_encoded_value’, this parameter is required and will set the encoded value of unknown categories. It has to be distinct from the values used to encode any of the categories in fit. If set to np.nan, the dtype parameter must be a float dtype. New in version 0.24. Attributes
categories_list of arrays
The categories of each feature determined during fit (in order of the features in X and corresponding with the output of transform). This does not include categories that weren’t seen during fit. See also
OneHotEncoder
Performs a one-hot encoding of categorical features.
LabelEncoder
Encodes target labels with values between 0 and n_classes-1. Examples Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to an ordinal encoding. >>> from sklearn.preprocessing import OrdinalEncoder
>>> enc = OrdinalEncoder()
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
OrdinalEncoder()
>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 3], ['Male', 1]])
array([[0., 2.],
[1., 0.]])
>>> enc.inverse_transform([[1, 0], [0, 1]])
array([['Male', 1],
['Female', 2]], dtype=object)
Methods
fit(X[, y]) Fit the OrdinalEncoder to X.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Convert the data back to the original representation.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X to ordinal codes.
fit(X, y=None) [source]
Fit the OrdinalEncoder to X. Parameters
Xarray-like, shape [n_samples, n_features]
The data to determine the categories of each feature.
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(X) [source]
Convert the data back to the original representation. Parameters
Xarray-like or sparse matrix, shape [n_samples, n_encoded_features]
The transformed data. Returns
X_trarray-like, shape [n_samples, n_features]
Inverse transformed array.
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 to ordinal codes. Parameters
Xarray-like, shape [n_samples, n_features]
The data to encode. Returns
X_outsparse matrix or a 2-d array
Transformed input. | sklearn.modules.generated.sklearn.preprocessing.ordinalencoder#sklearn.preprocessing.OrdinalEncoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.