doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
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.decomposition.sparsepca#sklearn.decomposition.SparsePCA.set_params |
transform(X) [source]
Least Squares projection of the data onto the sparse components. To avoid instability issues in case the system is under-determined, regularization can be applied (Ridge regression) via the ridge_alpha parameter. Note that Sparse PCA components orthogonality is not enforced as in PCA hence one cannot use a simple linear projection. Parameters
Xndarray of shape (n_samples, n_features)
Test data to be transformed, must have the same number of features as the data used to train the model. Returns
X_newndarray of shape (n_samples, n_components)
Transformed data. | sklearn.modules.generated.sklearn.decomposition.sparsepca#sklearn.decomposition.SparsePCA.transform |
sklearn.decomposition.sparse_encode(X, dictionary, *, gram=None, cov=None, algorithm='lasso_lars', n_nonzero_coefs=None, alpha=None, copy_cov=True, init=None, max_iter=1000, n_jobs=None, check_input=True, verbose=0, positive=False) [source]
Sparse coding Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array code such that: X ~= code * dictionary
Read more in the User Guide. Parameters
Xndarray of shape (n_samples, n_features)
Data matrix.
dictionaryndarray of shape (n_components, n_features)
The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows for meaningful output.
gramndarray of shape (n_components, n_components), default=None
Precomputed Gram matrix, dictionary * dictionary'.
covndarray of shape (n_components, n_samples), default=None
Precomputed covariance, dictionary' * X.
algorithm{‘lasso_lars’, ‘lasso_cd’, ‘lars’, ‘omp’, ‘threshold’}, default=’lasso_lars’
The algorithm used:
'lars': uses the least angle regression method (linear_model.lars_path);
'lasso_lars': uses Lars to compute the Lasso solution;
'lasso_cd': uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse;
'omp': uses orthogonal matching pursuit to estimate the sparse solution;
'threshold': squashes to zero all coefficients less than regularization from the projection dictionary * data'.
n_nonzero_coefsint, default=None
Number of nonzero coefficients to target in each column of the solution. This is only used by algorithm='lars' and algorithm='omp' and is overridden by alpha in the omp case. If None, then n_nonzero_coefs=int(n_features / 10).
alphafloat, default=None
If algorithm='lasso_lars' or algorithm='lasso_cd', alpha is the penalty applied to the L1 norm. If algorithm='threshold', alpha is the absolute value of the threshold below which coefficients will be squashed to zero. If algorithm='omp', alpha is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides n_nonzero_coefs. If None, default to 1.
copy_covbool, default=True
Whether to copy the precomputed covariance matrix; if False, it may be overwritten.
initndarray of shape (n_samples, n_components), default=None
Initialization value of the sparse codes. Only used if algorithm='lasso_cd'.
max_iterint, default=1000
Maximum number of iterations to perform if algorithm='lasso_cd' or 'lasso_lars'.
n_jobsint, default=None
Number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
check_inputbool, default=True
If False, the input arrays X and dictionary will not be checked.
verboseint, default=0
Controls the verbosity; the higher, the more messages.
positivebool, default=False
Whether to enforce positivity when finding the encoding. New in version 0.20. Returns
codendarray of shape (n_samples, n_components)
The sparse codes See also
sklearn.linear_model.lars_path
sklearn.linear_model.orthogonal_mp
sklearn.linear_model.Lasso
SparseCoder | sklearn.modules.generated.sklearn.decomposition.sparse_encode#sklearn.decomposition.sparse_encode |
class sklearn.decomposition.TruncatedSVD(n_components=2, *, algorithm='randomized', n_iter=5, random_state=None, tol=0.0) [source]
Dimensionality reduction using truncated SVD (aka LSA). This transformer performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). Contrary to PCA, this estimator does not center the data before computing the singular value decomposition. This means it can work with sparse matrices efficiently. In particular, truncated SVD works on term count/tf-idf matrices as returned by the vectorizers in sklearn.feature_extraction.text. In that context, it is known as latent semantic analysis (LSA). This estimator supports two algorithms: a fast randomized SVD solver, and a “naive” algorithm that uses ARPACK as an eigensolver on X * X.T or X.T * X, whichever is more efficient. Read more in the User Guide. Parameters
n_componentsint, default=2
Desired dimensionality of output data. Must be strictly less than the number of features. The default value is useful for visualisation. For LSA, a value of 100 is recommended.
algorithm{‘arpack’, ‘randomized’}, default=’randomized’
SVD solver to use. Either “arpack” for the ARPACK wrapper in SciPy (scipy.sparse.linalg.svds), or “randomized” for the randomized algorithm due to Halko (2009).
n_iterint, default=5
Number of iterations for randomized SVD solver. Not used by ARPACK. The default is larger than the default in randomized_svd to handle sparse matrices that may have large slowly decaying spectrum.
random_stateint, RandomState instance or None, default=None
Used during randomized svd. Pass an int for reproducible results across multiple function calls. See Glossary.
tolfloat, default=0.
Tolerance for ARPACK. 0 means machine precision. Ignored by randomized SVD solver. Attributes
components_ndarray of shape (n_components, n_features)
explained_variance_ndarray of shape (n_components,)
The variance of the training samples transformed by a projection to each component.
explained_variance_ratio_ndarray of shape (n_components,)
Percentage of variance explained by each of the selected components.
singular_values_ndarray od shape (n_components,)
The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the n_components variables in the lower-dimensional space. See also
PCA
Notes SVD suffers from a problem called “sign indeterminacy”, which means the sign of the components_ and the output from transform depend on the algorithm and random state. To work around this, fit instances of this class to data once, then keep the instance around to do transformations. References Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf Examples >>> from sklearn.decomposition import TruncatedSVD
>>> from scipy.sparse import random as sparse_random
>>> X = sparse_random(100, 100, density=0.01, format='csr',
... random_state=42)
>>> svd = TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> svd.fit(X)
TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> print(svd.explained_variance_ratio_)
[0.0646... 0.0633... 0.0639... 0.0535... 0.0406...]
>>> print(svd.explained_variance_ratio_.sum())
0.286...
>>> print(svd.singular_values_)
[1.553... 1.512... 1.510... 1.370... 1.199...]
Methods
fit(X[, y]) Fit model on training data X.
fit_transform(X[, y]) Fit model to X and perform dimensionality reduction on X.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Transform X back to its original space.
set_params(**params) Set the parameters of this estimator.
transform(X) Perform dimensionality reduction on X.
fit(X, y=None) [source]
Fit model on training data X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
yIgnored
Returns
selfobject
Returns the transformer object.
fit_transform(X, y=None) [source]
Fit model to X and perform dimensionality reduction on X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
yIgnored
Returns
X_newndarray of shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
inverse_transform(X) [source]
Transform X back to its original space. Returns an array X_original whose transform would be X. Parameters
Xarray-like of shape (n_samples, n_components)
New data. Returns
X_originalndarray of shape (n_samples, n_features)
Note that this is always a dense array.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
transform(X) [source]
Perform dimensionality reduction on X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data. Returns
X_newndarray of shape (n_samples, n_components)
Reduced version of X. This will always be a dense array. | sklearn.modules.generated.sklearn.decomposition.truncatedsvd#sklearn.decomposition.TruncatedSVD |
sklearn.decomposition.TruncatedSVD
class sklearn.decomposition.TruncatedSVD(n_components=2, *, algorithm='randomized', n_iter=5, random_state=None, tol=0.0) [source]
Dimensionality reduction using truncated SVD (aka LSA). This transformer performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). Contrary to PCA, this estimator does not center the data before computing the singular value decomposition. This means it can work with sparse matrices efficiently. In particular, truncated SVD works on term count/tf-idf matrices as returned by the vectorizers in sklearn.feature_extraction.text. In that context, it is known as latent semantic analysis (LSA). This estimator supports two algorithms: a fast randomized SVD solver, and a “naive” algorithm that uses ARPACK as an eigensolver on X * X.T or X.T * X, whichever is more efficient. Read more in the User Guide. Parameters
n_componentsint, default=2
Desired dimensionality of output data. Must be strictly less than the number of features. The default value is useful for visualisation. For LSA, a value of 100 is recommended.
algorithm{‘arpack’, ‘randomized’}, default=’randomized’
SVD solver to use. Either “arpack” for the ARPACK wrapper in SciPy (scipy.sparse.linalg.svds), or “randomized” for the randomized algorithm due to Halko (2009).
n_iterint, default=5
Number of iterations for randomized SVD solver. Not used by ARPACK. The default is larger than the default in randomized_svd to handle sparse matrices that may have large slowly decaying spectrum.
random_stateint, RandomState instance or None, default=None
Used during randomized svd. Pass an int for reproducible results across multiple function calls. See Glossary.
tolfloat, default=0.
Tolerance for ARPACK. 0 means machine precision. Ignored by randomized SVD solver. Attributes
components_ndarray of shape (n_components, n_features)
explained_variance_ndarray of shape (n_components,)
The variance of the training samples transformed by a projection to each component.
explained_variance_ratio_ndarray of shape (n_components,)
Percentage of variance explained by each of the selected components.
singular_values_ndarray od shape (n_components,)
The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the n_components variables in the lower-dimensional space. See also
PCA
Notes SVD suffers from a problem called “sign indeterminacy”, which means the sign of the components_ and the output from transform depend on the algorithm and random state. To work around this, fit instances of this class to data once, then keep the instance around to do transformations. References Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf Examples >>> from sklearn.decomposition import TruncatedSVD
>>> from scipy.sparse import random as sparse_random
>>> X = sparse_random(100, 100, density=0.01, format='csr',
... random_state=42)
>>> svd = TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> svd.fit(X)
TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> print(svd.explained_variance_ratio_)
[0.0646... 0.0633... 0.0639... 0.0535... 0.0406...]
>>> print(svd.explained_variance_ratio_.sum())
0.286...
>>> print(svd.singular_values_)
[1.553... 1.512... 1.510... 1.370... 1.199...]
Methods
fit(X[, y]) Fit model on training data X.
fit_transform(X[, y]) Fit model to X and perform dimensionality reduction on X.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Transform X back to its original space.
set_params(**params) Set the parameters of this estimator.
transform(X) Perform dimensionality reduction on X.
fit(X, y=None) [source]
Fit model on training data X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
yIgnored
Returns
selfobject
Returns the transformer object.
fit_transform(X, y=None) [source]
Fit model to X and perform dimensionality reduction on X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
yIgnored
Returns
X_newndarray of shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
inverse_transform(X) [source]
Transform X back to its original space. Returns an array X_original whose transform would be X. Parameters
Xarray-like of shape (n_samples, n_components)
New data. Returns
X_originalndarray of shape (n_samples, n_features)
Note that this is always a dense array.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
transform(X) [source]
Perform dimensionality reduction on X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data. Returns
X_newndarray of shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
Examples using sklearn.decomposition.TruncatedSVD
Hashing feature transformation using Totally Random Trees
Manifold learning on handwritten digits: Locally Linear Embedding, Isomap…
Column Transformer with Heterogeneous Data Sources
Clustering text documents using k-means | sklearn.modules.generated.sklearn.decomposition.truncatedsvd |
fit(X, y=None) [source]
Fit model on training data X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
yIgnored
Returns
selfobject
Returns the transformer object. | sklearn.modules.generated.sklearn.decomposition.truncatedsvd#sklearn.decomposition.TruncatedSVD.fit |
fit_transform(X, y=None) [source]
Fit model to X and perform dimensionality reduction on X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data.
yIgnored
Returns
X_newndarray of shape (n_samples, n_components)
Reduced version of X. This will always be a dense array. | sklearn.modules.generated.sklearn.decomposition.truncatedsvd#sklearn.decomposition.TruncatedSVD.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.decomposition.truncatedsvd#sklearn.decomposition.TruncatedSVD.get_params |
inverse_transform(X) [source]
Transform X back to its original space. Returns an array X_original whose transform would be X. Parameters
Xarray-like of shape (n_samples, n_components)
New data. Returns
X_originalndarray of shape (n_samples, n_features)
Note that this is always a dense array. | sklearn.modules.generated.sklearn.decomposition.truncatedsvd#sklearn.decomposition.TruncatedSVD.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.decomposition.truncatedsvd#sklearn.decomposition.TruncatedSVD.set_params |
transform(X) [source]
Perform dimensionality reduction on X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data. Returns
X_newndarray of shape (n_samples, n_components)
Reduced version of X. This will always be a dense array. | sklearn.modules.generated.sklearn.decomposition.truncatedsvd#sklearn.decomposition.TruncatedSVD.transform |
class sklearn.discriminant_analysis.LinearDiscriminantAnalysis(solver='svd', shrinkage=None, priors=None, n_components=None, store_covariance=False, tol=0.0001, covariance_estimator=None) [source]
Linear Discriminant Analysis A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule. The model fits a Gaussian density to each class, assuming that all classes share the same covariance matrix. The fitted model can also be used to reduce the dimensionality of the input by projecting it to the most discriminative directions, using the transform method. New in version 0.17: LinearDiscriminantAnalysis. Read more in the User Guide. Parameters
solver{‘svd’, ‘lsqr’, ‘eigen’}, default=’svd’
Solver to use, possible values:
‘svd’: Singular value decomposition (default). Does not compute the covariance matrix, therefore this solver is recommended for data with a large number of features. ‘lsqr’: Least squares solution. Can be combined with shrinkage or custom covariance estimator. ‘eigen’: Eigenvalue decomposition. Can be combined with shrinkage or custom covariance estimator.
shrinkage‘auto’ or float, default=None
Shrinkage parameter, possible values:
None: no shrinkage (default). ‘auto’: automatic shrinkage using the Ledoit-Wolf lemma. float between 0 and 1: fixed shrinkage parameter. This should be left to None if covariance_estimator is used. Note that shrinkage works only with ‘lsqr’ and ‘eigen’ solvers.
priorsarray-like of shape (n_classes,), default=None
The class prior probabilities. By default, the class proportions are inferred from the training data.
n_componentsint, default=None
Number of components (<= min(n_classes - 1, n_features)) for dimensionality reduction. If None, will be set to min(n_classes - 1, n_features). This parameter only affects the transform method.
store_covariancebool, default=False
If True, explicitely compute the weighted within-class covariance matrix when solver is ‘svd’. The matrix is always computed and stored for the other solvers. New in version 0.17.
tolfloat, default=1.0e-4
Absolute threshold for a singular value of X to be considered significant, used to estimate the rank of X. Dimensions whose singular values are non-significant are discarded. Only used if solver is ‘svd’. New in version 0.17.
covariance_estimatorcovariance estimator, default=None
If not None, covariance_estimator is used to estimate the covariance matrices instead of relying on the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a covariance_ attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate. This should be left to None if shrinkage is used. Note that covariance_estimator works only with ‘lsqr’ and ‘eigen’ solvers. New in version 0.24. Attributes
coef_ndarray of shape (n_features,) or (n_classes, n_features)
Weight vector(s).
intercept_ndarray of shape (n_classes,)
Intercept term.
covariance_array-like of shape (n_features, n_features)
Weighted within-class covariance matrix. It corresponds to sum_k prior_k * C_k where C_k is the covariance matrix of the samples in class k. The C_k are estimated using the (potentially shrunk) biased estimator of covariance. If solver is ‘svd’, only exists when store_covariance is True.
explained_variance_ratio_ndarray of shape (n_components,)
Percentage of variance explained by each of the selected components. If n_components is not set then all components are stored and the sum of explained variances is equal to 1.0. Only available when eigen or svd solver is used.
means_array-like of shape (n_classes, n_features)
Class-wise means.
priors_array-like of shape (n_classes,)
Class priors (sum to 1).
scalings_array-like of shape (rank, n_classes - 1)
Scaling of the features in the space spanned by the class centroids. Only available for ‘svd’ and ‘eigen’ solvers.
xbar_array-like of shape (n_features,)
Overall mean. Only present if solver is ‘svd’.
classes_array-like of shape (n_classes,)
Unique class labels. See also
QuadraticDiscriminantAnalysis
Quadratic Discriminant Analysis. Examples >>> import numpy as np
>>> from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = LinearDiscriminantAnalysis()
>>> clf.fit(X, y)
LinearDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
Methods
decision_function(X) Apply decision function to an array of samples.
fit(X, y) Fit LinearDiscriminantAnalysis model according to the given
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class labels for samples in X.
predict_log_proba(X) Estimate log probability.
predict_proba(X) Estimate probability.
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.
transform(X) Project data to maximize class separation.
decision_function(X) [source]
Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples (test vectors). Returns
Cndarray of shape (n_samples,) or (n_samples, n_classes)
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.
fit(X, y) [source]
Fit LinearDiscriminantAnalysis model according to the given
training data and parameters. Changed in version 0.19: store_covariance has been moved to main constructor. Changed in version 0.19: tol has been moved to main constructor. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,)
Target values.
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.
predict(X) [source]
Predict class labels for samples in X. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape [n_samples]
Predicted class label per sample.
predict_log_proba(X) [source]
Estimate log probability. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
Cndarray of shape (n_samples, n_classes)
Estimated log probabilities.
predict_proba(X) [source]
Estimate probability. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
Cndarray of shape (n_samples, n_classes)
Estimated probabilities.
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.
transform(X) [source]
Project data to maximize class separation. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
X_newndarray of shape (n_samples, n_components)
Transformed data. | sklearn.modules.generated.sklearn.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis |
sklearn.discriminant_analysis.LinearDiscriminantAnalysis
class sklearn.discriminant_analysis.LinearDiscriminantAnalysis(solver='svd', shrinkage=None, priors=None, n_components=None, store_covariance=False, tol=0.0001, covariance_estimator=None) [source]
Linear Discriminant Analysis A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule. The model fits a Gaussian density to each class, assuming that all classes share the same covariance matrix. The fitted model can also be used to reduce the dimensionality of the input by projecting it to the most discriminative directions, using the transform method. New in version 0.17: LinearDiscriminantAnalysis. Read more in the User Guide. Parameters
solver{‘svd’, ‘lsqr’, ‘eigen’}, default=’svd’
Solver to use, possible values:
‘svd’: Singular value decomposition (default). Does not compute the covariance matrix, therefore this solver is recommended for data with a large number of features. ‘lsqr’: Least squares solution. Can be combined with shrinkage or custom covariance estimator. ‘eigen’: Eigenvalue decomposition. Can be combined with shrinkage or custom covariance estimator.
shrinkage‘auto’ or float, default=None
Shrinkage parameter, possible values:
None: no shrinkage (default). ‘auto’: automatic shrinkage using the Ledoit-Wolf lemma. float between 0 and 1: fixed shrinkage parameter. This should be left to None if covariance_estimator is used. Note that shrinkage works only with ‘lsqr’ and ‘eigen’ solvers.
priorsarray-like of shape (n_classes,), default=None
The class prior probabilities. By default, the class proportions are inferred from the training data.
n_componentsint, default=None
Number of components (<= min(n_classes - 1, n_features)) for dimensionality reduction. If None, will be set to min(n_classes - 1, n_features). This parameter only affects the transform method.
store_covariancebool, default=False
If True, explicitely compute the weighted within-class covariance matrix when solver is ‘svd’. The matrix is always computed and stored for the other solvers. New in version 0.17.
tolfloat, default=1.0e-4
Absolute threshold for a singular value of X to be considered significant, used to estimate the rank of X. Dimensions whose singular values are non-significant are discarded. Only used if solver is ‘svd’. New in version 0.17.
covariance_estimatorcovariance estimator, default=None
If not None, covariance_estimator is used to estimate the covariance matrices instead of relying on the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a covariance_ attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate. This should be left to None if shrinkage is used. Note that covariance_estimator works only with ‘lsqr’ and ‘eigen’ solvers. New in version 0.24. Attributes
coef_ndarray of shape (n_features,) or (n_classes, n_features)
Weight vector(s).
intercept_ndarray of shape (n_classes,)
Intercept term.
covariance_array-like of shape (n_features, n_features)
Weighted within-class covariance matrix. It corresponds to sum_k prior_k * C_k where C_k is the covariance matrix of the samples in class k. The C_k are estimated using the (potentially shrunk) biased estimator of covariance. If solver is ‘svd’, only exists when store_covariance is True.
explained_variance_ratio_ndarray of shape (n_components,)
Percentage of variance explained by each of the selected components. If n_components is not set then all components are stored and the sum of explained variances is equal to 1.0. Only available when eigen or svd solver is used.
means_array-like of shape (n_classes, n_features)
Class-wise means.
priors_array-like of shape (n_classes,)
Class priors (sum to 1).
scalings_array-like of shape (rank, n_classes - 1)
Scaling of the features in the space spanned by the class centroids. Only available for ‘svd’ and ‘eigen’ solvers.
xbar_array-like of shape (n_features,)
Overall mean. Only present if solver is ‘svd’.
classes_array-like of shape (n_classes,)
Unique class labels. See also
QuadraticDiscriminantAnalysis
Quadratic Discriminant Analysis. Examples >>> import numpy as np
>>> from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = LinearDiscriminantAnalysis()
>>> clf.fit(X, y)
LinearDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
Methods
decision_function(X) Apply decision function to an array of samples.
fit(X, y) Fit LinearDiscriminantAnalysis model according to the given
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class labels for samples in X.
predict_log_proba(X) Estimate log probability.
predict_proba(X) Estimate probability.
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.
transform(X) Project data to maximize class separation.
decision_function(X) [source]
Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples (test vectors). Returns
Cndarray of shape (n_samples,) or (n_samples, n_classes)
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.
fit(X, y) [source]
Fit LinearDiscriminantAnalysis model according to the given
training data and parameters. Changed in version 0.19: store_covariance has been moved to main constructor. Changed in version 0.19: tol has been moved to main constructor. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,)
Target values.
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.
predict(X) [source]
Predict class labels for samples in X. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape [n_samples]
Predicted class label per sample.
predict_log_proba(X) [source]
Estimate log probability. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
Cndarray of shape (n_samples, n_classes)
Estimated log probabilities.
predict_proba(X) [source]
Estimate probability. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
Cndarray of shape (n_samples, n_classes)
Estimated probabilities.
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.
transform(X) [source]
Project data to maximize class separation. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
X_newndarray of shape (n_samples, n_components)
Transformed data.
Examples using sklearn.discriminant_analysis.LinearDiscriminantAnalysis
Normal, Ledoit-Wolf and OAS Linear Discriminant Analysis for classification
Linear and Quadratic Discriminant Analysis with covariance ellipsoid
Comparison of LDA and PCA 2D projection of Iris dataset
Manifold learning on handwritten digits: Locally Linear Embedding, Isomap…
Dimensionality Reduction with Neighborhood Components Analysis | sklearn.modules.generated.sklearn.discriminant_analysis.lineardiscriminantanalysis |
decision_function(X) [source]
Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples (test vectors). Returns
Cndarray of shape (n_samples,) or (n_samples, n_classes)
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class. | sklearn.modules.generated.sklearn.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.decision_function |
fit(X, y) [source]
Fit LinearDiscriminantAnalysis model according to the given
training data and parameters. Changed in version 0.19: store_covariance has been moved to main constructor. Changed in version 0.19: tol has been moved to main constructor. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,)
Target values. | sklearn.modules.generated.sklearn.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.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.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.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.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.get_params |
predict(X) [source]
Predict class labels for samples in X. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape [n_samples]
Predicted class label per sample. | sklearn.modules.generated.sklearn.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.predict |
predict_log_proba(X) [source]
Estimate log probability. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
Cndarray of shape (n_samples, n_classes)
Estimated log probabilities. | sklearn.modules.generated.sklearn.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.predict_log_proba |
predict_proba(X) [source]
Estimate probability. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
Cndarray of shape (n_samples, n_classes)
Estimated probabilities. | sklearn.modules.generated.sklearn.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.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.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.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.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.set_params |
transform(X) [source]
Project data to maximize class separation. Parameters
Xarray-like of shape (n_samples, n_features)
Input data. Returns
X_newndarray of shape (n_samples, n_components)
Transformed data. | sklearn.modules.generated.sklearn.discriminant_analysis.lineardiscriminantanalysis#sklearn.discriminant_analysis.LinearDiscriminantAnalysis.transform |
class sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis(*, priors=None, reg_param=0.0, store_covariance=False, tol=0.0001) [source]
Quadratic Discriminant Analysis A classifier with a quadratic decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule. The model fits a Gaussian density to each class. New in version 0.17: QuadraticDiscriminantAnalysis Read more in the User Guide. Parameters
priorsndarray of shape (n_classes,), default=None
Class priors. By default, the class proportions are inferred from the training data.
reg_paramfloat, default=0.0
Regularizes the per-class covariance estimates by transforming S2 as S2 = (1 - reg_param) * S2 + reg_param * np.eye(n_features), where S2 corresponds to the scaling_ attribute of a given class.
store_covariancebool, default=False
If True, the class covariance matrices are explicitely computed and stored in the self.covariance_ attribute. New in version 0.17.
tolfloat, default=1.0e-4
Absolute threshold for a singular value to be considered significant, used to estimate the rank of Xk where Xk is the centered matrix of samples in class k. This parameter does not affect the predictions. It only controls a warning that is raised when features are considered to be colinear. New in version 0.17. Attributes
covariance_list of len n_classes of ndarray of shape (n_features, n_features)
For each class, gives the covariance matrix estimated using the samples of that class. The estimations are unbiased. Only present if store_covariance is True.
means_array-like of shape (n_classes, n_features)
Class-wise means.
priors_array-like of shape (n_classes,)
Class priors (sum to 1).
rotations_list of len n_classes of ndarray of shape (n_features, n_k)
For each class k an array of shape (n_features, n_k), where n_k = min(n_features, number of elements in class k) It is the rotation of the Gaussian distribution, i.e. its principal axis. It corresponds to V, the matrix of eigenvectors coming from the SVD of Xk = U S Vt where Xk is the centered matrix of samples from class k.
scalings_list of len n_classes of ndarray of shape (n_k,)
For each class, contains the scaling of the Gaussian distributions along its principal axes, i.e. the variance in the rotated coordinate system. It corresponds to S^2 /
(n_samples - 1), where S is the diagonal matrix of singular values from the SVD of Xk, where Xk is the centered matrix of samples from class k.
classes_ndarray of shape (n_classes,)
Unique class labels. See also
LinearDiscriminantAnalysis
Linear Discriminant Analysis. Examples >>> from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = QuadraticDiscriminantAnalysis()
>>> clf.fit(X, y)
QuadraticDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
Methods
decision_function(X) Apply decision function to an array of samples.
fit(X, y) Fit the model according to the given training data and parameters.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on an array of test vectors X.
predict_log_proba(X) Return log of posterior probabilities of classification.
predict_proba(X) Return posterior probabilities of classification.
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.
decision_function(X) [source]
Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples (test vectors). Returns
Cndarray of shape (n_samples,) or (n_samples, n_classes)
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.
fit(X, y) [source]
Fit the model according to the given training data and parameters. Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance Changed in version 0.19: tol has been moved to main constructor. Parameters
Xarray-like of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
Target values (integers)
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.
predict(X) [source]
Perform classification on an array of test vectors X. The predicted class C for each sample in X is returned. Parameters
Xarray-like of shape (n_samples, n_features)
Returns
Cndarray of shape (n_samples,)
predict_log_proba(X) [source]
Return log of posterior probabilities of classification. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples/test vectors. Returns
Cndarray of shape (n_samples, n_classes)
Posterior log-probabilities of classification per class.
predict_proba(X) [source]
Return posterior probabilities of classification. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples/test vectors. Returns
Cndarray of shape (n_samples, n_classes)
Posterior probabilities of classification per class.
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.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis |
sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis
class sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis(*, priors=None, reg_param=0.0, store_covariance=False, tol=0.0001) [source]
Quadratic Discriminant Analysis A classifier with a quadratic decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule. The model fits a Gaussian density to each class. New in version 0.17: QuadraticDiscriminantAnalysis Read more in the User Guide. Parameters
priorsndarray of shape (n_classes,), default=None
Class priors. By default, the class proportions are inferred from the training data.
reg_paramfloat, default=0.0
Regularizes the per-class covariance estimates by transforming S2 as S2 = (1 - reg_param) * S2 + reg_param * np.eye(n_features), where S2 corresponds to the scaling_ attribute of a given class.
store_covariancebool, default=False
If True, the class covariance matrices are explicitely computed and stored in the self.covariance_ attribute. New in version 0.17.
tolfloat, default=1.0e-4
Absolute threshold for a singular value to be considered significant, used to estimate the rank of Xk where Xk is the centered matrix of samples in class k. This parameter does not affect the predictions. It only controls a warning that is raised when features are considered to be colinear. New in version 0.17. Attributes
covariance_list of len n_classes of ndarray of shape (n_features, n_features)
For each class, gives the covariance matrix estimated using the samples of that class. The estimations are unbiased. Only present if store_covariance is True.
means_array-like of shape (n_classes, n_features)
Class-wise means.
priors_array-like of shape (n_classes,)
Class priors (sum to 1).
rotations_list of len n_classes of ndarray of shape (n_features, n_k)
For each class k an array of shape (n_features, n_k), where n_k = min(n_features, number of elements in class k) It is the rotation of the Gaussian distribution, i.e. its principal axis. It corresponds to V, the matrix of eigenvectors coming from the SVD of Xk = U S Vt where Xk is the centered matrix of samples from class k.
scalings_list of len n_classes of ndarray of shape (n_k,)
For each class, contains the scaling of the Gaussian distributions along its principal axes, i.e. the variance in the rotated coordinate system. It corresponds to S^2 /
(n_samples - 1), where S is the diagonal matrix of singular values from the SVD of Xk, where Xk is the centered matrix of samples from class k.
classes_ndarray of shape (n_classes,)
Unique class labels. See also
LinearDiscriminantAnalysis
Linear Discriminant Analysis. Examples >>> from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = QuadraticDiscriminantAnalysis()
>>> clf.fit(X, y)
QuadraticDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
Methods
decision_function(X) Apply decision function to an array of samples.
fit(X, y) Fit the model according to the given training data and parameters.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on an array of test vectors X.
predict_log_proba(X) Return log of posterior probabilities of classification.
predict_proba(X) Return posterior probabilities of classification.
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.
decision_function(X) [source]
Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples (test vectors). Returns
Cndarray of shape (n_samples,) or (n_samples, n_classes)
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.
fit(X, y) [source]
Fit the model according to the given training data and parameters. Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance Changed in version 0.19: tol has been moved to main constructor. Parameters
Xarray-like of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
Target values (integers)
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.
predict(X) [source]
Perform classification on an array of test vectors X. The predicted class C for each sample in X is returned. Parameters
Xarray-like of shape (n_samples, n_features)
Returns
Cndarray of shape (n_samples,)
predict_log_proba(X) [source]
Return log of posterior probabilities of classification. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples/test vectors. Returns
Cndarray of shape (n_samples, n_classes)
Posterior log-probabilities of classification per class.
predict_proba(X) [source]
Return posterior probabilities of classification. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples/test vectors. Returns
Cndarray of shape (n_samples, n_classes)
Posterior probabilities of classification per class.
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.discriminant_analysis.QuadraticDiscriminantAnalysis
Classifier comparison
Linear and Quadratic Discriminant Analysis with covariance ellipsoid | sklearn.modules.generated.sklearn.discriminant_analysis.quadraticdiscriminantanalysis |
decision_function(X) [source]
Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples (test vectors). Returns
Cndarray of shape (n_samples,) or (n_samples, n_classes)
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class. | sklearn.modules.generated.sklearn.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis.decision_function |
fit(X, y) [source]
Fit the model according to the given training data and parameters. Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance Changed in version 0.19: tol has been moved to main constructor. Parameters
Xarray-like of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)
Target values (integers) | sklearn.modules.generated.sklearn.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis.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.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis.get_params |
predict(X) [source]
Perform classification on an array of test vectors X. The predicted class C for each sample in X is returned. Parameters
Xarray-like of shape (n_samples, n_features)
Returns
Cndarray of shape (n_samples,) | sklearn.modules.generated.sklearn.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis.predict |
predict_log_proba(X) [source]
Return log of posterior probabilities of classification. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples/test vectors. Returns
Cndarray of shape (n_samples, n_classes)
Posterior log-probabilities of classification per class. | sklearn.modules.generated.sklearn.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis.predict_log_proba |
predict_proba(X) [source]
Return posterior probabilities of classification. Parameters
Xarray-like of shape (n_samples, n_features)
Array of samples/test vectors. Returns
Cndarray of shape (n_samples, n_classes)
Posterior probabilities of classification per class. | sklearn.modules.generated.sklearn.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis.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.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis.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.discriminant_analysis.quadraticdiscriminantanalysis#sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis.set_params |
class sklearn.dummy.DummyClassifier(*, strategy='prior', random_state=None, constant=None) [source]
DummyClassifier is a classifier that makes predictions using simple rules. This classifier is useful as a simple baseline to compare with other (real) classifiers. Do not use it for real problems. Read more in the User Guide. New in version 0.13. Parameters
strategy{“stratified”, “most_frequent”, “prior”, “uniform”, “constant”}, default=”prior”
Strategy to use to generate predictions. “stratified”: generates predictions by respecting the training set’s class distribution. “most_frequent”: always predicts the most frequent label in the training set. “prior”: always predicts the class that maximizes the class prior (like “most_frequent”) and predict_proba returns the class prior. “uniform”: generates predictions uniformly at random.
“constant”: always predicts a constant label that is provided by the user. This is useful for metrics that evaluate a non-majority class Changed in version 0.24: The default value of strategy has changed to “prior” in version 0.24.
random_stateint, RandomState instance or None, default=None
Controls the randomness to generate the predictions when strategy='stratified' or strategy='uniform'. Pass an int for reproducible output across multiple function calls. See Glossary.
constantint or str or array-like of shape (n_outputs,)
The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy. Attributes
classes_ndarray of shape (n_classes,) or list of such arrays
Class labels for each output.
n_classes_int or list of int
Number of label for each output.
class_prior_ndarray of shape (n_classes,) or list of such arrays
Probability of each class for each output.
n_outputs_int
Number of outputs.
sparse_output_bool
True if the array returned from predict is to be in sparse CSC format. Is automatically set to True if the input y is passed in sparse format. Examples >>> import numpy as np
>>> from sklearn.dummy import DummyClassifier
>>> X = np.array([-1, 1, 1, 1])
>>> y = np.array([0, 1, 1, 1])
>>> dummy_clf = DummyClassifier(strategy="most_frequent")
>>> dummy_clf.fit(X, y)
DummyClassifier(strategy='most_frequent')
>>> dummy_clf.predict(X)
array([1, 1, 1, 1])
>>> dummy_clf.score(X, y)
0.75
Methods
fit(X, y[, sample_weight]) Fit the random classifier.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on test vectors X.
predict_log_proba(X) Return log probability estimates for the test vectors X.
predict_proba(X) Return probability estimates for the test vectors X.
score(X, y[, sample_weight]) Returns the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit the random classifier. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Target values.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
selfobject
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.
predict(X) [source]
Perform classification on test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Predicted target values for X.
predict_log_proba(X) [source]
Return log probability estimates for the test vectors X. Parameters
X{array-like, object with finite length or shape}
Training data, requires length = n_samples Returns
Pndarray of shape (n_samples, n_classes) or list of such arrays
Returns the log probability of the sample for each class in the model, where classes are ordered arithmetically for each output.
predict_proba(X) [source]
Return probability estimates for the test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data. Returns
Pndarray of shape (n_samples, n_classes) or list of such arrays
Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output.
score(X, y, sample_weight=None) [source]
Returns 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
XNone or array-like of shape (n_samples, n_features)
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyClassifier operates independently of the sampled observations.
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.dummy.dummyclassifier#sklearn.dummy.DummyClassifier |
sklearn.dummy.DummyClassifier
class sklearn.dummy.DummyClassifier(*, strategy='prior', random_state=None, constant=None) [source]
DummyClassifier is a classifier that makes predictions using simple rules. This classifier is useful as a simple baseline to compare with other (real) classifiers. Do not use it for real problems. Read more in the User Guide. New in version 0.13. Parameters
strategy{“stratified”, “most_frequent”, “prior”, “uniform”, “constant”}, default=”prior”
Strategy to use to generate predictions. “stratified”: generates predictions by respecting the training set’s class distribution. “most_frequent”: always predicts the most frequent label in the training set. “prior”: always predicts the class that maximizes the class prior (like “most_frequent”) and predict_proba returns the class prior. “uniform”: generates predictions uniformly at random.
“constant”: always predicts a constant label that is provided by the user. This is useful for metrics that evaluate a non-majority class Changed in version 0.24: The default value of strategy has changed to “prior” in version 0.24.
random_stateint, RandomState instance or None, default=None
Controls the randomness to generate the predictions when strategy='stratified' or strategy='uniform'. Pass an int for reproducible output across multiple function calls. See Glossary.
constantint or str or array-like of shape (n_outputs,)
The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy. Attributes
classes_ndarray of shape (n_classes,) or list of such arrays
Class labels for each output.
n_classes_int or list of int
Number of label for each output.
class_prior_ndarray of shape (n_classes,) or list of such arrays
Probability of each class for each output.
n_outputs_int
Number of outputs.
sparse_output_bool
True if the array returned from predict is to be in sparse CSC format. Is automatically set to True if the input y is passed in sparse format. Examples >>> import numpy as np
>>> from sklearn.dummy import DummyClassifier
>>> X = np.array([-1, 1, 1, 1])
>>> y = np.array([0, 1, 1, 1])
>>> dummy_clf = DummyClassifier(strategy="most_frequent")
>>> dummy_clf.fit(X, y)
DummyClassifier(strategy='most_frequent')
>>> dummy_clf.predict(X)
array([1, 1, 1, 1])
>>> dummy_clf.score(X, y)
0.75
Methods
fit(X, y[, sample_weight]) Fit the random classifier.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on test vectors X.
predict_log_proba(X) Return log probability estimates for the test vectors X.
predict_proba(X) Return probability estimates for the test vectors X.
score(X, y[, sample_weight]) Returns the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit the random classifier. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Target values.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
selfobject
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.
predict(X) [source]
Perform classification on test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Predicted target values for X.
predict_log_proba(X) [source]
Return log probability estimates for the test vectors X. Parameters
X{array-like, object with finite length or shape}
Training data, requires length = n_samples Returns
Pndarray of shape (n_samples, n_classes) or list of such arrays
Returns the log probability of the sample for each class in the model, where classes are ordered arithmetically for each output.
predict_proba(X) [source]
Return probability estimates for the test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data. Returns
Pndarray of shape (n_samples, n_classes) or list of such arrays
Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output.
score(X, y, sample_weight=None) [source]
Returns 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
XNone or array-like of shape (n_samples, n_features)
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyClassifier operates independently of the sampled observations.
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.dummy.dummyclassifier |
fit(X, y, sample_weight=None) [source]
Fit the random classifier. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Target values.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
selfobject | sklearn.modules.generated.sklearn.dummy.dummyclassifier#sklearn.dummy.DummyClassifier.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.dummy.dummyclassifier#sklearn.dummy.DummyClassifier.get_params |
predict(X) [source]
Perform classification on test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Predicted target values for X. | sklearn.modules.generated.sklearn.dummy.dummyclassifier#sklearn.dummy.DummyClassifier.predict |
predict_log_proba(X) [source]
Return log probability estimates for the test vectors X. Parameters
X{array-like, object with finite length or shape}
Training data, requires length = n_samples Returns
Pndarray of shape (n_samples, n_classes) or list of such arrays
Returns the log probability of the sample for each class in the model, where classes are ordered arithmetically for each output. | sklearn.modules.generated.sklearn.dummy.dummyclassifier#sklearn.dummy.DummyClassifier.predict_log_proba |
predict_proba(X) [source]
Return probability estimates for the test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data. Returns
Pndarray of shape (n_samples, n_classes) or list of such arrays
Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output. | sklearn.modules.generated.sklearn.dummy.dummyclassifier#sklearn.dummy.DummyClassifier.predict_proba |
score(X, y, sample_weight=None) [source]
Returns 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
XNone or array-like of shape (n_samples, n_features)
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyClassifier operates independently of the sampled observations.
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.dummy.dummyclassifier#sklearn.dummy.DummyClassifier.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.dummy.dummyclassifier#sklearn.dummy.DummyClassifier.set_params |
class sklearn.dummy.DummyRegressor(*, strategy='mean', constant=None, quantile=None) [source]
DummyRegressor is a regressor that makes predictions using simple rules. This regressor is useful as a simple baseline to compare with other (real) regressors. Do not use it for real problems. Read more in the User Guide. New in version 0.13. Parameters
strategy{“mean”, “median”, “quantile”, “constant”}, default=”mean”
Strategy to use to generate predictions. “mean”: always predicts the mean of the training set “median”: always predicts the median of the training set “quantile”: always predicts a specified quantile of the training set, provided with the quantile parameter. “constant”: always predicts a constant value that is provided by the user.
constantint or float or array-like of shape (n_outputs,), default=None
The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.
quantilefloat in [0.0, 1.0], default=None
The quantile to predict using the “quantile” strategy. A quantile of 0.5 corresponds to the median, while 0.0 to the minimum and 1.0 to the maximum. Attributes
constant_ndarray of shape (1, n_outputs)
Mean or median or quantile of the training targets or constant value given by the user.
n_outputs_int
Number of outputs. Examples >>> import numpy as np
>>> from sklearn.dummy import DummyRegressor
>>> X = np.array([1.0, 2.0, 3.0, 4.0])
>>> y = np.array([2.0, 3.0, 5.0, 10.0])
>>> dummy_regr = DummyRegressor(strategy="mean")
>>> dummy_regr.fit(X, y)
DummyRegressor()
>>> dummy_regr.predict(X)
array([5., 5., 5., 5.])
>>> dummy_regr.score(X, y)
0.0
Methods
fit(X, y[, sample_weight]) Fit the random regressor.
get_params([deep]) Get parameters for this estimator.
predict(X[, return_std]) Perform classification on test vectors X.
score(X, y[, sample_weight]) Returns the coefficient of determination R^2 of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit the random regressor. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Target values.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
selfobject
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.
predict(X, return_std=False) [source]
Perform classification on test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data.
return_stdbool, default=False
Whether to return the standard deviation of posterior prediction. All zeros in this case. New in version 0.20. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Predicted target values for X.
y_stdarray-like of shape (n_samples,) or (n_samples, n_outputs)
Standard deviation of predictive distribution of query points.
score(X, y, sample_weight=None) [source]
Returns the coefficient of determination R^2 of the prediction. The coefficient R^2 is defined as (1 - 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
XNone or array-like of shape (n_samples, n_features)
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
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.
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.dummy.dummyregressor#sklearn.dummy.DummyRegressor |
sklearn.dummy.DummyRegressor
class sklearn.dummy.DummyRegressor(*, strategy='mean', constant=None, quantile=None) [source]
DummyRegressor is a regressor that makes predictions using simple rules. This regressor is useful as a simple baseline to compare with other (real) regressors. Do not use it for real problems. Read more in the User Guide. New in version 0.13. Parameters
strategy{“mean”, “median”, “quantile”, “constant”}, default=”mean”
Strategy to use to generate predictions. “mean”: always predicts the mean of the training set “median”: always predicts the median of the training set “quantile”: always predicts a specified quantile of the training set, provided with the quantile parameter. “constant”: always predicts a constant value that is provided by the user.
constantint or float or array-like of shape (n_outputs,), default=None
The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.
quantilefloat in [0.0, 1.0], default=None
The quantile to predict using the “quantile” strategy. A quantile of 0.5 corresponds to the median, while 0.0 to the minimum and 1.0 to the maximum. Attributes
constant_ndarray of shape (1, n_outputs)
Mean or median or quantile of the training targets or constant value given by the user.
n_outputs_int
Number of outputs. Examples >>> import numpy as np
>>> from sklearn.dummy import DummyRegressor
>>> X = np.array([1.0, 2.0, 3.0, 4.0])
>>> y = np.array([2.0, 3.0, 5.0, 10.0])
>>> dummy_regr = DummyRegressor(strategy="mean")
>>> dummy_regr.fit(X, y)
DummyRegressor()
>>> dummy_regr.predict(X)
array([5., 5., 5., 5.])
>>> dummy_regr.score(X, y)
0.0
Methods
fit(X, y[, sample_weight]) Fit the random regressor.
get_params([deep]) Get parameters for this estimator.
predict(X[, return_std]) Perform classification on test vectors X.
score(X, y[, sample_weight]) Returns the coefficient of determination R^2 of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit the random regressor. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Target values.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
selfobject
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.
predict(X, return_std=False) [source]
Perform classification on test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data.
return_stdbool, default=False
Whether to return the standard deviation of posterior prediction. All zeros in this case. New in version 0.20. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Predicted target values for X.
y_stdarray-like of shape (n_samples,) or (n_samples, n_outputs)
Standard deviation of predictive distribution of query points.
score(X, y, sample_weight=None) [source]
Returns the coefficient of determination R^2 of the prediction. The coefficient R^2 is defined as (1 - 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
XNone or array-like of shape (n_samples, n_features)
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
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.
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.dummy.DummyRegressor
Poisson regression and non-normal loss | sklearn.modules.generated.sklearn.dummy.dummyregressor |
fit(X, y, sample_weight=None) [source]
Fit the random regressor. Parameters
Xarray-like of shape (n_samples, n_features)
Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Target values.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
selfobject | sklearn.modules.generated.sklearn.dummy.dummyregressor#sklearn.dummy.DummyRegressor.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.dummy.dummyregressor#sklearn.dummy.DummyRegressor.get_params |
predict(X, return_std=False) [source]
Perform classification on test vectors X. Parameters
Xarray-like of shape (n_samples, n_features)
Test data.
return_stdbool, default=False
Whether to return the standard deviation of posterior prediction. All zeros in this case. New in version 0.20. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Predicted target values for X.
y_stdarray-like of shape (n_samples,) or (n_samples, n_outputs)
Standard deviation of predictive distribution of query points. | sklearn.modules.generated.sklearn.dummy.dummyregressor#sklearn.dummy.DummyRegressor.predict |
score(X, y, sample_weight=None) [source]
Returns the coefficient of determination R^2 of the prediction. The coefficient R^2 is defined as (1 - 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
XNone or array-like of shape (n_samples, n_features)
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
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. | sklearn.modules.generated.sklearn.dummy.dummyregressor#sklearn.dummy.DummyRegressor.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.dummy.dummyregressor#sklearn.dummy.DummyRegressor.set_params |
class sklearn.ensemble.AdaBoostClassifier(base_estimator=None, *, n_estimators=50, learning_rate=1.0, algorithm='SAMME.R', random_state=None) [source]
An AdaBoost classifier. An AdaBoost [1] classifier is a meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset but where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases. This class implements the algorithm known as AdaBoost-SAMME [2]. Read more in the User Guide. New in version 0.14. Parameters
base_estimatorobject, default=None
The base estimator from which the boosted ensemble is built. Support for sample weighting is required, as well as proper classes_ and n_classes_ attributes. If None, then the base estimator is DecisionTreeClassifier initialized with max_depth=1.
n_estimatorsint, default=50
The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
learning_ratefloat, default=1.
Learning rate shrinks the contribution of each classifier by learning_rate. There is a trade-off between learning_rate and n_estimators.
algorithm{‘SAMME’, ‘SAMME.R’}, default=’SAMME.R’
If ‘SAMME.R’ then use the SAMME.R real boosting algorithm. base_estimator must support calculation of class probabilities. If ‘SAMME’ then use the SAMME discrete boosting algorithm. The SAMME.R algorithm typically converges faster than SAMME, achieving a lower test error with fewer boosting iterations.
random_stateint, RandomState instance or None, default=None
Controls the random seed given at each base_estimator at each boosting iteration. Thus, it is only used when base_estimator exposes a random_state. Pass an int for reproducible output across multiple function calls. See Glossary. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
estimators_list of classifiers
The collection of fitted sub-estimators.
classes_ndarray of shape (n_classes,)
The classes labels.
n_classes_int
The number of classes.
estimator_weights_ndarray of floats
Weights for each estimator in the boosted ensemble.
estimator_errors_ndarray of floats
Classification error for each estimator in the boosted ensemble.
feature_importances_ndarray of shape (n_features,)
The impurity-based feature importances. See also
AdaBoostRegressor
An AdaBoost regressor that begins by fitting a regressor on the original dataset and then fits additional copies of the regressor on the same dataset but where the weights of instances are adjusted according to the error of the current prediction.
GradientBoostingClassifier
GB builds an additive model in a forward stage-wise fashion. Regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced.
sklearn.tree.DecisionTreeClassifier
A non-parametric supervised learning method used for classification. Creates a model that predicts the value of a target variable by learning simple decision rules inferred from the data features. References
1
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
2
Zhu, H. Zou, S. Rosset, T. Hastie, “Multi-class AdaBoost”, 2009. Examples >>> from sklearn.ensemble import AdaBoostClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
... n_informative=2, n_redundant=0,
... random_state=0, shuffle=False)
>>> clf = AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
>>> clf.score(X, y)
0.983...
Methods
decision_function(X) Compute the decision function of X.
fit(X, y[, sample_weight]) Build a boosted classifier from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict classes for X.
predict_log_proba(X) Predict class log-probabilities for X.
predict_proba(X) Predict class probabilities for 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.
staged_decision_function(X) Compute decision function of X for each boosting iteration.
staged_predict(X) Return staged predictions for X.
staged_predict_proba(X) Predict class probabilities for X.
staged_score(X, y[, sample_weight]) Return staged scores for X, y.
decision_function(X) [source]
Compute the decision function of X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
scorendarray of shape of (n_samples, k)
The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The feature importances.
fit(X, y, sample_weight=None) [source]
Build a boosted classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
The target values (class labels).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, the sample weights are initialized to 1 / n_samples. Returns
selfobject
Fitted estimator.
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.
predict(X) [source]
Predict classes for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
yndarray of shape (n_samples,)
The predicted classes.
predict_log_proba(X) [source]
Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the weighted mean predicted class log-probabilities of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
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.
staged_decision_function(X) [source]
Compute decision function of X for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
scoregenerator of ndarray of shape (n_samples, k)
The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.
staged_predict(X) [source]
Return staged predictions for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters
Xarray-like of shape (n_samples, n_features)
The input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
ygenerator of ndarray of shape (n_samples,)
The predicted classes.
staged_predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. This generator method yields the ensemble predicted class probabilities after each iteration of boosting and therefore allows monitoring, such as to determine the predicted class probabilities on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
pgenerator of ndarray of shape (n_samples,)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
staged_score(X, y, sample_weight=None) [source]
Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
Labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Yields
zfloat | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier |
sklearn.ensemble.AdaBoostClassifier
class sklearn.ensemble.AdaBoostClassifier(base_estimator=None, *, n_estimators=50, learning_rate=1.0, algorithm='SAMME.R', random_state=None) [source]
An AdaBoost classifier. An AdaBoost [1] classifier is a meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset but where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases. This class implements the algorithm known as AdaBoost-SAMME [2]. Read more in the User Guide. New in version 0.14. Parameters
base_estimatorobject, default=None
The base estimator from which the boosted ensemble is built. Support for sample weighting is required, as well as proper classes_ and n_classes_ attributes. If None, then the base estimator is DecisionTreeClassifier initialized with max_depth=1.
n_estimatorsint, default=50
The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
learning_ratefloat, default=1.
Learning rate shrinks the contribution of each classifier by learning_rate. There is a trade-off between learning_rate and n_estimators.
algorithm{‘SAMME’, ‘SAMME.R’}, default=’SAMME.R’
If ‘SAMME.R’ then use the SAMME.R real boosting algorithm. base_estimator must support calculation of class probabilities. If ‘SAMME’ then use the SAMME discrete boosting algorithm. The SAMME.R algorithm typically converges faster than SAMME, achieving a lower test error with fewer boosting iterations.
random_stateint, RandomState instance or None, default=None
Controls the random seed given at each base_estimator at each boosting iteration. Thus, it is only used when base_estimator exposes a random_state. Pass an int for reproducible output across multiple function calls. See Glossary. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
estimators_list of classifiers
The collection of fitted sub-estimators.
classes_ndarray of shape (n_classes,)
The classes labels.
n_classes_int
The number of classes.
estimator_weights_ndarray of floats
Weights for each estimator in the boosted ensemble.
estimator_errors_ndarray of floats
Classification error for each estimator in the boosted ensemble.
feature_importances_ndarray of shape (n_features,)
The impurity-based feature importances. See also
AdaBoostRegressor
An AdaBoost regressor that begins by fitting a regressor on the original dataset and then fits additional copies of the regressor on the same dataset but where the weights of instances are adjusted according to the error of the current prediction.
GradientBoostingClassifier
GB builds an additive model in a forward stage-wise fashion. Regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced.
sklearn.tree.DecisionTreeClassifier
A non-parametric supervised learning method used for classification. Creates a model that predicts the value of a target variable by learning simple decision rules inferred from the data features. References
1
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
2
Zhu, H. Zou, S. Rosset, T. Hastie, “Multi-class AdaBoost”, 2009. Examples >>> from sklearn.ensemble import AdaBoostClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
... n_informative=2, n_redundant=0,
... random_state=0, shuffle=False)
>>> clf = AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
>>> clf.score(X, y)
0.983...
Methods
decision_function(X) Compute the decision function of X.
fit(X, y[, sample_weight]) Build a boosted classifier from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict classes for X.
predict_log_proba(X) Predict class log-probabilities for X.
predict_proba(X) Predict class probabilities for 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.
staged_decision_function(X) Compute decision function of X for each boosting iteration.
staged_predict(X) Return staged predictions for X.
staged_predict_proba(X) Predict class probabilities for X.
staged_score(X, y[, sample_weight]) Return staged scores for X, y.
decision_function(X) [source]
Compute the decision function of X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
scorendarray of shape of (n_samples, k)
The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The feature importances.
fit(X, y, sample_weight=None) [source]
Build a boosted classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
The target values (class labels).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, the sample weights are initialized to 1 / n_samples. Returns
selfobject
Fitted estimator.
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.
predict(X) [source]
Predict classes for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
yndarray of shape (n_samples,)
The predicted classes.
predict_log_proba(X) [source]
Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the weighted mean predicted class log-probabilities of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
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.
staged_decision_function(X) [source]
Compute decision function of X for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
scoregenerator of ndarray of shape (n_samples, k)
The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.
staged_predict(X) [source]
Return staged predictions for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters
Xarray-like of shape (n_samples, n_features)
The input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
ygenerator of ndarray of shape (n_samples,)
The predicted classes.
staged_predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. This generator method yields the ensemble predicted class probabilities after each iteration of boosting and therefore allows monitoring, such as to determine the predicted class probabilities on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
pgenerator of ndarray of shape (n_samples,)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
staged_score(X, y, sample_weight=None) [source]
Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
Labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Yields
zfloat
Examples using sklearn.ensemble.AdaBoostClassifier
Classifier comparison
Two-class AdaBoost
Multi-class AdaBoosted Decision Trees
Discrete versus Real AdaBoost
Plot the decision surfaces of ensembles of trees on the iris dataset | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier |
decision_function(X) [source]
Compute the decision function of X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
scorendarray of shape of (n_samples, k)
The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.decision_function |
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The feature importances. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.feature_importances_ |
fit(X, y, sample_weight=None) [source]
Build a boosted classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
The target values (class labels).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, the sample weights are initialized to 1 / n_samples. Returns
selfobject
Fitted estimator. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.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.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.get_params |
predict(X) [source]
Predict classes for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
yndarray of shape (n_samples,)
The predicted classes. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.predict |
predict_log_proba(X) [source]
Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the weighted mean predicted class log-probabilities of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.predict_log_proba |
predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.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.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.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.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.set_params |
staged_decision_function(X) [source]
Compute decision function of X for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
scoregenerator of ndarray of shape (n_samples, k)
The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.staged_decision_function |
staged_predict(X) [source]
Return staged predictions for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters
Xarray-like of shape (n_samples, n_features)
The input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
ygenerator of ndarray of shape (n_samples,)
The predicted classes. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.staged_predict |
staged_predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. This generator method yields the ensemble predicted class probabilities after each iteration of boosting and therefore allows monitoring, such as to determine the predicted class probabilities on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields
pgenerator of ndarray of shape (n_samples,)
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute. | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.staged_predict_proba |
staged_score(X, y, sample_weight=None) [source]
Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
Labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Yields
zfloat | sklearn.modules.generated.sklearn.ensemble.adaboostclassifier#sklearn.ensemble.AdaBoostClassifier.staged_score |
class sklearn.ensemble.AdaBoostRegressor(base_estimator=None, *, n_estimators=50, learning_rate=1.0, loss='linear', random_state=None) [source]
An AdaBoost regressor. An AdaBoost [1] regressor is a meta-estimator that begins by fitting a regressor on the original dataset and then fits additional copies of the regressor on the same dataset but where the weights of instances are adjusted according to the error of the current prediction. As such, subsequent regressors focus more on difficult cases. This class implements the algorithm known as AdaBoost.R2 [2]. Read more in the User Guide. New in version 0.14. Parameters
base_estimatorobject, default=None
The base estimator from which the boosted ensemble is built. If None, then the base estimator is DecisionTreeRegressor initialized with max_depth=3.
n_estimatorsint, default=50
The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
learning_ratefloat, default=1.
Learning rate shrinks the contribution of each regressor by learning_rate. There is a trade-off between learning_rate and n_estimators.
loss{‘linear’, ‘square’, ‘exponential’}, default=’linear’
The loss function to use when updating the weights after each boosting iteration.
random_stateint, RandomState instance or None, default=None
Controls the random seed given at each base_estimator at each boosting iteration. Thus, it is only used when base_estimator exposes a random_state. In addition, it controls the bootstrap of the weights used to train the base_estimator at each boosting iteration. Pass an int for reproducible output across multiple function calls. See Glossary. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
estimators_list of classifiers
The collection of fitted sub-estimators.
estimator_weights_ndarray of floats
Weights for each estimator in the boosted ensemble.
estimator_errors_ndarray of floats
Regression error for each estimator in the boosted ensemble.
feature_importances_ndarray of shape (n_features,)
The impurity-based feature importances. See also
AdaBoostClassifier, GradientBoostingRegressor
sklearn.tree.DecisionTreeRegressor
References
1
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
2
Drucker, “Improving Regressors using Boosting Techniques”, 1997. Examples >>> from sklearn.ensemble import AdaBoostRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, n_informative=2,
... random_state=0, shuffle=False)
>>> regr = AdaBoostRegressor(random_state=0, n_estimators=100)
>>> regr.fit(X, y)
AdaBoostRegressor(n_estimators=100, random_state=0)
>>> regr.predict([[0, 0, 0, 0]])
array([4.7972...])
>>> regr.score(X, y)
0.9771...
Methods
fit(X, y[, sample_weight]) Build a boosted regressor from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict regression value for 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.
staged_predict(X) Return staged predictions for X.
staged_score(X, y[, sample_weight]) Return staged scores for X, y.
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The feature importances.
fit(X, y, sample_weight=None) [source]
Build a boosted regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
The target values (real numbers).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, the sample weights are initialized to 1 / n_samples. Returns
selfobject
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.
predict(X) [source]
Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
yndarray of shape (n_samples,)
The predicted regression values.
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.
staged_predict(X) [source]
Return staged predictions for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Yields
ygenerator of ndarray of shape (n_samples,)
The predicted regression values.
staged_score(X, y, sample_weight=None) [source]
Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
Labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Yields
zfloat | sklearn.modules.generated.sklearn.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor |
sklearn.ensemble.AdaBoostRegressor
class sklearn.ensemble.AdaBoostRegressor(base_estimator=None, *, n_estimators=50, learning_rate=1.0, loss='linear', random_state=None) [source]
An AdaBoost regressor. An AdaBoost [1] regressor is a meta-estimator that begins by fitting a regressor on the original dataset and then fits additional copies of the regressor on the same dataset but where the weights of instances are adjusted according to the error of the current prediction. As such, subsequent regressors focus more on difficult cases. This class implements the algorithm known as AdaBoost.R2 [2]. Read more in the User Guide. New in version 0.14. Parameters
base_estimatorobject, default=None
The base estimator from which the boosted ensemble is built. If None, then the base estimator is DecisionTreeRegressor initialized with max_depth=3.
n_estimatorsint, default=50
The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
learning_ratefloat, default=1.
Learning rate shrinks the contribution of each regressor by learning_rate. There is a trade-off between learning_rate and n_estimators.
loss{‘linear’, ‘square’, ‘exponential’}, default=’linear’
The loss function to use when updating the weights after each boosting iteration.
random_stateint, RandomState instance or None, default=None
Controls the random seed given at each base_estimator at each boosting iteration. Thus, it is only used when base_estimator exposes a random_state. In addition, it controls the bootstrap of the weights used to train the base_estimator at each boosting iteration. Pass an int for reproducible output across multiple function calls. See Glossary. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
estimators_list of classifiers
The collection of fitted sub-estimators.
estimator_weights_ndarray of floats
Weights for each estimator in the boosted ensemble.
estimator_errors_ndarray of floats
Regression error for each estimator in the boosted ensemble.
feature_importances_ndarray of shape (n_features,)
The impurity-based feature importances. See also
AdaBoostClassifier, GradientBoostingRegressor
sklearn.tree.DecisionTreeRegressor
References
1
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
2
Drucker, “Improving Regressors using Boosting Techniques”, 1997. Examples >>> from sklearn.ensemble import AdaBoostRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, n_informative=2,
... random_state=0, shuffle=False)
>>> regr = AdaBoostRegressor(random_state=0, n_estimators=100)
>>> regr.fit(X, y)
AdaBoostRegressor(n_estimators=100, random_state=0)
>>> regr.predict([[0, 0, 0, 0]])
array([4.7972...])
>>> regr.score(X, y)
0.9771...
Methods
fit(X, y[, sample_weight]) Build a boosted regressor from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict regression value for 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.
staged_predict(X) Return staged predictions for X.
staged_score(X, y[, sample_weight]) Return staged scores for X, y.
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The feature importances.
fit(X, y, sample_weight=None) [source]
Build a boosted regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
The target values (real numbers).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, the sample weights are initialized to 1 / n_samples. Returns
selfobject
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.
predict(X) [source]
Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
yndarray of shape (n_samples,)
The predicted regression values.
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.
staged_predict(X) [source]
Return staged predictions for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Yields
ygenerator of ndarray of shape (n_samples,)
The predicted regression values.
staged_score(X, y, sample_weight=None) [source]
Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
Labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Yields
zfloat
Examples using sklearn.ensemble.AdaBoostRegressor
Decision Tree Regression with AdaBoost | sklearn.modules.generated.sklearn.ensemble.adaboostregressor |
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The feature importances. | sklearn.modules.generated.sklearn.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor.feature_importances_ |
fit(X, y, sample_weight=None) [source]
Build a boosted regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
The target values (real numbers).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, the sample weights are initialized to 1 / n_samples. Returns
selfobject | sklearn.modules.generated.sklearn.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor.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.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor.get_params |
predict(X) [source]
Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Returns
yndarray of shape (n_samples,)
The predicted regression values. | sklearn.modules.generated.sklearn.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor.predict |
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.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor.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.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor.set_params |
staged_predict(X) [source]
Return staged predictions for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Yields
ygenerator of ndarray of shape (n_samples,)
The predicted regression values. | sklearn.modules.generated.sklearn.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor.staged_predict |
staged_score(X, y, sample_weight=None) [source]
Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)
Labels for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Yields
zfloat | sklearn.modules.generated.sklearn.ensemble.adaboostregressor#sklearn.ensemble.AdaBoostRegressor.staged_score |
class sklearn.ensemble.BaggingClassifier(base_estimator=None, n_estimators=10, *, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0) [source]
A Bagging classifier. A Bagging classifier is an ensemble meta-estimator that fits base classifiers each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it. This algorithm encompasses several works from the literature. When random subsets of the dataset are drawn as random subsets of the samples, then this algorithm is known as Pasting [1]. If samples are drawn with replacement, then the method is known as Bagging [2]. When random subsets of the dataset are drawn as random subsets of the features, then the method is known as Random Subspaces [3]. Finally, when base estimators are built on subsets of both samples and features, then the method is known as Random Patches [4]. Read more in the User Guide. New in version 0.15. Parameters
base_estimatorobject, default=None
The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeClassifier.
n_estimatorsint, default=10
The number of base estimators in the ensemble.
max_samplesint or float, default=1.0
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details). If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples.
max_featuresint or float, default=1.0
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details). If int, then draw max_features features. If float, then draw max_features * X.shape[1] features.
bootstrapbool, default=True
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
bootstrap_featuresbool, default=False
Whether features are drawn with replacement.
oob_scorebool, default=False
Whether to use out-of-bag samples to estimate the generalization error.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new ensemble. See the Glossary. New in version 0.17: warm_start constructor parameter.
n_jobsint, default=None
The number of jobs to run in parallel for both fit and predict. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance or None, default=None
Controls the random resampling of the original dataset (sample wise and feature wise). If the base estimator accepts a random_state attribute, a different seed is generated for each instance in the ensemble. Pass an int for reproducible output across multiple function calls. See Glossary.
verboseint, default=0
Controls the verbosity when fitting and predicting. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
n_features_int
The number of features when fit is performed.
estimators_list of estimators
The collection of fitted base estimators.
estimators_samples_list of arrays
The subset of drawn samples for each base estimator.
estimators_features_list of arrays
The subset of drawn features for each base estimator.
classes_ndarray of shape (n_classes,)
The classes labels.
n_classes_int or list
The number of classes.
oob_score_float
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
oob_decision_function_ndarray of shape (n_samples, n_classes)
Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_decision_function_ might contain NaN. This attribute exists only when oob_score is True. References
1
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
2
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
3
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
4
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012. Examples >>> from sklearn.svm import SVC
>>> from sklearn.ensemble import BaggingClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=100, n_features=4,
... n_informative=2, n_redundant=0,
... random_state=0, shuffle=False)
>>> clf = BaggingClassifier(base_estimator=SVC(),
... n_estimators=10, random_state=0).fit(X, y)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
Methods
decision_function(X) Average of the decision functions of the base classifiers.
fit(X, y[, sample_weight]) Build a Bagging ensemble of estimators from the training
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class for X.
predict_log_proba(X) Predict class log-probabilities for X.
predict_proba(X) Predict class probabilities for 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.
decision_function(X) [source]
Average of the decision functions of the base classifiers. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
scorendarray of shape (n_samples, k)
The decision function of the input samples. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Regression and binary classification are special cases with k == 1, otherwise k==n_classes.
property estimators_samples_
The subset of drawn samples for each base estimator. Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples. Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected.
fit(X, y, sample_weight=None) [source]
Build a Bagging ensemble of estimators from the training
set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting. Returns
selfobject
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.
predict(X) [source]
Predict class for X. The predicted class of an input sample is computed as the class with the highest mean predicted probability. If base estimators do not implement a predict_proba method, then it resorts to voting. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
yndarray of shape (n_samples,)
The predicted classes.
predict_log_proba(X) [source]
Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the base estimators in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
pndarray of shape (n_samples, n_classes)
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble. If base estimators do not implement a predict_proba method, then it resorts to voting and the predicted class probabilities of an input sample represents the proportion of estimators predicting each class. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the classes corresponds to that 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.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier |
sklearn.ensemble.BaggingClassifier
class sklearn.ensemble.BaggingClassifier(base_estimator=None, n_estimators=10, *, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0) [source]
A Bagging classifier. A Bagging classifier is an ensemble meta-estimator that fits base classifiers each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it. This algorithm encompasses several works from the literature. When random subsets of the dataset are drawn as random subsets of the samples, then this algorithm is known as Pasting [1]. If samples are drawn with replacement, then the method is known as Bagging [2]. When random subsets of the dataset are drawn as random subsets of the features, then the method is known as Random Subspaces [3]. Finally, when base estimators are built on subsets of both samples and features, then the method is known as Random Patches [4]. Read more in the User Guide. New in version 0.15. Parameters
base_estimatorobject, default=None
The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeClassifier.
n_estimatorsint, default=10
The number of base estimators in the ensemble.
max_samplesint or float, default=1.0
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details). If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples.
max_featuresint or float, default=1.0
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details). If int, then draw max_features features. If float, then draw max_features * X.shape[1] features.
bootstrapbool, default=True
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
bootstrap_featuresbool, default=False
Whether features are drawn with replacement.
oob_scorebool, default=False
Whether to use out-of-bag samples to estimate the generalization error.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new ensemble. See the Glossary. New in version 0.17: warm_start constructor parameter.
n_jobsint, default=None
The number of jobs to run in parallel for both fit and predict. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance or None, default=None
Controls the random resampling of the original dataset (sample wise and feature wise). If the base estimator accepts a random_state attribute, a different seed is generated for each instance in the ensemble. Pass an int for reproducible output across multiple function calls. See Glossary.
verboseint, default=0
Controls the verbosity when fitting and predicting. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
n_features_int
The number of features when fit is performed.
estimators_list of estimators
The collection of fitted base estimators.
estimators_samples_list of arrays
The subset of drawn samples for each base estimator.
estimators_features_list of arrays
The subset of drawn features for each base estimator.
classes_ndarray of shape (n_classes,)
The classes labels.
n_classes_int or list
The number of classes.
oob_score_float
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
oob_decision_function_ndarray of shape (n_samples, n_classes)
Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_decision_function_ might contain NaN. This attribute exists only when oob_score is True. References
1
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
2
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
3
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
4
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012. Examples >>> from sklearn.svm import SVC
>>> from sklearn.ensemble import BaggingClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=100, n_features=4,
... n_informative=2, n_redundant=0,
... random_state=0, shuffle=False)
>>> clf = BaggingClassifier(base_estimator=SVC(),
... n_estimators=10, random_state=0).fit(X, y)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
Methods
decision_function(X) Average of the decision functions of the base classifiers.
fit(X, y[, sample_weight]) Build a Bagging ensemble of estimators from the training
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class for X.
predict_log_proba(X) Predict class log-probabilities for X.
predict_proba(X) Predict class probabilities for 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.
decision_function(X) [source]
Average of the decision functions of the base classifiers. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
scorendarray of shape (n_samples, k)
The decision function of the input samples. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Regression and binary classification are special cases with k == 1, otherwise k==n_classes.
property estimators_samples_
The subset of drawn samples for each base estimator. Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples. Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected.
fit(X, y, sample_weight=None) [source]
Build a Bagging ensemble of estimators from the training
set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting. Returns
selfobject
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.
predict(X) [source]
Predict class for X. The predicted class of an input sample is computed as the class with the highest mean predicted probability. If base estimators do not implement a predict_proba method, then it resorts to voting. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
yndarray of shape (n_samples,)
The predicted classes.
predict_log_proba(X) [source]
Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the base estimators in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
pndarray of shape (n_samples, n_classes)
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble. If base estimators do not implement a predict_proba method, then it resorts to voting and the predicted class probabilities of an input sample represents the proportion of estimators predicting each class. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the classes corresponds to that 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.ensemble.baggingclassifier |
decision_function(X) [source]
Average of the decision functions of the base classifiers. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
scorendarray of shape (n_samples, k)
The decision function of the input samples. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Regression and binary classification are special cases with k == 1, otherwise k==n_classes. | sklearn.modules.generated.sklearn.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.decision_function |
property estimators_samples_
The subset of drawn samples for each base estimator. Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples. Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected. | sklearn.modules.generated.sklearn.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.estimators_samples_ |
fit(X, y, sample_weight=None) [source]
Build a Bagging ensemble of estimators from the training
set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting. Returns
selfobject | sklearn.modules.generated.sklearn.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.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.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.get_params |
predict(X) [source]
Predict class for X. The predicted class of an input sample is computed as the class with the highest mean predicted probability. If base estimators do not implement a predict_proba method, then it resorts to voting. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
yndarray of shape (n_samples,)
The predicted classes. | sklearn.modules.generated.sklearn.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.predict |
predict_log_proba(X) [source]
Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the base estimators in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
pndarray of shape (n_samples, n_classes)
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. | sklearn.modules.generated.sklearn.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.predict_log_proba |
predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble. If base estimators do not implement a predict_proba method, then it resorts to voting and the predicted class probabilities of an input sample represents the proportion of estimators predicting each class. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. | sklearn.modules.generated.sklearn.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.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.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.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.ensemble.baggingclassifier#sklearn.ensemble.BaggingClassifier.set_params |
class sklearn.ensemble.BaggingRegressor(base_estimator=None, n_estimators=10, *, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0) [source]
A Bagging regressor. A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it. This algorithm encompasses several works from the literature. When random subsets of the dataset are drawn as random subsets of the samples, then this algorithm is known as Pasting [1]. If samples are drawn with replacement, then the method is known as Bagging [2]. When random subsets of the dataset are drawn as random subsets of the features, then the method is known as Random Subspaces [3]. Finally, when base estimators are built on subsets of both samples and features, then the method is known as Random Patches [4]. Read more in the User Guide. New in version 0.15. Parameters
base_estimatorobject, default=None
The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeRegressor.
n_estimatorsint, default=10
The number of base estimators in the ensemble.
max_samplesint or float, default=1.0
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details). If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples.
max_featuresint or float, default=1.0
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details). If int, then draw max_features features. If float, then draw max_features * X.shape[1] features.
bootstrapbool, default=True
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
bootstrap_featuresbool, default=False
Whether features are drawn with replacement.
oob_scorebool, default=False
Whether to use out-of-bag samples to estimate the generalization error.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new ensemble. See the Glossary.
n_jobsint, default=None
The number of jobs to run in parallel for both fit and predict. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance or None, default=None
Controls the random resampling of the original dataset (sample wise and feature wise). If the base estimator accepts a random_state attribute, a different seed is generated for each instance in the ensemble. Pass an int for reproducible output across multiple function calls. See Glossary.
verboseint, default=0
Controls the verbosity when fitting and predicting. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
n_features_int
The number of features when fit is performed.
estimators_list of estimators
The collection of fitted sub-estimators.
estimators_samples_list of arrays
The subset of drawn samples for each base estimator.
estimators_features_list of arrays
The subset of drawn features for each base estimator.
oob_score_float
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
oob_prediction_ndarray of shape (n_samples,)
Prediction computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_prediction_ might contain NaN. This attribute exists only when oob_score is True. References
1
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
2
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
3
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
4
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012. Examples >>> from sklearn.svm import SVR
>>> from sklearn.ensemble import BaggingRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_samples=100, n_features=4,
... n_informative=2, n_targets=1,
... random_state=0, shuffle=False)
>>> regr = BaggingRegressor(base_estimator=SVR(),
... n_estimators=10, random_state=0).fit(X, y)
>>> regr.predict([[0, 0, 0, 0]])
array([-2.8720...])
Methods
fit(X, y[, sample_weight]) Build a Bagging ensemble of estimators from the training
get_params([deep]) Get parameters for this estimator.
predict(X) Predict regression target for 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.
property estimators_samples_
The subset of drawn samples for each base estimator. Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples. Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected.
fit(X, y, sample_weight=None) [source]
Build a Bagging ensemble of estimators from the training
set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting. Returns
selfobject
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.
predict(X) [source]
Predict regression target for X. The predicted regression target of an input sample is computed as the mean predicted regression targets of the estimators in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
yndarray of shape (n_samples,)
The predicted values.
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.ensemble.baggingregressor#sklearn.ensemble.BaggingRegressor |
sklearn.ensemble.BaggingRegressor
class sklearn.ensemble.BaggingRegressor(base_estimator=None, n_estimators=10, *, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0) [source]
A Bagging regressor. A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it. This algorithm encompasses several works from the literature. When random subsets of the dataset are drawn as random subsets of the samples, then this algorithm is known as Pasting [1]. If samples are drawn with replacement, then the method is known as Bagging [2]. When random subsets of the dataset are drawn as random subsets of the features, then the method is known as Random Subspaces [3]. Finally, when base estimators are built on subsets of both samples and features, then the method is known as Random Patches [4]. Read more in the User Guide. New in version 0.15. Parameters
base_estimatorobject, default=None
The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeRegressor.
n_estimatorsint, default=10
The number of base estimators in the ensemble.
max_samplesint or float, default=1.0
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details). If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples.
max_featuresint or float, default=1.0
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details). If int, then draw max_features features. If float, then draw max_features * X.shape[1] features.
bootstrapbool, default=True
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
bootstrap_featuresbool, default=False
Whether features are drawn with replacement.
oob_scorebool, default=False
Whether to use out-of-bag samples to estimate the generalization error.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new ensemble. See the Glossary.
n_jobsint, default=None
The number of jobs to run in parallel for both fit and predict. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance or None, default=None
Controls the random resampling of the original dataset (sample wise and feature wise). If the base estimator accepts a random_state attribute, a different seed is generated for each instance in the ensemble. Pass an int for reproducible output across multiple function calls. See Glossary.
verboseint, default=0
Controls the verbosity when fitting and predicting. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
n_features_int
The number of features when fit is performed.
estimators_list of estimators
The collection of fitted sub-estimators.
estimators_samples_list of arrays
The subset of drawn samples for each base estimator.
estimators_features_list of arrays
The subset of drawn features for each base estimator.
oob_score_float
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
oob_prediction_ndarray of shape (n_samples,)
Prediction computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_prediction_ might contain NaN. This attribute exists only when oob_score is True. References
1
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
2
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
3
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
4
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012. Examples >>> from sklearn.svm import SVR
>>> from sklearn.ensemble import BaggingRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_samples=100, n_features=4,
... n_informative=2, n_targets=1,
... random_state=0, shuffle=False)
>>> regr = BaggingRegressor(base_estimator=SVR(),
... n_estimators=10, random_state=0).fit(X, y)
>>> regr.predict([[0, 0, 0, 0]])
array([-2.8720...])
Methods
fit(X, y[, sample_weight]) Build a Bagging ensemble of estimators from the training
get_params([deep]) Get parameters for this estimator.
predict(X) Predict regression target for 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.
property estimators_samples_
The subset of drawn samples for each base estimator. Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples. Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected.
fit(X, y, sample_weight=None) [source]
Build a Bagging ensemble of estimators from the training
set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting. Returns
selfobject
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.
predict(X) [source]
Predict regression target for X. The predicted regression target of an input sample is computed as the mean predicted regression targets of the estimators in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
yndarray of shape (n_samples,)
The predicted values.
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.ensemble.BaggingRegressor
Single estimator versus bagging: bias-variance decomposition | sklearn.modules.generated.sklearn.ensemble.baggingregressor |
property estimators_samples_
The subset of drawn samples for each base estimator. Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples. Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected. | sklearn.modules.generated.sklearn.ensemble.baggingregressor#sklearn.ensemble.BaggingRegressor.estimators_samples_ |
fit(X, y, sample_weight=None) [source]
Build a Bagging ensemble of estimators from the training
set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting. Returns
selfobject | sklearn.modules.generated.sklearn.ensemble.baggingregressor#sklearn.ensemble.BaggingRegressor.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.ensemble.baggingregressor#sklearn.ensemble.BaggingRegressor.get_params |
predict(X) [source]
Predict regression target for X. The predicted regression target of an input sample is computed as the mean predicted regression targets of the estimators in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
yndarray of shape (n_samples,)
The predicted values. | sklearn.modules.generated.sklearn.ensemble.baggingregressor#sklearn.ensemble.BaggingRegressor.predict |
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.ensemble.baggingregressor#sklearn.ensemble.BaggingRegressor.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.ensemble.baggingregressor#sklearn.ensemble.BaggingRegressor.set_params |
class sklearn.ensemble.ExtraTreesClassifier(n_estimators=100, *, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None) [source]
An extra-trees classifier. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. Read more in the User Guide. Parameters
n_estimatorsint, default=100
The number of trees in the forest. Changed in version 0.22: The default value of n_estimators changed from 10 to 100 in 0.22.
criterion{“gini”, “entropy”}, default=”gini”
The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain.
max_depthint, default=None
The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.
min_samples_splitint or float, default=2
The minimum number of samples required to split an internal node: If int, then consider min_samples_split as the minimum number. If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split. Changed in version 0.18: Added float values for fractions.
min_samples_leafint or float, default=1
The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. If int, then consider min_samples_leaf as the minimum number. If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node. Changed in version 0.18: Added float values for fractions.
min_weight_fraction_leaffloat, default=0.0
The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.
max_features{“auto”, “sqrt”, “log2”}, int or float, default=”auto”
The number of features to consider when looking for the best split: If int, then consider max_features features at each split. If float, then max_features is a fraction and round(max_features * n_features) features are considered at each split. If “auto”, then max_features=sqrt(n_features). If “sqrt”, then max_features=sqrt(n_features). If “log2”, then max_features=log2(n_features). If None, then max_features=n_features. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.
max_leaf_nodesint, default=None
Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.
min_impurity_decreasefloat, default=0.0
A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following: N_t / N * (impurity - N_t_R / N_t * right_impurity
- N_t_L / N_t * left_impurity)
where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child. N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed. New in version 0.19.
min_impurity_splitfloat, default=None
Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use min_impurity_decrease instead.
bootstrapbool, default=False
Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree.
oob_scorebool, default=False
Whether to use out-of-bag samples to estimate the generalization accuracy.
n_jobsint, default=None
The number of jobs to run in parallel. fit, predict, decision_path and apply are all parallelized over the trees. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance or None, default=None
Controls 3 sources of randomness: the bootstrapping of the samples used when building trees (if bootstrap=True) the sampling of the features to consider when looking for the best split at each node (if max_features < n_features) the draw of the splits for each of the max_features
See Glossary for details.
verboseint, default=0
Controls the verbosity when fitting and predicting.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See the Glossary.
class_weight{“balanced”, “balanced_subsample”}, dict or list of dicts, default=None
Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)) The “balanced_subsample” mode is the same as “balanced” except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified.
ccp_alphanon-negative float, default=0.0
Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details. New in version 0.22.
max_samplesint or float, default=None
If bootstrap is True, the number of samples to draw from X to train each base estimator. If None (default), then draw X.shape[0] samples. If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples. Thus, max_samples should be in the interval (0, 1). New in version 0.22. Attributes
base_estimator_ExtraTreesClassifier
The child estimator template used to create the collection of fitted sub-estimators.
estimators_list of DecisionTreeClassifier
The collection of fitted sub-estimators.
classes_ndarray of shape (n_classes,) or a list of such arrays
The classes labels (single output problem), or a list of arrays of class labels (multi-output problem).
n_classes_int or list
The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem).
feature_importances_ndarray of shape (n_features,)
The impurity-based feature importances.
n_features_int
The number of features when fit is performed.
n_outputs_int
The number of outputs when fit is performed.
oob_score_float
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
oob_decision_function_ndarray of shape (n_samples, n_classes)
Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_decision_function_ might contain NaN. This attribute exists only when oob_score is True. See also
sklearn.tree.ExtraTreeClassifier
Base classifier for this ensemble.
RandomForestClassifier
Ensemble Classifier based on trees with optimal splits. Notes The default values for the parameters controlling the size of the trees (e.g. max_depth, min_samples_leaf, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References
1
P. Geurts, D. Ernst., and L. Wehenkel, “Extremely randomized trees”, Machine Learning, 63(1), 3-42, 2006. Examples >>> from sklearn.ensemble import ExtraTreesClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_features=4, random_state=0)
>>> clf = ExtraTreesClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
ExtraTreesClassifier(random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
Methods
apply(X) Apply trees in the forest to X, return leaf indices.
decision_path(X) Return the decision path in the forest.
fit(X, y[, sample_weight]) Build a forest of trees from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class for X.
predict_log_proba(X) Predict class log-probabilities for X.
predict_proba(X) Predict class probabilities for 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.
apply(X) [source]
Apply trees in the forest to X, return leaf indices. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
X_leavesndarray of shape (n_samples, n_estimators)
For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in.
decision_path(X) [source]
Return the decision path in the forest. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. The matrix is of CSR format.
n_nodes_ptrndarray of shape (n_estimators + 1,)
The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator.
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros.
fit(X, y, sample_weight=None) [source]
Build a forest of trees from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
selfobject
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.
predict(X) [source]
Predict class for X. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
yndarray of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes.
predict_log_proba(X) [source]
Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the trees in the forest. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
pndarray of shape (n_samples, n_classes), or a list of n_outputs
such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
pndarray of shape (n_samples, n_classes), or a list of n_outputs
such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that 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.ensemble.extratreesclassifier#sklearn.ensemble.ExtraTreesClassifier |
sklearn.ensemble.ExtraTreesClassifier
class sklearn.ensemble.ExtraTreesClassifier(n_estimators=100, *, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None) [source]
An extra-trees classifier. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. Read more in the User Guide. Parameters
n_estimatorsint, default=100
The number of trees in the forest. Changed in version 0.22: The default value of n_estimators changed from 10 to 100 in 0.22.
criterion{“gini”, “entropy”}, default=”gini”
The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain.
max_depthint, default=None
The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.
min_samples_splitint or float, default=2
The minimum number of samples required to split an internal node: If int, then consider min_samples_split as the minimum number. If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split. Changed in version 0.18: Added float values for fractions.
min_samples_leafint or float, default=1
The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. If int, then consider min_samples_leaf as the minimum number. If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node. Changed in version 0.18: Added float values for fractions.
min_weight_fraction_leaffloat, default=0.0
The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.
max_features{“auto”, “sqrt”, “log2”}, int or float, default=”auto”
The number of features to consider when looking for the best split: If int, then consider max_features features at each split. If float, then max_features is a fraction and round(max_features * n_features) features are considered at each split. If “auto”, then max_features=sqrt(n_features). If “sqrt”, then max_features=sqrt(n_features). If “log2”, then max_features=log2(n_features). If None, then max_features=n_features. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.
max_leaf_nodesint, default=None
Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.
min_impurity_decreasefloat, default=0.0
A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following: N_t / N * (impurity - N_t_R / N_t * right_impurity
- N_t_L / N_t * left_impurity)
where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child. N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed. New in version 0.19.
min_impurity_splitfloat, default=None
Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use min_impurity_decrease instead.
bootstrapbool, default=False
Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree.
oob_scorebool, default=False
Whether to use out-of-bag samples to estimate the generalization accuracy.
n_jobsint, default=None
The number of jobs to run in parallel. fit, predict, decision_path and apply are all parallelized over the trees. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance or None, default=None
Controls 3 sources of randomness: the bootstrapping of the samples used when building trees (if bootstrap=True) the sampling of the features to consider when looking for the best split at each node (if max_features < n_features) the draw of the splits for each of the max_features
See Glossary for details.
verboseint, default=0
Controls the verbosity when fitting and predicting.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See the Glossary.
class_weight{“balanced”, “balanced_subsample”}, dict or list of dicts, default=None
Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)) The “balanced_subsample” mode is the same as “balanced” except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified.
ccp_alphanon-negative float, default=0.0
Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details. New in version 0.22.
max_samplesint or float, default=None
If bootstrap is True, the number of samples to draw from X to train each base estimator. If None (default), then draw X.shape[0] samples. If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples. Thus, max_samples should be in the interval (0, 1). New in version 0.22. Attributes
base_estimator_ExtraTreesClassifier
The child estimator template used to create the collection of fitted sub-estimators.
estimators_list of DecisionTreeClassifier
The collection of fitted sub-estimators.
classes_ndarray of shape (n_classes,) or a list of such arrays
The classes labels (single output problem), or a list of arrays of class labels (multi-output problem).
n_classes_int or list
The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem).
feature_importances_ndarray of shape (n_features,)
The impurity-based feature importances.
n_features_int
The number of features when fit is performed.
n_outputs_int
The number of outputs when fit is performed.
oob_score_float
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
oob_decision_function_ndarray of shape (n_samples, n_classes)
Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_decision_function_ might contain NaN. This attribute exists only when oob_score is True. See also
sklearn.tree.ExtraTreeClassifier
Base classifier for this ensemble.
RandomForestClassifier
Ensemble Classifier based on trees with optimal splits. Notes The default values for the parameters controlling the size of the trees (e.g. max_depth, min_samples_leaf, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References
1
P. Geurts, D. Ernst., and L. Wehenkel, “Extremely randomized trees”, Machine Learning, 63(1), 3-42, 2006. Examples >>> from sklearn.ensemble import ExtraTreesClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_features=4, random_state=0)
>>> clf = ExtraTreesClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
ExtraTreesClassifier(random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
Methods
apply(X) Apply trees in the forest to X, return leaf indices.
decision_path(X) Return the decision path in the forest.
fit(X, y[, sample_weight]) Build a forest of trees from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class for X.
predict_log_proba(X) Predict class log-probabilities for X.
predict_proba(X) Predict class probabilities for 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.
apply(X) [source]
Apply trees in the forest to X, return leaf indices. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
X_leavesndarray of shape (n_samples, n_estimators)
For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in.
decision_path(X) [source]
Return the decision path in the forest. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. The matrix is of CSR format.
n_nodes_ptrndarray of shape (n_estimators + 1,)
The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator.
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros.
fit(X, y, sample_weight=None) [source]
Build a forest of trees from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
selfobject
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.
predict(X) [source]
Predict class for X. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
yndarray of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes.
predict_log_proba(X) [source]
Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the trees in the forest. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
pndarray of shape (n_samples, n_classes), or a list of n_outputs
such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
predict_proba(X) [source]
Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
pndarray of shape (n_samples, n_classes), or a list of n_outputs
such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that 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.ensemble.ExtraTreesClassifier
Pixel importances with a parallel forest of trees
Feature importances with forests of trees
Hashing feature transformation using Totally Random Trees
Plot the decision surfaces of ensembles of trees on the iris dataset | sklearn.modules.generated.sklearn.ensemble.extratreesclassifier |
apply(X) [source]
Apply trees in the forest to X, return leaf indices. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
X_leavesndarray of shape (n_samples, n_estimators)
For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in. | sklearn.modules.generated.sklearn.ensemble.extratreesclassifier#sklearn.ensemble.ExtraTreesClassifier.apply |
decision_path(X) [source]
Return the decision path in the forest. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. The matrix is of CSR format.
n_nodes_ptrndarray of shape (n_estimators + 1,)
The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator. | sklearn.modules.generated.sklearn.ensemble.extratreesclassifier#sklearn.ensemble.ExtraTreesClassifier.decision_path |
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns
feature_importances_ndarray of shape (n_features,)
The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros. | sklearn.modules.generated.sklearn.ensemble.extratreesclassifier#sklearn.ensemble.ExtraTreesClassifier.feature_importances_ |
fit(X, y, sample_weight=None) [source]
Build a forest of trees from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
selfobject | sklearn.modules.generated.sklearn.ensemble.extratreesclassifier#sklearn.ensemble.ExtraTreesClassifier.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.ensemble.extratreesclassifier#sklearn.ensemble.ExtraTreesClassifier.get_params |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.