doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
sklearn.feature_selection.SelectFromModel
class sklearn.feature_selection.SelectFromModel(estimator, *, threshold=None, prefit=False, norm_order=1, max_features=None, importance_getter='auto') [source]
Meta-transformer for selecting features based on importance weights. New in version 0.17. Read more in the User Guide. Parameters
estimatorobject
The base estimator from which the transformer is built. This can be both a fitted (if prefit is set to True) or a non-fitted estimator. The estimator must have either a feature_importances_ or coef_ attribute after fitting.
thresholdstring or float, default=None
The threshold value to use for feature selection. Features whose importance is greater or equal are kept while the others are discarded. If “median” (resp. “mean”), then the threshold value is the median (resp. the mean) of the feature importances. A scaling factor (e.g., “1.25*mean”) may also be used. If None and if the estimator has a parameter penalty set to l1, either explicitly or implicitly (e.g, Lasso), the threshold used is 1e-5. Otherwise, “mean” is used by default.
prefitbool, default=False
Whether a prefit model is expected to be passed into the constructor directly or not. If True, transform must be called directly and SelectFromModel cannot be used with cross_val_score, GridSearchCV and similar utilities that clone the estimator. Otherwise train the model using fit and then transform to do feature selection.
norm_ordernon-zero int, inf, -inf, default=1
Order of the norm used to filter the vectors of coefficients below threshold in the case where the coef_ attribute of the estimator is of dimension 2.
max_featuresint, default=None
The maximum number of features to select. To only select based on max_features, set threshold=-np.inf. New in version 0.20.
importance_getterstr or callable, default=’auto’
If ‘auto’, uses the feature importance either through a coef_ attribute or feature_importances_ attribute of estimator. Also accepts a string that specifies an attribute name/path for extracting feature importance (implemented with attrgetter). For example, give regressor_.coef_ in case of TransformedTargetRegressor or named_steps.clf.feature_importances_ in case of Pipeline with its last step named clf. If callable, overrides the default feature importance getter. The callable is passed with the fitted estimator and it should return importance for each feature. New in version 0.24. Attributes
estimator_an estimator
The base estimator from which the transformer is built. This is stored only when a non-fitted estimator is passed to the SelectFromModel, i.e when prefit is False.
threshold_float
The threshold value used for feature selection. See also
RFE
Recursive feature elimination based on importance weights.
RFECV
Recursive feature elimination with built-in cross-validated selection of the best number of features.
SequentialFeatureSelector
Sequential cross-validation based feature selection. Does not rely on importance weights. Notes Allows NaN/Inf in the input if the underlying estimator does as well. Examples >>> from sklearn.feature_selection import SelectFromModel
>>> from sklearn.linear_model import LogisticRegression
>>> X = [[ 0.87, -1.34, 0.31 ],
... [-2.79, -0.02, -0.85 ],
... [-1.34, -0.48, -2.55 ],
... [ 1.92, 1.48, 0.65 ]]
>>> y = [0, 1, 0, 1]
>>> selector = SelectFromModel(estimator=LogisticRegression()).fit(X, y)
>>> selector.estimator_.coef_
array([[-0.3252302 , 0.83462377, 0.49750423]])
>>> selector.threshold_
0.55245...
>>> selector.get_support()
array([False, True, False])
>>> selector.transform(X)
array([[-1.34],
[-0.02],
[-0.48],
[ 1.48]])
Methods
fit(X[, y]) Fit the SelectFromModel meta-transformer.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
partial_fit(X[, y]) Fit the SelectFromModel meta-transformer only once.
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y=None, **fit_params) [source]
Fit the SelectFromModel meta-transformer. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,), default=None
The target values (integers that correspond to classes in classification, real numbers in regression).
**fit_paramsOther estimator specific parameters
Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform.
partial_fit(X, y=None, **fit_params) [source]
Fit the SelectFromModel meta-transformer only once. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,), default=None
The target values (integers that correspond to classes in classification, real numbers in regression).
**fit_paramsOther estimator specific parameters
Returns
selfobject
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]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features.
Examples using sklearn.feature_selection.SelectFromModel
Model-based and sequential feature selection
Classification of text documents using sparse features | sklearn.modules.generated.sklearn.feature_selection.selectfrommodel |
fit(X, y=None, **fit_params) [source]
Fit the SelectFromModel meta-transformer. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,), default=None
The target values (integers that correspond to classes in classification, real numbers in regression).
**fit_paramsOther estimator specific parameters
Returns
selfobject | sklearn.modules.generated.sklearn.feature_selection.selectfrommodel#sklearn.feature_selection.SelectFromModel.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.feature_selection.selectfrommodel#sklearn.feature_selection.SelectFromModel.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.feature_selection.selectfrommodel#sklearn.feature_selection.SelectFromModel.get_params |
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. | sklearn.modules.generated.sklearn.feature_selection.selectfrommodel#sklearn.feature_selection.SelectFromModel.get_support |
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform. | sklearn.modules.generated.sklearn.feature_selection.selectfrommodel#sklearn.feature_selection.SelectFromModel.inverse_transform |
partial_fit(X, y=None, **fit_params) [source]
Fit the SelectFromModel meta-transformer only once. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,), default=None
The target values (integers that correspond to classes in classification, real numbers in regression).
**fit_paramsOther estimator specific parameters
Returns
selfobject | sklearn.modules.generated.sklearn.feature_selection.selectfrommodel#sklearn.feature_selection.SelectFromModel.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.feature_selection.selectfrommodel#sklearn.feature_selection.SelectFromModel.set_params |
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectfrommodel#sklearn.feature_selection.SelectFromModel.transform |
class sklearn.feature_selection.SelectFwe(score_func=<function f_classif>, *, alpha=0.05) [source]
Filter: Select the p-values corresponding to Family-wise error rate Read more in the User Guide. Parameters
score_funccallable, default=f_classif
Function taking two arrays X and y, and returning a pair of arrays (scores, pvalues). Default is f_classif (see below “See Also”). The default function only works with classification tasks.
alphafloat, default=5e-2
The highest uncorrected p-value for features to keep. Attributes
scores_array-like of shape (n_features,)
Scores of features.
pvalues_array-like of shape (n_features,)
p-values of feature scores. See also
f_classif
ANOVA F-value between label/feature for classification tasks.
chi2
Chi-squared stats of non-negative features for classification tasks.
f_regression
F-value between label/feature for regression tasks.
SelectPercentile
Select features based on percentile of the highest scores.
SelectKBest
Select features based on the k highest scores.
SelectFpr
Select features based on a false positive rate test.
SelectFdr
Select features based on an estimated false discovery rate.
GenericUnivariateSelect
Univariate feature selector with configurable mode. Examples >>> from sklearn.datasets import load_breast_cancer
>>> from sklearn.feature_selection import SelectFwe, chi2
>>> X, y = load_breast_cancer(return_X_y=True)
>>> X.shape
(569, 30)
>>> X_new = SelectFwe(chi2, alpha=0.01).fit_transform(X, y)
>>> X_new.shape
(569, 15)
Methods
fit(X, y) Run score function on (X, y) and get the appropriate features.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectfwe#sklearn.feature_selection.SelectFwe |
sklearn.feature_selection.SelectFwe
class sklearn.feature_selection.SelectFwe(score_func=<function f_classif>, *, alpha=0.05) [source]
Filter: Select the p-values corresponding to Family-wise error rate Read more in the User Guide. Parameters
score_funccallable, default=f_classif
Function taking two arrays X and y, and returning a pair of arrays (scores, pvalues). Default is f_classif (see below “See Also”). The default function only works with classification tasks.
alphafloat, default=5e-2
The highest uncorrected p-value for features to keep. Attributes
scores_array-like of shape (n_features,)
Scores of features.
pvalues_array-like of shape (n_features,)
p-values of feature scores. See also
f_classif
ANOVA F-value between label/feature for classification tasks.
chi2
Chi-squared stats of non-negative features for classification tasks.
f_regression
F-value between label/feature for regression tasks.
SelectPercentile
Select features based on percentile of the highest scores.
SelectKBest
Select features based on the k highest scores.
SelectFpr
Select features based on a false positive rate test.
SelectFdr
Select features based on an estimated false discovery rate.
GenericUnivariateSelect
Univariate feature selector with configurable mode. Examples >>> from sklearn.datasets import load_breast_cancer
>>> from sklearn.feature_selection import SelectFwe, chi2
>>> X, y = load_breast_cancer(return_X_y=True)
>>> X.shape
(569, 30)
>>> X_new = SelectFwe(chi2, alpha=0.01).fit_transform(X, y)
>>> X_new.shape
(569, 15)
Methods
fit(X, y) Run score function on (X, y) and get the appropriate features.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectfwe |
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject | sklearn.modules.generated.sklearn.feature_selection.selectfwe#sklearn.feature_selection.SelectFwe.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.feature_selection.selectfwe#sklearn.feature_selection.SelectFwe.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.feature_selection.selectfwe#sklearn.feature_selection.SelectFwe.get_params |
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. | sklearn.modules.generated.sklearn.feature_selection.selectfwe#sklearn.feature_selection.SelectFwe.get_support |
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform. | sklearn.modules.generated.sklearn.feature_selection.selectfwe#sklearn.feature_selection.SelectFwe.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.feature_selection.selectfwe#sklearn.feature_selection.SelectFwe.set_params |
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectfwe#sklearn.feature_selection.SelectFwe.transform |
class sklearn.feature_selection.SelectKBest(score_func=<function f_classif>, *, k=10) [source]
Select features according to the k highest scores. Read more in the User Guide. Parameters
score_funccallable, default=f_classif
Function taking two arrays X and y, and returning a pair of arrays (scores, pvalues) or a single array with scores. Default is f_classif (see below “See Also”). The default function only works with classification tasks. New in version 0.18.
kint or “all”, default=10
Number of top features to select. The “all” option bypasses selection, for use in a parameter search. Attributes
scores_array-like of shape (n_features,)
Scores of features.
pvalues_array-like of shape (n_features,)
p-values of feature scores, None if score_func returned only scores. See also
f_classif
ANOVA F-value between label/feature for classification tasks.
mutual_info_classif
Mutual information for a discrete target.
chi2
Chi-squared stats of non-negative features for classification tasks.
f_regression
F-value between label/feature for regression tasks.
mutual_info_regression
Mutual information for a continuous target.
SelectPercentile
Select features based on percentile of the highest scores.
SelectFpr
Select features based on a false positive rate test.
SelectFdr
Select features based on an estimated false discovery rate.
SelectFwe
Select features based on family-wise error rate.
GenericUnivariateSelect
Univariate feature selector with configurable mode. Notes Ties between features with equal scores will be broken in an unspecified way. Examples >>> from sklearn.datasets import load_digits
>>> from sklearn.feature_selection import SelectKBest, chi2
>>> X, y = load_digits(return_X_y=True)
>>> X.shape
(1797, 64)
>>> X_new = SelectKBest(chi2, k=20).fit_transform(X, y)
>>> X_new.shape
(1797, 20)
Methods
fit(X, y) Run score function on (X, y) and get the appropriate features.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectkbest#sklearn.feature_selection.SelectKBest |
sklearn.feature_selection.SelectKBest
class sklearn.feature_selection.SelectKBest(score_func=<function f_classif>, *, k=10) [source]
Select features according to the k highest scores. Read more in the User Guide. Parameters
score_funccallable, default=f_classif
Function taking two arrays X and y, and returning a pair of arrays (scores, pvalues) or a single array with scores. Default is f_classif (see below “See Also”). The default function only works with classification tasks. New in version 0.18.
kint or “all”, default=10
Number of top features to select. The “all” option bypasses selection, for use in a parameter search. Attributes
scores_array-like of shape (n_features,)
Scores of features.
pvalues_array-like of shape (n_features,)
p-values of feature scores, None if score_func returned only scores. See also
f_classif
ANOVA F-value between label/feature for classification tasks.
mutual_info_classif
Mutual information for a discrete target.
chi2
Chi-squared stats of non-negative features for classification tasks.
f_regression
F-value between label/feature for regression tasks.
mutual_info_regression
Mutual information for a continuous target.
SelectPercentile
Select features based on percentile of the highest scores.
SelectFpr
Select features based on a false positive rate test.
SelectFdr
Select features based on an estimated false discovery rate.
SelectFwe
Select features based on family-wise error rate.
GenericUnivariateSelect
Univariate feature selector with configurable mode. Notes Ties between features with equal scores will be broken in an unspecified way. Examples >>> from sklearn.datasets import load_digits
>>> from sklearn.feature_selection import SelectKBest, chi2
>>> X, y = load_digits(return_X_y=True)
>>> X.shape
(1797, 64)
>>> X_new = SelectKBest(chi2, k=20).fit_transform(X, y)
>>> X_new.shape
(1797, 20)
Methods
fit(X, y) Run score function on (X, y) and get the appropriate features.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features.
Examples using sklearn.feature_selection.SelectKBest
Pipeline Anova SVM
Univariate Feature Selection
Concatenating multiple feature extraction methods
Selecting dimensionality reduction with Pipeline and GridSearchCV
Classification of text documents using sparse features | sklearn.modules.generated.sklearn.feature_selection.selectkbest |
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject | sklearn.modules.generated.sklearn.feature_selection.selectkbest#sklearn.feature_selection.SelectKBest.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.feature_selection.selectkbest#sklearn.feature_selection.SelectKBest.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.feature_selection.selectkbest#sklearn.feature_selection.SelectKBest.get_params |
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. | sklearn.modules.generated.sklearn.feature_selection.selectkbest#sklearn.feature_selection.SelectKBest.get_support |
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform. | sklearn.modules.generated.sklearn.feature_selection.selectkbest#sklearn.feature_selection.SelectKBest.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.feature_selection.selectkbest#sklearn.feature_selection.SelectKBest.set_params |
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectkbest#sklearn.feature_selection.SelectKBest.transform |
class sklearn.feature_selection.SelectorMixin [source]
Transformer mixin that performs feature selection given a support mask This mixin provides a feature selector implementation with transform and inverse_transform functionality given an implementation of _get_support_mask. Methods
fit_transform(X[, y]) Fit to data, then transform it.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
transform(X) Reduce X to the selected features.
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_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform.
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectormixin#sklearn.feature_selection.SelectorMixin |
sklearn.feature_selection.SelectorMixin
class sklearn.feature_selection.SelectorMixin [source]
Transformer mixin that performs feature selection given a support mask This mixin provides a feature selector implementation with transform and inverse_transform functionality given an implementation of _get_support_mask. Methods
fit_transform(X[, y]) Fit to data, then transform it.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
transform(X) Reduce X to the selected features.
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_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform.
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectormixin |
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.feature_selection.selectormixin#sklearn.feature_selection.SelectorMixin.fit_transform |
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. | sklearn.modules.generated.sklearn.feature_selection.selectormixin#sklearn.feature_selection.SelectorMixin.get_support |
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform. | sklearn.modules.generated.sklearn.feature_selection.selectormixin#sklearn.feature_selection.SelectorMixin.inverse_transform |
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectormixin#sklearn.feature_selection.SelectorMixin.transform |
class sklearn.feature_selection.SelectPercentile(score_func=<function f_classif>, *, percentile=10) [source]
Select features according to a percentile of the highest scores. Read more in the User Guide. Parameters
score_funccallable, default=f_classif
Function taking two arrays X and y, and returning a pair of arrays (scores, pvalues) or a single array with scores. Default is f_classif (see below “See Also”). The default function only works with classification tasks. New in version 0.18.
percentileint, default=10
Percent of features to keep. Attributes
scores_array-like of shape (n_features,)
Scores of features.
pvalues_array-like of shape (n_features,)
p-values of feature scores, None if score_func returned only scores. See also
f_classif
ANOVA F-value between label/feature for classification tasks.
mutual_info_classif
Mutual information for a discrete target.
chi2
Chi-squared stats of non-negative features for classification tasks.
f_regression
F-value between label/feature for regression tasks.
mutual_info_regression
Mutual information for a continuous target.
SelectKBest
Select features based on the k highest scores.
SelectFpr
Select features based on a false positive rate test.
SelectFdr
Select features based on an estimated false discovery rate.
SelectFwe
Select features based on family-wise error rate.
GenericUnivariateSelect
Univariate feature selector with configurable mode. Notes Ties between features with equal scores will be broken in an unspecified way. Examples >>> from sklearn.datasets import load_digits
>>> from sklearn.feature_selection import SelectPercentile, chi2
>>> X, y = load_digits(return_X_y=True)
>>> X.shape
(1797, 64)
>>> X_new = SelectPercentile(chi2, percentile=10).fit_transform(X, y)
>>> X_new.shape
(1797, 7)
Methods
fit(X, y) Run score function on (X, y) and get the appropriate features.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectpercentile#sklearn.feature_selection.SelectPercentile |
sklearn.feature_selection.SelectPercentile
class sklearn.feature_selection.SelectPercentile(score_func=<function f_classif>, *, percentile=10) [source]
Select features according to a percentile of the highest scores. Read more in the User Guide. Parameters
score_funccallable, default=f_classif
Function taking two arrays X and y, and returning a pair of arrays (scores, pvalues) or a single array with scores. Default is f_classif (see below “See Also”). The default function only works with classification tasks. New in version 0.18.
percentileint, default=10
Percent of features to keep. Attributes
scores_array-like of shape (n_features,)
Scores of features.
pvalues_array-like of shape (n_features,)
p-values of feature scores, None if score_func returned only scores. See also
f_classif
ANOVA F-value between label/feature for classification tasks.
mutual_info_classif
Mutual information for a discrete target.
chi2
Chi-squared stats of non-negative features for classification tasks.
f_regression
F-value between label/feature for regression tasks.
mutual_info_regression
Mutual information for a continuous target.
SelectKBest
Select features based on the k highest scores.
SelectFpr
Select features based on a false positive rate test.
SelectFdr
Select features based on an estimated false discovery rate.
SelectFwe
Select features based on family-wise error rate.
GenericUnivariateSelect
Univariate feature selector with configurable mode. Notes Ties between features with equal scores will be broken in an unspecified way. Examples >>> from sklearn.datasets import load_digits
>>> from sklearn.feature_selection import SelectPercentile, chi2
>>> X, y = load_digits(return_X_y=True)
>>> X.shape
(1797, 64)
>>> X_new = SelectPercentile(chi2, percentile=10).fit_transform(X, y)
>>> X_new.shape
(1797, 7)
Methods
fit(X, y) Run score function on (X, y) and get the appropriate features.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features.
Examples using sklearn.feature_selection.SelectPercentile
Feature agglomeration vs. univariate selection
SVM-Anova: SVM with univariate feature selection | sklearn.modules.generated.sklearn.feature_selection.selectpercentile |
fit(X, y) [source]
Run score function on (X, y) and get the appropriate features. Parameters
Xarray-like of shape (n_samples, n_features)
The training input samples.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression). Returns
selfobject | sklearn.modules.generated.sklearn.feature_selection.selectpercentile#sklearn.feature_selection.SelectPercentile.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.feature_selection.selectpercentile#sklearn.feature_selection.SelectPercentile.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.feature_selection.selectpercentile#sklearn.feature_selection.SelectPercentile.get_params |
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. | sklearn.modules.generated.sklearn.feature_selection.selectpercentile#sklearn.feature_selection.SelectPercentile.get_support |
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform. | sklearn.modules.generated.sklearn.feature_selection.selectpercentile#sklearn.feature_selection.SelectPercentile.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.feature_selection.selectpercentile#sklearn.feature_selection.SelectPercentile.set_params |
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.selectpercentile#sklearn.feature_selection.SelectPercentile.transform |
class sklearn.feature_selection.SequentialFeatureSelector(estimator, *, n_features_to_select=None, direction='forward', scoring=None, cv=5, n_jobs=None) [source]
Transformer that performs Sequential Feature Selection. This Sequential Feature Selector adds (forward selection) or removes (backward selection) features to form a feature subset in a greedy fashion. At each stage, this estimator chooses the best feature to add or remove based on the cross-validation score of an estimator. Read more in the User Guide. New in version 0.24. Parameters
estimatorestimator instance
An unfitted estimator.
n_features_to_selectint or float, default=None
The number of features to select. If None, half of the features are selected. If integer, the parameter is the absolute number of features to select. If float between 0 and 1, it is the fraction of features to select. direction: {‘forward’, ‘backward’}, default=’forward’
Whether to perform forward selection or backward selection.
scoringstr, callable, list/tuple or dict, default=None
A single str (see The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions) to evaluate the predictions on the test set. NOTE that when using custom scorers, each scorer should return a single value. Metric functions returning a list/array of values can be wrapped into multiple scorers that return one value each. If None, the estimator’s score method is used.
cvint, cross-validation generator or an iterable, default=None
Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross validation, integer, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.
n_jobsint, default=None
Number of jobs to run in parallel. When evaluating a new feature to add or remove, the cross-validation procedure is parallel over the folds. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
n_features_to_select_int
The number of features that were selected.
support_ndarray of shape (n_features,), dtype=bool
The mask of selected features. See also
RFE
Recursive feature elimination based on importance weights.
RFECV
Recursive feature elimination based on importance weights, with automatic selection of the number of features.
SelectFromModel
Feature selection based on thresholds of importance weights. Examples >>> from sklearn.feature_selection import SequentialFeatureSelector
>>> from sklearn.neighbors import KNeighborsClassifier
>>> from sklearn.datasets import load_iris
>>> X, y = load_iris(return_X_y=True)
>>> knn = KNeighborsClassifier(n_neighbors=3)
>>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3)
>>> sfs.fit(X, y)
SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3),
n_features_to_select=3)
>>> sfs.get_support()
array([ True, False, True, True])
>>> sfs.transform(X).shape
(150, 3)
Methods
fit(X, y) Learn the features to select.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Learn the features to select. Parameters
Xarray-like of shape (n_samples, n_features)
Training vectors.
yarray-like of shape (n_samples,)
Target values. Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.sequentialfeatureselector#sklearn.feature_selection.SequentialFeatureSelector |
sklearn.feature_selection.SequentialFeatureSelector
class sklearn.feature_selection.SequentialFeatureSelector(estimator, *, n_features_to_select=None, direction='forward', scoring=None, cv=5, n_jobs=None) [source]
Transformer that performs Sequential Feature Selection. This Sequential Feature Selector adds (forward selection) or removes (backward selection) features to form a feature subset in a greedy fashion. At each stage, this estimator chooses the best feature to add or remove based on the cross-validation score of an estimator. Read more in the User Guide. New in version 0.24. Parameters
estimatorestimator instance
An unfitted estimator.
n_features_to_selectint or float, default=None
The number of features to select. If None, half of the features are selected. If integer, the parameter is the absolute number of features to select. If float between 0 and 1, it is the fraction of features to select. direction: {‘forward’, ‘backward’}, default=’forward’
Whether to perform forward selection or backward selection.
scoringstr, callable, list/tuple or dict, default=None
A single str (see The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions) to evaluate the predictions on the test set. NOTE that when using custom scorers, each scorer should return a single value. Metric functions returning a list/array of values can be wrapped into multiple scorers that return one value each. If None, the estimator’s score method is used.
cvint, cross-validation generator or an iterable, default=None
Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross validation, integer, to specify the number of folds in a (Stratified)KFold,
CV splitter, An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.
n_jobsint, default=None
Number of jobs to run in parallel. When evaluating a new feature to add or remove, the cross-validation procedure is parallel over the folds. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
n_features_to_select_int
The number of features that were selected.
support_ndarray of shape (n_features,), dtype=bool
The mask of selected features. See also
RFE
Recursive feature elimination based on importance weights.
RFECV
Recursive feature elimination based on importance weights, with automatic selection of the number of features.
SelectFromModel
Feature selection based on thresholds of importance weights. Examples >>> from sklearn.feature_selection import SequentialFeatureSelector
>>> from sklearn.neighbors import KNeighborsClassifier
>>> from sklearn.datasets import load_iris
>>> X, y = load_iris(return_X_y=True)
>>> knn = KNeighborsClassifier(n_neighbors=3)
>>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3)
>>> sfs.fit(X, y)
SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3),
n_features_to_select=3)
>>> sfs.get_support()
array([ True, False, True, True])
>>> sfs.transform(X).shape
(150, 3)
Methods
fit(X, y) Learn the features to select.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y) [source]
Learn the features to select. Parameters
Xarray-like of shape (n_samples, n_features)
Training vectors.
yarray-like of shape (n_samples,)
Target values. Returns
selfobject
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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features.
Examples using sklearn.feature_selection.SequentialFeatureSelector
Release Highlights for scikit-learn 0.24
Model-based and sequential feature selection | sklearn.modules.generated.sklearn.feature_selection.sequentialfeatureselector |
fit(X, y) [source]
Learn the features to select. Parameters
Xarray-like of shape (n_samples, n_features)
Training vectors.
yarray-like of shape (n_samples,)
Target values. Returns
selfobject | sklearn.modules.generated.sklearn.feature_selection.sequentialfeatureselector#sklearn.feature_selection.SequentialFeatureSelector.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.feature_selection.sequentialfeatureselector#sklearn.feature_selection.SequentialFeatureSelector.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.feature_selection.sequentialfeatureselector#sklearn.feature_selection.SequentialFeatureSelector.get_params |
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. | sklearn.modules.generated.sklearn.feature_selection.sequentialfeatureselector#sklearn.feature_selection.SequentialFeatureSelector.get_support |
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform. | sklearn.modules.generated.sklearn.feature_selection.sequentialfeatureselector#sklearn.feature_selection.SequentialFeatureSelector.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.feature_selection.sequentialfeatureselector#sklearn.feature_selection.SequentialFeatureSelector.set_params |
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.sequentialfeatureselector#sklearn.feature_selection.SequentialFeatureSelector.transform |
class sklearn.feature_selection.VarianceThreshold(threshold=0.0) [source]
Feature selector that removes all low-variance features. This feature selection algorithm looks only at the features (X), not the desired outputs (y), and can thus be used for unsupervised learning. Read more in the User Guide. Parameters
thresholdfloat, default=0
Features with a training-set variance lower than this threshold will be removed. The default is to keep all features with non-zero variance, i.e. remove the features that have the same value in all samples. Attributes
variances_array, shape (n_features,)
Variances of individual features. Notes Allows NaN in the input. Raises ValueError if no feature in X meets the variance threshold. Examples The following dataset has integer features, two of which are the same in every sample. These are removed with the default setting for threshold: >>> X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]
>>> selector = VarianceThreshold()
>>> selector.fit_transform(X)
array([[2, 0],
[1, 4],
[1, 1]])
Methods
fit(X[, y]) Learn empirical variances from X.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y=None) [source]
Learn empirical variances from X. Parameters
X{array-like, sparse matrix}, shape (n_samples, n_features)
Sample vectors from which to compute variances.
yany, default=None
Ignored. This parameter exists only for compatibility with sklearn.pipeline.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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.variancethreshold#sklearn.feature_selection.VarianceThreshold |
sklearn.feature_selection.VarianceThreshold
class sklearn.feature_selection.VarianceThreshold(threshold=0.0) [source]
Feature selector that removes all low-variance features. This feature selection algorithm looks only at the features (X), not the desired outputs (y), and can thus be used for unsupervised learning. Read more in the User Guide. Parameters
thresholdfloat, default=0
Features with a training-set variance lower than this threshold will be removed. The default is to keep all features with non-zero variance, i.e. remove the features that have the same value in all samples. Attributes
variances_array, shape (n_features,)
Variances of individual features. Notes Allows NaN in the input. Raises ValueError if no feature in X meets the variance threshold. Examples The following dataset has integer features, two of which are the same in every sample. These are removed with the default setting for threshold: >>> X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]
>>> selector = VarianceThreshold()
>>> selector.fit_transform(X)
array([[2, 0],
[1, 4],
[1, 1]])
Methods
fit(X[, y]) Learn empirical variances from X.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
get_support([indices]) Get a mask, or integer index, of the features selected
inverse_transform(X) Reverse the transformation operation
set_params(**params) Set the parameters of this estimator.
transform(X) Reduce X to the selected features.
fit(X, y=None) [source]
Learn empirical variances from X. Parameters
X{array-like, sparse matrix}, shape (n_samples, n_features)
Sample vectors from which to compute variances.
yany, default=None
Ignored. This parameter exists only for compatibility with sklearn.pipeline.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.
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by 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(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.variancethreshold |
fit(X, y=None) [source]
Learn empirical variances from X. Parameters
X{array-like, sparse matrix}, shape (n_samples, n_features)
Sample vectors from which to compute variances.
yany, default=None
Ignored. This parameter exists only for compatibility with sklearn.pipeline.Pipeline. Returns
self | sklearn.modules.generated.sklearn.feature_selection.variancethreshold#sklearn.feature_selection.VarianceThreshold.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.feature_selection.variancethreshold#sklearn.feature_selection.VarianceThreshold.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.feature_selection.variancethreshold#sklearn.feature_selection.VarianceThreshold.get_params |
get_support(indices=False) [source]
Get a mask, or integer index, of the features selected Parameters
indicesbool, default=False
If True, the return value will be an array of integers, rather than a boolean mask. Returns
supportarray
An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. | sklearn.modules.generated.sklearn.feature_selection.variancethreshold#sklearn.feature_selection.VarianceThreshold.get_support |
inverse_transform(X) [source]
Reverse the transformation operation Parameters
Xarray of shape [n_samples, n_selected_features]
The input samples. Returns
X_rarray of shape [n_samples, n_original_features]
X with columns of zeros inserted where features would have been removed by transform. | sklearn.modules.generated.sklearn.feature_selection.variancethreshold#sklearn.feature_selection.VarianceThreshold.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.feature_selection.variancethreshold#sklearn.feature_selection.VarianceThreshold.set_params |
transform(X) [source]
Reduce X to the selected features. Parameters
Xarray of shape [n_samples, n_features]
The input samples. Returns
X_rarray of shape [n_samples, n_selected_features]
The input samples with only the selected features. | sklearn.modules.generated.sklearn.feature_selection.variancethreshold#sklearn.feature_selection.VarianceThreshold.transform |
class sklearn.gaussian_process.GaussianProcessClassifier(kernel=None, *, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, max_iter_predict=100, warm_start=False, copy_X_train=True, random_state=None, multi_class='one_vs_rest', n_jobs=None) [source]
Gaussian process classification (GPC) based on Laplace approximation. The implementation is based on Algorithm 3.1, 3.2, and 5.1 of Gaussian Processes for Machine Learning (GPML) by Rasmussen and Williams. Internally, the Laplace approximation is used for approximating the non-Gaussian posterior by a Gaussian. Currently, the implementation is restricted to using the logistic link function. For multi-class classification, several binary one-versus rest classifiers are fitted. Note that this class thus does not implement a true multi-class Laplace approximation. Read more in the User Guide. Parameters
kernelkernel instance, default=None
The kernel specifying the covariance function of the GP. If None is passed, the kernel “1.0 * RBF(1.0)” is used as default. Note that the kernel’s hyperparameters are optimized during fitting.
optimizer‘fmin_l_bfgs_b’ or callable, default=’fmin_l_bfgs_b’
Can either be one of the internally supported optimizers for optimizing the kernel’s parameters, specified by a string, or an externally defined optimizer passed as a callable. If a callable is passed, it must have the signature: def optimizer(obj_func, initial_theta, bounds):
# * 'obj_func' is the objective function to be maximized, which
# takes the hyperparameters theta as parameter and an
# optional flag eval_gradient, which determines if the
# gradient is returned additionally to the function value
# * 'initial_theta': the initial value for theta, which can be
# used by local optimizers
# * 'bounds': the bounds on the values of theta
....
# Returned are the best found hyperparameters theta and
# the corresponding value of the target function.
return theta_opt, func_min
Per default, the ‘L-BFGS-B’ algorithm from scipy.optimize.minimize is used. If None is passed, the kernel’s parameters are kept fixed. Available internal optimizers are: 'fmin_l_bfgs_b'
n_restarts_optimizerint, default=0
The number of restarts of the optimizer for finding the kernel’s parameters which maximize the log-marginal likelihood. The first run of the optimizer is performed from the kernel’s initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite. Note that n_restarts_optimizer=0 implies that one run is performed.
max_iter_predictint, default=100
The maximum number of iterations in Newton’s method for approximating the posterior during predict. Smaller values will reduce computation time at the cost of worse results.
warm_startbool, default=False
If warm-starts are enabled, the solution of the last Newton iteration on the Laplace approximation of the posterior mode is used as initialization for the next call of _posterior_mode(). This can speed up convergence when _posterior_mode is called several times on similar problems as in hyperparameter optimization. See the Glossary.
copy_X_trainbool, default=True
If True, a persistent copy of the training data is stored in the object. Otherwise, just a reference to the training data is stored, which might cause predictions to change if the data is modified externally.
random_stateint, RandomState instance or None, default=None
Determines random number generation used to initialize the centers. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>.
multi_class{‘one_vs_rest’, ‘one_vs_one’}, default=’one_vs_rest’
Specifies how multi-class classification problems are handled. Supported are ‘one_vs_rest’ and ‘one_vs_one’. In ‘one_vs_rest’, one binary Gaussian process classifier is fitted for each class, which is trained to separate this class from the rest. In ‘one_vs_one’, one binary Gaussian process classifier is fitted for each pair of classes, which is trained to separate these two classes. The predictions of these binary predictors are combined into multi-class predictions. Note that ‘one_vs_one’ does not support predicting probability estimates.
n_jobsint, default=None
The number of jobs to use for the computation: the specified multiclass problems are computed in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
base_estimator_Estimator instance
The estimator instance that defines the likelihood function using the observed data.
kernel_kernel instance
The kernel used for prediction. In case of binary classification, the structure of the kernel is the same as the one passed as parameter but with optimized hyperparameters. In case of multi-class classification, a CompoundKernel is returned which consists of the different kernels used in the one-versus-rest classifiers.
log_marginal_likelihood_value_float
The log-marginal-likelihood of self.kernel_.theta
classes_array-like of shape (n_classes,)
Unique class labels.
n_classes_int
The number of classes in the training data Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.gaussian_process import GaussianProcessClassifier
>>> from sklearn.gaussian_process.kernels import RBF
>>> X, y = load_iris(return_X_y=True)
>>> kernel = 1.0 * RBF(1.0)
>>> gpc = GaussianProcessClassifier(kernel=kernel,
... random_state=0).fit(X, y)
>>> gpc.score(X, y)
0.9866...
>>> gpc.predict_proba(X[:2,:])
array([[0.83548752, 0.03228706, 0.13222543],
[0.79064206, 0.06525643, 0.14410151]])
New in version 0.18. Methods
fit(X, y) Fit Gaussian process classification model
get_params([deep]) Get parameters for this estimator.
log_marginal_likelihood([theta, …]) Returns log-marginal likelihood of theta for training data.
predict(X) Perform classification on an array of test vectors X.
predict_proba(X) Return probability estimates for the test vector X.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]
Fit Gaussian process classification model Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Feature vectors or other representations of training data.
yarray-like of shape (n_samples,)
Target values, must be binary Returns
selfreturns an instance of self.
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.
log_marginal_likelihood(theta=None, eval_gradient=False, clone_kernel=True) [source]
Returns log-marginal likelihood of theta for training data. In the case of multi-class classification, the mean log-marginal likelihood of the one-versus-rest classifiers are returned. Parameters
thetaarray-like of shape (n_kernel_params,), default=None
Kernel hyperparameters for which the log-marginal likelihood is evaluated. In the case of multi-class classification, theta may be the hyperparameters of the compound kernel or of an individual kernel. In the latter case, all individual kernel get assigned the same theta values. If None, the precomputed log_marginal_likelihood of self.kernel_.theta is returned.
eval_gradientbool, default=False
If True, the gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta is returned additionally. Note that gradient computation is not supported for non-binary classification. If True, theta must not be None.
clone_kernelbool, default=True
If True, the kernel attribute is copied. If False, the kernel attribute is modified, but may result in a performance improvement. Returns
log_likelihoodfloat
Log-marginal likelihood of theta for training data.
log_likelihood_gradientndarray of shape (n_kernel_params,), optional
Gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta. Only returned when eval_gradient is True.
predict(X) [source]
Perform classification on an array of test vectors X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated for classification. Returns
Cndarray of shape (n_samples,)
Predicted target values for X, values are from classes_
predict_proba(X) [source]
Return probability estimates for the test vector X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated for classification. Returns
Carray-like of shape (n_samples, n_classes)
Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
score(X, y, sample_weight=None) [source]
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y.
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.gaussian_process.gaussianprocessclassifier#sklearn.gaussian_process.GaussianProcessClassifier |
sklearn.gaussian_process.GaussianProcessClassifier
class sklearn.gaussian_process.GaussianProcessClassifier(kernel=None, *, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, max_iter_predict=100, warm_start=False, copy_X_train=True, random_state=None, multi_class='one_vs_rest', n_jobs=None) [source]
Gaussian process classification (GPC) based on Laplace approximation. The implementation is based on Algorithm 3.1, 3.2, and 5.1 of Gaussian Processes for Machine Learning (GPML) by Rasmussen and Williams. Internally, the Laplace approximation is used for approximating the non-Gaussian posterior by a Gaussian. Currently, the implementation is restricted to using the logistic link function. For multi-class classification, several binary one-versus rest classifiers are fitted. Note that this class thus does not implement a true multi-class Laplace approximation. Read more in the User Guide. Parameters
kernelkernel instance, default=None
The kernel specifying the covariance function of the GP. If None is passed, the kernel “1.0 * RBF(1.0)” is used as default. Note that the kernel’s hyperparameters are optimized during fitting.
optimizer‘fmin_l_bfgs_b’ or callable, default=’fmin_l_bfgs_b’
Can either be one of the internally supported optimizers for optimizing the kernel’s parameters, specified by a string, or an externally defined optimizer passed as a callable. If a callable is passed, it must have the signature: def optimizer(obj_func, initial_theta, bounds):
# * 'obj_func' is the objective function to be maximized, which
# takes the hyperparameters theta as parameter and an
# optional flag eval_gradient, which determines if the
# gradient is returned additionally to the function value
# * 'initial_theta': the initial value for theta, which can be
# used by local optimizers
# * 'bounds': the bounds on the values of theta
....
# Returned are the best found hyperparameters theta and
# the corresponding value of the target function.
return theta_opt, func_min
Per default, the ‘L-BFGS-B’ algorithm from scipy.optimize.minimize is used. If None is passed, the kernel’s parameters are kept fixed. Available internal optimizers are: 'fmin_l_bfgs_b'
n_restarts_optimizerint, default=0
The number of restarts of the optimizer for finding the kernel’s parameters which maximize the log-marginal likelihood. The first run of the optimizer is performed from the kernel’s initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite. Note that n_restarts_optimizer=0 implies that one run is performed.
max_iter_predictint, default=100
The maximum number of iterations in Newton’s method for approximating the posterior during predict. Smaller values will reduce computation time at the cost of worse results.
warm_startbool, default=False
If warm-starts are enabled, the solution of the last Newton iteration on the Laplace approximation of the posterior mode is used as initialization for the next call of _posterior_mode(). This can speed up convergence when _posterior_mode is called several times on similar problems as in hyperparameter optimization. See the Glossary.
copy_X_trainbool, default=True
If True, a persistent copy of the training data is stored in the object. Otherwise, just a reference to the training data is stored, which might cause predictions to change if the data is modified externally.
random_stateint, RandomState instance or None, default=None
Determines random number generation used to initialize the centers. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>.
multi_class{‘one_vs_rest’, ‘one_vs_one’}, default=’one_vs_rest’
Specifies how multi-class classification problems are handled. Supported are ‘one_vs_rest’ and ‘one_vs_one’. In ‘one_vs_rest’, one binary Gaussian process classifier is fitted for each class, which is trained to separate this class from the rest. In ‘one_vs_one’, one binary Gaussian process classifier is fitted for each pair of classes, which is trained to separate these two classes. The predictions of these binary predictors are combined into multi-class predictions. Note that ‘one_vs_one’ does not support predicting probability estimates.
n_jobsint, default=None
The number of jobs to use for the computation: the specified multiclass problems are computed in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
base_estimator_Estimator instance
The estimator instance that defines the likelihood function using the observed data.
kernel_kernel instance
The kernel used for prediction. In case of binary classification, the structure of the kernel is the same as the one passed as parameter but with optimized hyperparameters. In case of multi-class classification, a CompoundKernel is returned which consists of the different kernels used in the one-versus-rest classifiers.
log_marginal_likelihood_value_float
The log-marginal-likelihood of self.kernel_.theta
classes_array-like of shape (n_classes,)
Unique class labels.
n_classes_int
The number of classes in the training data Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.gaussian_process import GaussianProcessClassifier
>>> from sklearn.gaussian_process.kernels import RBF
>>> X, y = load_iris(return_X_y=True)
>>> kernel = 1.0 * RBF(1.0)
>>> gpc = GaussianProcessClassifier(kernel=kernel,
... random_state=0).fit(X, y)
>>> gpc.score(X, y)
0.9866...
>>> gpc.predict_proba(X[:2,:])
array([[0.83548752, 0.03228706, 0.13222543],
[0.79064206, 0.06525643, 0.14410151]])
New in version 0.18. Methods
fit(X, y) Fit Gaussian process classification model
get_params([deep]) Get parameters for this estimator.
log_marginal_likelihood([theta, …]) Returns log-marginal likelihood of theta for training data.
predict(X) Perform classification on an array of test vectors X.
predict_proba(X) Return probability estimates for the test vector X.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]
Fit Gaussian process classification model Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Feature vectors or other representations of training data.
yarray-like of shape (n_samples,)
Target values, must be binary Returns
selfreturns an instance of self.
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.
log_marginal_likelihood(theta=None, eval_gradient=False, clone_kernel=True) [source]
Returns log-marginal likelihood of theta for training data. In the case of multi-class classification, the mean log-marginal likelihood of the one-versus-rest classifiers are returned. Parameters
thetaarray-like of shape (n_kernel_params,), default=None
Kernel hyperparameters for which the log-marginal likelihood is evaluated. In the case of multi-class classification, theta may be the hyperparameters of the compound kernel or of an individual kernel. In the latter case, all individual kernel get assigned the same theta values. If None, the precomputed log_marginal_likelihood of self.kernel_.theta is returned.
eval_gradientbool, default=False
If True, the gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta is returned additionally. Note that gradient computation is not supported for non-binary classification. If True, theta must not be None.
clone_kernelbool, default=True
If True, the kernel attribute is copied. If False, the kernel attribute is modified, but may result in a performance improvement. Returns
log_likelihoodfloat
Log-marginal likelihood of theta for training data.
log_likelihood_gradientndarray of shape (n_kernel_params,), optional
Gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta. Only returned when eval_gradient is True.
predict(X) [source]
Perform classification on an array of test vectors X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated for classification. Returns
Cndarray of shape (n_samples,)
Predicted target values for X, values are from classes_
predict_proba(X) [source]
Return probability estimates for the test vector X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated for classification. Returns
Carray-like of shape (n_samples, n_classes)
Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
score(X, y, sample_weight=None) [source]
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y.
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.
Examples using sklearn.gaussian_process.GaussianProcessClassifier
Plot classification probability
Classifier comparison
Illustration of Gaussian process classification (GPC) on the XOR dataset
Gaussian process classification (GPC) on iris dataset
Iso-probability lines for Gaussian Processes classification (GPC)
Probabilistic predictions with Gaussian process classification (GPC)
Gaussian processes on discrete data structures | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessclassifier |
fit(X, y) [source]
Fit Gaussian process classification model Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Feature vectors or other representations of training data.
yarray-like of shape (n_samples,)
Target values, must be binary Returns
selfreturns an instance of self. | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessclassifier#sklearn.gaussian_process.GaussianProcessClassifier.fit |
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.gaussian_process.gaussianprocessclassifier#sklearn.gaussian_process.GaussianProcessClassifier.get_params |
log_marginal_likelihood(theta=None, eval_gradient=False, clone_kernel=True) [source]
Returns log-marginal likelihood of theta for training data. In the case of multi-class classification, the mean log-marginal likelihood of the one-versus-rest classifiers are returned. Parameters
thetaarray-like of shape (n_kernel_params,), default=None
Kernel hyperparameters for which the log-marginal likelihood is evaluated. In the case of multi-class classification, theta may be the hyperparameters of the compound kernel or of an individual kernel. In the latter case, all individual kernel get assigned the same theta values. If None, the precomputed log_marginal_likelihood of self.kernel_.theta is returned.
eval_gradientbool, default=False
If True, the gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta is returned additionally. Note that gradient computation is not supported for non-binary classification. If True, theta must not be None.
clone_kernelbool, default=True
If True, the kernel attribute is copied. If False, the kernel attribute is modified, but may result in a performance improvement. Returns
log_likelihoodfloat
Log-marginal likelihood of theta for training data.
log_likelihood_gradientndarray of shape (n_kernel_params,), optional
Gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta. Only returned when eval_gradient is True. | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessclassifier#sklearn.gaussian_process.GaussianProcessClassifier.log_marginal_likelihood |
predict(X) [source]
Perform classification on an array of test vectors X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated for classification. Returns
Cndarray of shape (n_samples,)
Predicted target values for X, values are from classes_ | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessclassifier#sklearn.gaussian_process.GaussianProcessClassifier.predict |
predict_proba(X) [source]
Return probability estimates for the test vector X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated for classification. Returns
Carray-like of shape (n_samples, n_classes)
Returns the probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessclassifier#sklearn.gaussian_process.GaussianProcessClassifier.predict_proba |
score(X, y, sample_weight=None) [source]
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
Mean accuracy of self.predict(X) wrt. y. | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessclassifier#sklearn.gaussian_process.GaussianProcessClassifier.score |
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.gaussian_process.gaussianprocessclassifier#sklearn.gaussian_process.GaussianProcessClassifier.set_params |
class sklearn.gaussian_process.GaussianProcessRegressor(kernel=None, *, alpha=1e-10, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, normalize_y=False, copy_X_train=True, random_state=None) [source]
Gaussian process regression (GPR). The implementation is based on Algorithm 2.1 of Gaussian Processes for Machine Learning (GPML) by Rasmussen and Williams. In addition to standard scikit-learn estimator API, GaussianProcessRegressor: allows prediction without prior fitting (based on the GP prior) provides an additional method sample_y(X), which evaluates samples drawn from the GPR (prior or posterior) at given inputs exposes a method log_marginal_likelihood(theta), which can be used externally for other ways of selecting hyperparameters, e.g., via Markov chain Monte Carlo. Read more in the User Guide. New in version 0.18. Parameters
kernelkernel instance, default=None
The kernel specifying the covariance function of the GP. If None is passed, the kernel ConstantKernel(1.0, constant_value_bounds="fixed"
* RBF(1.0, length_scale_bounds="fixed") is used as default. Note that the kernel hyperparameters are optimized during fitting unless the bounds are marked as “fixed”.
alphafloat or ndarray of shape (n_samples,), default=1e-10
Value added to the diagonal of the kernel matrix during fitting. This can prevent a potential numerical issue during fitting, by ensuring that the calculated values form a positive definite matrix. It can also be interpreted as the variance of additional Gaussian measurement noise on the training observations. Note that this is different from using a WhiteKernel. If an array is passed, it must have the same number of entries as the data used for fitting and is used as datapoint-dependent noise level. Allowing to specify the noise level directly as a parameter is mainly for convenience and for consistency with Ridge.
optimizer“fmin_l_bfgs_b” or callable, default=”fmin_l_bfgs_b”
Can either be one of the internally supported optimizers for optimizing the kernel’s parameters, specified by a string, or an externally defined optimizer passed as a callable. If a callable is passed, it must have the signature: def optimizer(obj_func, initial_theta, bounds):
# * 'obj_func' is the objective function to be minimized, which
# takes the hyperparameters theta as parameter and an
# optional flag eval_gradient, which determines if the
# gradient is returned additionally to the function value
# * 'initial_theta': the initial value for theta, which can be
# used by local optimizers
# * 'bounds': the bounds on the values of theta
....
# Returned are the best found hyperparameters theta and
# the corresponding value of the target function.
return theta_opt, func_min
Per default, the ‘L-BGFS-B’ algorithm from scipy.optimize.minimize is used. If None is passed, the kernel’s parameters are kept fixed. Available internal optimizers are: 'fmin_l_bfgs_b'
n_restarts_optimizerint, default=0
The number of restarts of the optimizer for finding the kernel’s parameters which maximize the log-marginal likelihood. The first run of the optimizer is performed from the kernel’s initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite. Note that n_restarts_optimizer == 0 implies that one run is performed.
normalize_ybool, default=False
Whether the target values y are normalized, the mean and variance of the target values are set equal to 0 and 1 respectively. This is recommended for cases where zero-mean, unit-variance priors are used. Note that, in this implementation, the normalisation is reversed before the GP predictions are reported. Changed in version 0.23.
copy_X_trainbool, default=True
If True, a persistent copy of the training data is stored in the object. Otherwise, just a reference to the training data is stored, which might cause predictions to change if the data is modified externally.
random_stateint, RandomState instance or None, default=None
Determines random number generation used to initialize the centers. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Attributes
X_train_array-like of shape (n_samples, n_features) or list of object
Feature vectors or other representations of training data (also required for prediction).
y_train_array-like of shape (n_samples,) or (n_samples, n_targets)
Target values in training data (also required for prediction)
kernel_kernel instance
The kernel used for prediction. The structure of the kernel is the same as the one passed as parameter but with optimized hyperparameters
L_array-like of shape (n_samples, n_samples)
Lower-triangular Cholesky decomposition of the kernel in X_train_
alpha_array-like of shape (n_samples,)
Dual coefficients of training data points in kernel space
log_marginal_likelihood_value_float
The log-marginal-likelihood of self.kernel_.theta Examples >>> from sklearn.datasets import make_friedman2
>>> from sklearn.gaussian_process import GaussianProcessRegressor
>>> from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
>>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0)
>>> kernel = DotProduct() + WhiteKernel()
>>> gpr = GaussianProcessRegressor(kernel=kernel,
... random_state=0).fit(X, y)
>>> gpr.score(X, y)
0.3680...
>>> gpr.predict(X[:2,:], return_std=True)
(array([653.0..., 592.1...]), array([316.6..., 316.6...]))
Methods
fit(X, y) Fit Gaussian process regression model.
get_params([deep]) Get parameters for this estimator.
log_marginal_likelihood([theta, …]) Returns log-marginal likelihood of theta for training data.
predict(X[, return_std, return_cov]) Predict using the Gaussian process regression model
sample_y(X[, n_samples, random_state]) Draw samples from Gaussian process and evaluate at X.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]
Fit Gaussian process regression model. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Feature vectors or other representations of training data.
yarray-like of shape (n_samples,) or (n_samples, n_targets)
Target values Returns
selfreturns an instance of self.
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.
log_marginal_likelihood(theta=None, eval_gradient=False, clone_kernel=True) [source]
Returns log-marginal likelihood of theta for training data. Parameters
thetaarray-like of shape (n_kernel_params,) default=None
Kernel hyperparameters for which the log-marginal likelihood is evaluated. If None, the precomputed log_marginal_likelihood of self.kernel_.theta is returned.
eval_gradientbool, default=False
If True, the gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta is returned additionally. If True, theta must not be None.
clone_kernelbool, default=True
If True, the kernel attribute is copied. If False, the kernel attribute is modified, but may result in a performance improvement. Returns
log_likelihoodfloat
Log-marginal likelihood of theta for training data.
log_likelihood_gradientndarray of shape (n_kernel_params,), optional
Gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta. Only returned when eval_gradient is True.
predict(X, return_std=False, return_cov=False) [source]
Predict using the Gaussian process regression model We can also predict based on an unfitted model by using the GP prior. In addition to the mean of the predictive distribution, also its standard deviation (return_std=True) or covariance (return_cov=True). Note that at most one of the two can be requested. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated.
return_stdbool, default=False
If True, the standard-deviation of the predictive distribution at the query points is returned along with the mean.
return_covbool, default=False
If True, the covariance of the joint predictive distribution at the query points is returned along with the mean. Returns
y_meanndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution a query points.
y_stdndarray of shape (n_samples,), optional
Standard deviation of predictive distribution at query points. Only returned when return_std is True.
y_covndarray of shape (n_samples, n_samples), optional
Covariance of joint predictive distribution a query points. Only returned when return_cov is True.
sample_y(X, n_samples=1, random_state=0) [source]
Draw samples from Gaussian process and evaluate at X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated.
n_samplesint, default=1
The number of samples drawn from the Gaussian process
random_stateint, RandomState instance or None, default=0
Determines random number generation to randomly draw samples. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Returns
y_samplesndarray of shape (n_samples_X, [n_output_dims], n_samples)
Values of n_samples samples drawn from Gaussian process and evaluated at query points.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
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.gaussian_process.gaussianprocessregressor#sklearn.gaussian_process.GaussianProcessRegressor |
sklearn.gaussian_process.GaussianProcessRegressor
class sklearn.gaussian_process.GaussianProcessRegressor(kernel=None, *, alpha=1e-10, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, normalize_y=False, copy_X_train=True, random_state=None) [source]
Gaussian process regression (GPR). The implementation is based on Algorithm 2.1 of Gaussian Processes for Machine Learning (GPML) by Rasmussen and Williams. In addition to standard scikit-learn estimator API, GaussianProcessRegressor: allows prediction without prior fitting (based on the GP prior) provides an additional method sample_y(X), which evaluates samples drawn from the GPR (prior or posterior) at given inputs exposes a method log_marginal_likelihood(theta), which can be used externally for other ways of selecting hyperparameters, e.g., via Markov chain Monte Carlo. Read more in the User Guide. New in version 0.18. Parameters
kernelkernel instance, default=None
The kernel specifying the covariance function of the GP. If None is passed, the kernel ConstantKernel(1.0, constant_value_bounds="fixed"
* RBF(1.0, length_scale_bounds="fixed") is used as default. Note that the kernel hyperparameters are optimized during fitting unless the bounds are marked as “fixed”.
alphafloat or ndarray of shape (n_samples,), default=1e-10
Value added to the diagonal of the kernel matrix during fitting. This can prevent a potential numerical issue during fitting, by ensuring that the calculated values form a positive definite matrix. It can also be interpreted as the variance of additional Gaussian measurement noise on the training observations. Note that this is different from using a WhiteKernel. If an array is passed, it must have the same number of entries as the data used for fitting and is used as datapoint-dependent noise level. Allowing to specify the noise level directly as a parameter is mainly for convenience and for consistency with Ridge.
optimizer“fmin_l_bfgs_b” or callable, default=”fmin_l_bfgs_b”
Can either be one of the internally supported optimizers for optimizing the kernel’s parameters, specified by a string, or an externally defined optimizer passed as a callable. If a callable is passed, it must have the signature: def optimizer(obj_func, initial_theta, bounds):
# * 'obj_func' is the objective function to be minimized, which
# takes the hyperparameters theta as parameter and an
# optional flag eval_gradient, which determines if the
# gradient is returned additionally to the function value
# * 'initial_theta': the initial value for theta, which can be
# used by local optimizers
# * 'bounds': the bounds on the values of theta
....
# Returned are the best found hyperparameters theta and
# the corresponding value of the target function.
return theta_opt, func_min
Per default, the ‘L-BGFS-B’ algorithm from scipy.optimize.minimize is used. If None is passed, the kernel’s parameters are kept fixed. Available internal optimizers are: 'fmin_l_bfgs_b'
n_restarts_optimizerint, default=0
The number of restarts of the optimizer for finding the kernel’s parameters which maximize the log-marginal likelihood. The first run of the optimizer is performed from the kernel’s initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite. Note that n_restarts_optimizer == 0 implies that one run is performed.
normalize_ybool, default=False
Whether the target values y are normalized, the mean and variance of the target values are set equal to 0 and 1 respectively. This is recommended for cases where zero-mean, unit-variance priors are used. Note that, in this implementation, the normalisation is reversed before the GP predictions are reported. Changed in version 0.23.
copy_X_trainbool, default=True
If True, a persistent copy of the training data is stored in the object. Otherwise, just a reference to the training data is stored, which might cause predictions to change if the data is modified externally.
random_stateint, RandomState instance or None, default=None
Determines random number generation used to initialize the centers. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Attributes
X_train_array-like of shape (n_samples, n_features) or list of object
Feature vectors or other representations of training data (also required for prediction).
y_train_array-like of shape (n_samples,) or (n_samples, n_targets)
Target values in training data (also required for prediction)
kernel_kernel instance
The kernel used for prediction. The structure of the kernel is the same as the one passed as parameter but with optimized hyperparameters
L_array-like of shape (n_samples, n_samples)
Lower-triangular Cholesky decomposition of the kernel in X_train_
alpha_array-like of shape (n_samples,)
Dual coefficients of training data points in kernel space
log_marginal_likelihood_value_float
The log-marginal-likelihood of self.kernel_.theta Examples >>> from sklearn.datasets import make_friedman2
>>> from sklearn.gaussian_process import GaussianProcessRegressor
>>> from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
>>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0)
>>> kernel = DotProduct() + WhiteKernel()
>>> gpr = GaussianProcessRegressor(kernel=kernel,
... random_state=0).fit(X, y)
>>> gpr.score(X, y)
0.3680...
>>> gpr.predict(X[:2,:], return_std=True)
(array([653.0..., 592.1...]), array([316.6..., 316.6...]))
Methods
fit(X, y) Fit Gaussian process regression model.
get_params([deep]) Get parameters for this estimator.
log_marginal_likelihood([theta, …]) Returns log-marginal likelihood of theta for training data.
predict(X[, return_std, return_cov]) Predict using the Gaussian process regression model
sample_y(X[, n_samples, random_state]) Draw samples from Gaussian process and evaluate at X.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]
Fit Gaussian process regression model. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Feature vectors or other representations of training data.
yarray-like of shape (n_samples,) or (n_samples, n_targets)
Target values Returns
selfreturns an instance of self.
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.
log_marginal_likelihood(theta=None, eval_gradient=False, clone_kernel=True) [source]
Returns log-marginal likelihood of theta for training data. Parameters
thetaarray-like of shape (n_kernel_params,) default=None
Kernel hyperparameters for which the log-marginal likelihood is evaluated. If None, the precomputed log_marginal_likelihood of self.kernel_.theta is returned.
eval_gradientbool, default=False
If True, the gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta is returned additionally. If True, theta must not be None.
clone_kernelbool, default=True
If True, the kernel attribute is copied. If False, the kernel attribute is modified, but may result in a performance improvement. Returns
log_likelihoodfloat
Log-marginal likelihood of theta for training data.
log_likelihood_gradientndarray of shape (n_kernel_params,), optional
Gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta. Only returned when eval_gradient is True.
predict(X, return_std=False, return_cov=False) [source]
Predict using the Gaussian process regression model We can also predict based on an unfitted model by using the GP prior. In addition to the mean of the predictive distribution, also its standard deviation (return_std=True) or covariance (return_cov=True). Note that at most one of the two can be requested. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated.
return_stdbool, default=False
If True, the standard-deviation of the predictive distribution at the query points is returned along with the mean.
return_covbool, default=False
If True, the covariance of the joint predictive distribution at the query points is returned along with the mean. Returns
y_meanndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution a query points.
y_stdndarray of shape (n_samples,), optional
Standard deviation of predictive distribution at query points. Only returned when return_std is True.
y_covndarray of shape (n_samples, n_samples), optional
Covariance of joint predictive distribution a query points. Only returned when return_cov is True.
sample_y(X, n_samples=1, random_state=0) [source]
Draw samples from Gaussian process and evaluate at X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated.
n_samplesint, default=1
The number of samples drawn from the Gaussian process
random_stateint, RandomState instance or None, default=0
Determines random number generation to randomly draw samples. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Returns
y_samplesndarray of shape (n_samples_X, [n_output_dims], n_samples)
Values of n_samples samples drawn from Gaussian process and evaluated at query points.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
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.
Examples using sklearn.gaussian_process.GaussianProcessRegressor
Comparison of kernel ridge and Gaussian process regression
Illustration of prior and posterior Gaussian process for different kernels
Gaussian process regression (GPR) with noise-level estimation
Gaussian Processes regression: basic introductory example
Gaussian process regression (GPR) on Mauna Loa CO2 data.
Gaussian processes on discrete data structures | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessregressor |
fit(X, y) [source]
Fit Gaussian process regression model. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Feature vectors or other representations of training data.
yarray-like of shape (n_samples,) or (n_samples, n_targets)
Target values Returns
selfreturns an instance of self. | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessregressor#sklearn.gaussian_process.GaussianProcessRegressor.fit |
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.gaussian_process.gaussianprocessregressor#sklearn.gaussian_process.GaussianProcessRegressor.get_params |
log_marginal_likelihood(theta=None, eval_gradient=False, clone_kernel=True) [source]
Returns log-marginal likelihood of theta for training data. Parameters
thetaarray-like of shape (n_kernel_params,) default=None
Kernel hyperparameters for which the log-marginal likelihood is evaluated. If None, the precomputed log_marginal_likelihood of self.kernel_.theta is returned.
eval_gradientbool, default=False
If True, the gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta is returned additionally. If True, theta must not be None.
clone_kernelbool, default=True
If True, the kernel attribute is copied. If False, the kernel attribute is modified, but may result in a performance improvement. Returns
log_likelihoodfloat
Log-marginal likelihood of theta for training data.
log_likelihood_gradientndarray of shape (n_kernel_params,), optional
Gradient of the log-marginal likelihood with respect to the kernel hyperparameters at position theta. Only returned when eval_gradient is True. | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessregressor#sklearn.gaussian_process.GaussianProcessRegressor.log_marginal_likelihood |
predict(X, return_std=False, return_cov=False) [source]
Predict using the Gaussian process regression model We can also predict based on an unfitted model by using the GP prior. In addition to the mean of the predictive distribution, also its standard deviation (return_std=True) or covariance (return_cov=True). Note that at most one of the two can be requested. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated.
return_stdbool, default=False
If True, the standard-deviation of the predictive distribution at the query points is returned along with the mean.
return_covbool, default=False
If True, the covariance of the joint predictive distribution at the query points is returned along with the mean. Returns
y_meanndarray of shape (n_samples, [n_output_dims])
Mean of predictive distribution a query points.
y_stdndarray of shape (n_samples,), optional
Standard deviation of predictive distribution at query points. Only returned when return_std is True.
y_covndarray of shape (n_samples, n_samples), optional
Covariance of joint predictive distribution a query points. Only returned when return_cov is True. | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessregressor#sklearn.gaussian_process.GaussianProcessRegressor.predict |
sample_y(X, n_samples=1, random_state=0) [source]
Draw samples from Gaussian process and evaluate at X. Parameters
Xarray-like of shape (n_samples, n_features) or list of object
Query points where the GP is evaluated.
n_samplesint, default=1
The number of samples drawn from the Gaussian process
random_stateint, RandomState instance or None, default=0
Determines random number generation to randomly draw samples. Pass an int for reproducible results across multiple function calls. See :term: Glossary <random_state>. Returns
y_samplesndarray of shape (n_samples_X, [n_output_dims], n_samples)
Values of n_samples samples drawn from Gaussian process and evaluated at query points. | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessregressor#sklearn.gaussian_process.GaussianProcessRegressor.sample_y |
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor). | sklearn.modules.generated.sklearn.gaussian_process.gaussianprocessregressor#sklearn.gaussian_process.GaussianProcessRegressor.score |
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.gaussian_process.gaussianprocessregressor#sklearn.gaussian_process.GaussianProcessRegressor.set_params |
class sklearn.gaussian_process.kernels.CompoundKernel(kernels) [source]
Kernel which is composed of a set of other kernels. New in version 0.18. Parameters
kernelslist of Kernels
The other kernels Attributes
bounds
Returns the log-transformed bounds on the theta.
hyperparameters
Returns a list of all hyperparameter specifications.
n_dims
Returns the number of non-fixed hyperparameters of the kernel.
requires_vector_input
Returns whether the kernel is defined on discrete structures.
theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Examples >>> from sklearn.gaussian_process.kernels import WhiteKernel
>>> from sklearn.gaussian_process.kernels import RBF
>>> from sklearn.gaussian_process.kernels import CompoundKernel
>>> kernel = CompoundKernel(
... [WhiteKernel(noise_level=3.0), RBF(length_scale=2.0)])
>>> print(kernel.bounds)
[[-11.51292546 11.51292546]
[-11.51292546 11.51292546]]
>>> print(kernel.n_dims)
2
>>> print(kernel.theta)
[1.09861229 0.69314718]
Methods
__call__(X[, Y, eval_gradient]) Return the kernel k(X, Y) and optionally its gradient.
clone_with_theta(theta) Returns a clone of self with given hyperparameters theta.
diag(X) Returns the diagonal of the kernel k(X, X).
get_params([deep]) Get parameters of this kernel.
is_stationary() Returns whether the kernel is stationary.
set_params(**params) Set the parameters of this kernel.
__call__(X, Y=None, eval_gradient=False) [source]
Return the kernel k(X, Y) and optionally its gradient. Note that this compound kernel returns the results of all simple kernel stacked along an additional axis. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object, default=None
Left argument of the returned kernel k(X, Y)
Yarray-like of shape (n_samples_X, n_features) or list of object, default=None
Right argument of the returned kernel k(X, Y). If None, k(X, X) is evaluated instead.
eval_gradientbool, default=False
Determines whether the gradient with respect to the log of the kernel hyperparameter is computed. Returns
Kndarray of shape (n_samples_X, n_samples_Y, n_kernels)
Kernel k(X, Y)
K_gradientndarray of shape (n_samples_X, n_samples_X, n_dims, n_kernels), optional
The gradient of the kernel k(X, X) with respect to the log of the hyperparameter of the kernel. Only returned when eval_gradient is True.
property bounds
Returns the log-transformed bounds on the theta. Returns
boundsarray of shape (n_dims, 2)
The log-transformed bounds on the kernel’s hyperparameters theta
clone_with_theta(theta) [source]
Returns a clone of self with given hyperparameters theta. Parameters
thetandarray of shape (n_dims,)
The hyperparameters
diag(X) [source]
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object
Argument to the kernel. Returns
K_diagndarray of shape (n_samples_X, n_kernels)
Diagonal of kernel k(X, X)
get_params(deep=True) [source]
Get parameters of this kernel. 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.
property hyperparameters
Returns a list of all hyperparameter specifications.
is_stationary() [source]
Returns whether the kernel is stationary.
property n_dims
Returns the number of non-fixed hyperparameters of the kernel.
property requires_vector_input
Returns whether the kernel is defined on discrete structures.
set_params(**params) [source]
Set the parameters of this kernel. The method works on simple kernels as well as on nested kernels. The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Returns
self
property theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel’s hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns
thetandarray of shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel |
sklearn.gaussian_process.kernels.CompoundKernel
class sklearn.gaussian_process.kernels.CompoundKernel(kernels) [source]
Kernel which is composed of a set of other kernels. New in version 0.18. Parameters
kernelslist of Kernels
The other kernels Attributes
bounds
Returns the log-transformed bounds on the theta.
hyperparameters
Returns a list of all hyperparameter specifications.
n_dims
Returns the number of non-fixed hyperparameters of the kernel.
requires_vector_input
Returns whether the kernel is defined on discrete structures.
theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Examples >>> from sklearn.gaussian_process.kernels import WhiteKernel
>>> from sklearn.gaussian_process.kernels import RBF
>>> from sklearn.gaussian_process.kernels import CompoundKernel
>>> kernel = CompoundKernel(
... [WhiteKernel(noise_level=3.0), RBF(length_scale=2.0)])
>>> print(kernel.bounds)
[[-11.51292546 11.51292546]
[-11.51292546 11.51292546]]
>>> print(kernel.n_dims)
2
>>> print(kernel.theta)
[1.09861229 0.69314718]
Methods
__call__(X[, Y, eval_gradient]) Return the kernel k(X, Y) and optionally its gradient.
clone_with_theta(theta) Returns a clone of self with given hyperparameters theta.
diag(X) Returns the diagonal of the kernel k(X, X).
get_params([deep]) Get parameters of this kernel.
is_stationary() Returns whether the kernel is stationary.
set_params(**params) Set the parameters of this kernel.
__call__(X, Y=None, eval_gradient=False) [source]
Return the kernel k(X, Y) and optionally its gradient. Note that this compound kernel returns the results of all simple kernel stacked along an additional axis. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object, default=None
Left argument of the returned kernel k(X, Y)
Yarray-like of shape (n_samples_X, n_features) or list of object, default=None
Right argument of the returned kernel k(X, Y). If None, k(X, X) is evaluated instead.
eval_gradientbool, default=False
Determines whether the gradient with respect to the log of the kernel hyperparameter is computed. Returns
Kndarray of shape (n_samples_X, n_samples_Y, n_kernels)
Kernel k(X, Y)
K_gradientndarray of shape (n_samples_X, n_samples_X, n_dims, n_kernels), optional
The gradient of the kernel k(X, X) with respect to the log of the hyperparameter of the kernel. Only returned when eval_gradient is True.
property bounds
Returns the log-transformed bounds on the theta. Returns
boundsarray of shape (n_dims, 2)
The log-transformed bounds on the kernel’s hyperparameters theta
clone_with_theta(theta) [source]
Returns a clone of self with given hyperparameters theta. Parameters
thetandarray of shape (n_dims,)
The hyperparameters
diag(X) [source]
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object
Argument to the kernel. Returns
K_diagndarray of shape (n_samples_X, n_kernels)
Diagonal of kernel k(X, X)
get_params(deep=True) [source]
Get parameters of this kernel. 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.
property hyperparameters
Returns a list of all hyperparameter specifications.
is_stationary() [source]
Returns whether the kernel is stationary.
property n_dims
Returns the number of non-fixed hyperparameters of the kernel.
property requires_vector_input
Returns whether the kernel is defined on discrete structures.
set_params(**params) [source]
Set the parameters of this kernel. The method works on simple kernels as well as on nested kernels. The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Returns
self
property theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel’s hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns
thetandarray of shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel |
property bounds
Returns the log-transformed bounds on the theta. Returns
boundsarray of shape (n_dims, 2)
The log-transformed bounds on the kernel’s hyperparameters theta | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.bounds |
clone_with_theta(theta) [source]
Returns a clone of self with given hyperparameters theta. Parameters
thetandarray of shape (n_dims,)
The hyperparameters | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.clone_with_theta |
diag(X) [source]
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object
Argument to the kernel. Returns
K_diagndarray of shape (n_samples_X, n_kernels)
Diagonal of kernel k(X, X) | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.diag |
get_params(deep=True) [source]
Get parameters of this kernel. 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.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.get_params |
property hyperparameters
Returns a list of all hyperparameter specifications. | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.hyperparameters |
is_stationary() [source]
Returns whether the kernel is stationary. | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.is_stationary |
property n_dims
Returns the number of non-fixed hyperparameters of the kernel. | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.n_dims |
property requires_vector_input
Returns whether the kernel is defined on discrete structures. | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.requires_vector_input |
set_params(**params) [source]
Set the parameters of this kernel. The method works on simple kernels as well as on nested kernels. The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Returns
self | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.set_params |
property theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel’s hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns
thetandarray of shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.theta |
__call__(X, Y=None, eval_gradient=False) [source]
Return the kernel k(X, Y) and optionally its gradient. Note that this compound kernel returns the results of all simple kernel stacked along an additional axis. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object, default=None
Left argument of the returned kernel k(X, Y)
Yarray-like of shape (n_samples_X, n_features) or list of object, default=None
Right argument of the returned kernel k(X, Y). If None, k(X, X) is evaluated instead.
eval_gradientbool, default=False
Determines whether the gradient with respect to the log of the kernel hyperparameter is computed. Returns
Kndarray of shape (n_samples_X, n_samples_Y, n_kernels)
Kernel k(X, Y)
K_gradientndarray of shape (n_samples_X, n_samples_X, n_dims, n_kernels), optional
The gradient of the kernel k(X, X) with respect to the log of the hyperparameter of the kernel. Only returned when eval_gradient is True. | sklearn.modules.generated.sklearn.gaussian_process.kernels.compoundkernel#sklearn.gaussian_process.kernels.CompoundKernel.__call__ |
class sklearn.gaussian_process.kernels.ConstantKernel(constant_value=1.0, constant_value_bounds=1e-05, 100000.0) [source]
Constant kernel. Can be used as part of a product-kernel where it scales the magnitude of the other factor (kernel) or as part of a sum-kernel, where it modifies the mean of the Gaussian process. \[k(x_1, x_2) = constant\_value \;\forall\; x_1, x_2\] Adding a constant kernel is equivalent to adding a constant: kernel = RBF() + ConstantKernel(constant_value=2)
is the same as: kernel = RBF() + 2
Read more in the User Guide. New in version 0.18. Parameters
constant_valuefloat, default=1.0
The constant value which defines the covariance: k(x_1, x_2) = constant_value
constant_value_boundspair of floats >= 0 or “fixed”, default=(1e-5, 1e5)
The lower and upper bound on constant_value. If set to “fixed”, constant_value cannot be changed during hyperparameter tuning. Attributes
bounds
Returns the log-transformed bounds on the theta. hyperparameter_constant_value
hyperparameters
Returns a list of all hyperparameter specifications.
n_dims
Returns the number of non-fixed hyperparameters of the kernel.
requires_vector_input
Whether the kernel works only on fixed-length feature vectors.
theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Examples >>> from sklearn.datasets import make_friedman2
>>> from sklearn.gaussian_process import GaussianProcessRegressor
>>> from sklearn.gaussian_process.kernels import RBF, ConstantKernel
>>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0)
>>> kernel = RBF() + ConstantKernel(constant_value=2)
>>> gpr = GaussianProcessRegressor(kernel=kernel, alpha=5,
... random_state=0).fit(X, y)
>>> gpr.score(X, y)
0.3696...
>>> gpr.predict(X[:1,:], return_std=True)
(array([606.1...]), array([0.24...]))
Methods
__call__(X[, Y, eval_gradient]) Return the kernel k(X, Y) and optionally its gradient.
clone_with_theta(theta) Returns a clone of self with given hyperparameters theta.
diag(X) Returns the diagonal of the kernel k(X, X).
get_params([deep]) Get parameters of this kernel.
is_stationary() Returns whether the kernel is stationary.
set_params(**params) Set the parameters of this kernel.
__call__(X, Y=None, eval_gradient=False) [source]
Return the kernel k(X, Y) and optionally its gradient. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object
Left argument of the returned kernel k(X, Y)
Yarray-like of shape (n_samples_X, n_features) or list of object, default=None
Right argument of the returned kernel k(X, Y). If None, k(X, X) is evaluated instead.
eval_gradientbool, default=False
Determines whether the gradient with respect to the log of the kernel hyperparameter is computed. Only supported when Y is None. Returns
Kndarray of shape (n_samples_X, n_samples_Y)
Kernel k(X, Y)
K_gradientndarray of shape (n_samples_X, n_samples_X, n_dims), optional
The gradient of the kernel k(X, X) with respect to the log of the hyperparameter of the kernel. Only returned when eval_gradient is True.
property bounds
Returns the log-transformed bounds on the theta. Returns
boundsndarray of shape (n_dims, 2)
The log-transformed bounds on the kernel’s hyperparameters theta
clone_with_theta(theta) [source]
Returns a clone of self with given hyperparameters theta. Parameters
thetandarray of shape (n_dims,)
The hyperparameters
diag(X) [source]
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object
Argument to the kernel. Returns
K_diagndarray of shape (n_samples_X,)
Diagonal of kernel k(X, X)
get_params(deep=True) [source]
Get parameters of this kernel. 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.
property hyperparameters
Returns a list of all hyperparameter specifications.
is_stationary() [source]
Returns whether the kernel is stationary.
property n_dims
Returns the number of non-fixed hyperparameters of the kernel.
property requires_vector_input
Whether the kernel works only on fixed-length feature vectors.
set_params(**params) [source]
Set the parameters of this kernel. The method works on simple kernels as well as on nested kernels. The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Returns
self
property theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel’s hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns
thetandarray of shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel | sklearn.modules.generated.sklearn.gaussian_process.kernels.constantkernel#sklearn.gaussian_process.kernels.ConstantKernel |
sklearn.gaussian_process.kernels.ConstantKernel
class sklearn.gaussian_process.kernels.ConstantKernel(constant_value=1.0, constant_value_bounds=1e-05, 100000.0) [source]
Constant kernel. Can be used as part of a product-kernel where it scales the magnitude of the other factor (kernel) or as part of a sum-kernel, where it modifies the mean of the Gaussian process. \[k(x_1, x_2) = constant\_value \;\forall\; x_1, x_2\] Adding a constant kernel is equivalent to adding a constant: kernel = RBF() + ConstantKernel(constant_value=2)
is the same as: kernel = RBF() + 2
Read more in the User Guide. New in version 0.18. Parameters
constant_valuefloat, default=1.0
The constant value which defines the covariance: k(x_1, x_2) = constant_value
constant_value_boundspair of floats >= 0 or “fixed”, default=(1e-5, 1e5)
The lower and upper bound on constant_value. If set to “fixed”, constant_value cannot be changed during hyperparameter tuning. Attributes
bounds
Returns the log-transformed bounds on the theta. hyperparameter_constant_value
hyperparameters
Returns a list of all hyperparameter specifications.
n_dims
Returns the number of non-fixed hyperparameters of the kernel.
requires_vector_input
Whether the kernel works only on fixed-length feature vectors.
theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Examples >>> from sklearn.datasets import make_friedman2
>>> from sklearn.gaussian_process import GaussianProcessRegressor
>>> from sklearn.gaussian_process.kernels import RBF, ConstantKernel
>>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0)
>>> kernel = RBF() + ConstantKernel(constant_value=2)
>>> gpr = GaussianProcessRegressor(kernel=kernel, alpha=5,
... random_state=0).fit(X, y)
>>> gpr.score(X, y)
0.3696...
>>> gpr.predict(X[:1,:], return_std=True)
(array([606.1...]), array([0.24...]))
Methods
__call__(X[, Y, eval_gradient]) Return the kernel k(X, Y) and optionally its gradient.
clone_with_theta(theta) Returns a clone of self with given hyperparameters theta.
diag(X) Returns the diagonal of the kernel k(X, X).
get_params([deep]) Get parameters of this kernel.
is_stationary() Returns whether the kernel is stationary.
set_params(**params) Set the parameters of this kernel.
__call__(X, Y=None, eval_gradient=False) [source]
Return the kernel k(X, Y) and optionally its gradient. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object
Left argument of the returned kernel k(X, Y)
Yarray-like of shape (n_samples_X, n_features) or list of object, default=None
Right argument of the returned kernel k(X, Y). If None, k(X, X) is evaluated instead.
eval_gradientbool, default=False
Determines whether the gradient with respect to the log of the kernel hyperparameter is computed. Only supported when Y is None. Returns
Kndarray of shape (n_samples_X, n_samples_Y)
Kernel k(X, Y)
K_gradientndarray of shape (n_samples_X, n_samples_X, n_dims), optional
The gradient of the kernel k(X, X) with respect to the log of the hyperparameter of the kernel. Only returned when eval_gradient is True.
property bounds
Returns the log-transformed bounds on the theta. Returns
boundsndarray of shape (n_dims, 2)
The log-transformed bounds on the kernel’s hyperparameters theta
clone_with_theta(theta) [source]
Returns a clone of self with given hyperparameters theta. Parameters
thetandarray of shape (n_dims,)
The hyperparameters
diag(X) [source]
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object
Argument to the kernel. Returns
K_diagndarray of shape (n_samples_X,)
Diagonal of kernel k(X, X)
get_params(deep=True) [source]
Get parameters of this kernel. 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.
property hyperparameters
Returns a list of all hyperparameter specifications.
is_stationary() [source]
Returns whether the kernel is stationary.
property n_dims
Returns the number of non-fixed hyperparameters of the kernel.
property requires_vector_input
Whether the kernel works only on fixed-length feature vectors.
set_params(**params) [source]
Set the parameters of this kernel. The method works on simple kernels as well as on nested kernels. The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Returns
self
property theta
Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel’s hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns
thetandarray of shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel
Examples using sklearn.gaussian_process.kernels.ConstantKernel
Illustration of prior and posterior Gaussian process for different kernels
Iso-probability lines for Gaussian Processes classification (GPC)
Gaussian Processes regression: basic introductory example | sklearn.modules.generated.sklearn.gaussian_process.kernels.constantkernel |
property bounds
Returns the log-transformed bounds on the theta. Returns
boundsndarray of shape (n_dims, 2)
The log-transformed bounds on the kernel’s hyperparameters theta | sklearn.modules.generated.sklearn.gaussian_process.kernels.constantkernel#sklearn.gaussian_process.kernels.ConstantKernel.bounds |
clone_with_theta(theta) [source]
Returns a clone of self with given hyperparameters theta. Parameters
thetandarray of shape (n_dims,)
The hyperparameters | sklearn.modules.generated.sklearn.gaussian_process.kernels.constantkernel#sklearn.gaussian_process.kernels.ConstantKernel.clone_with_theta |
diag(X) [source]
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters
Xarray-like of shape (n_samples_X, n_features) or list of object
Argument to the kernel. Returns
K_diagndarray of shape (n_samples_X,)
Diagonal of kernel k(X, X) | sklearn.modules.generated.sklearn.gaussian_process.kernels.constantkernel#sklearn.gaussian_process.kernels.ConstantKernel.diag |
get_params(deep=True) [source]
Get parameters of this kernel. 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.gaussian_process.kernels.constantkernel#sklearn.gaussian_process.kernels.ConstantKernel.get_params |
property hyperparameters
Returns a list of all hyperparameter specifications. | sklearn.modules.generated.sklearn.gaussian_process.kernels.constantkernel#sklearn.gaussian_process.kernels.ConstantKernel.hyperparameters |
is_stationary() [source]
Returns whether the kernel is stationary. | sklearn.modules.generated.sklearn.gaussian_process.kernels.constantkernel#sklearn.gaussian_process.kernels.ConstantKernel.is_stationary |
property n_dims
Returns the number of non-fixed hyperparameters of the kernel. | sklearn.modules.generated.sklearn.gaussian_process.kernels.constantkernel#sklearn.gaussian_process.kernels.ConstantKernel.n_dims |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.