doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
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.svm.nusvr#sklearn.svm.NuSVR.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.svm.nusvr#sklearn.svm.NuSVR.set_params |
class sklearn.svm.OneClassSVM(*, kernel='rbf', degree=3, gamma='scale', coef0=0.0, tol=0.001, nu=0.5, shrinking=True, cache_size=200, verbose=False, max_iter=- 1) [source]
Unsupervised Outlier Detection. Estimate the support of a high-dimensional distribution. The implementation is based on libsvm. Read more in the User Guide. Parameters
kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’
Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to precompute the kernel matrix.
degreeint, default=3
Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.
gamma{‘scale’, ‘auto’} or float, default=’scale’
Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma, if ‘auto’, uses 1 / n_features. Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’.
coef0float, default=0.0
Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.
tolfloat, default=1e-3
Tolerance for stopping criterion.
nufloat, default=0.5
An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By default 0.5 will be taken.
shrinkingbool, default=True
Whether to use the shrinking heuristic. See the User Guide.
cache_sizefloat, default=200
Specify the size of the kernel cache (in MB).
verbosebool, default=False
Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.
max_iterint, default=-1
Hard limit on iterations within solver, or -1 for no limit. Attributes
class_weight_ndarray of shape (n_classes,)
Multipliers of parameter C for each class. Computed based on the class_weight parameter.
coef_ndarray of shape (1, n_features)
Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel. coef_ is readonly property derived from dual_coef_ and support_vectors_.
dual_coef_ndarray of shape (1, n_SV)
Coefficients of the support vectors in the decision function.
fit_status_int
0 if correctly fitted, 1 otherwise (will raise warning)
intercept_ndarray of shape (1,)
Constant in the decision function.
n_support_ndarray of shape (n_classes,), dtype=int32
Number of support vectors for each class.
offset_float
Offset used to define the decision function from the raw scores. We have the relation: decision_function = score_samples - offset_. The offset is the opposite of intercept_ and is provided for consistency with other outlier detection algorithms. New in version 0.20.
shape_fit_tuple of int of shape (n_dimensions_of_X,)
Array dimensions of training vector X.
support_ndarray of shape (n_SV,)
Indices of support vectors.
support_vectors_ndarray of shape (n_SV, n_features)
Support vectors. Examples >>> from sklearn.svm import OneClassSVM
>>> X = [[0], [0.44], [0.45], [0.46], [1]]
>>> clf = OneClassSVM(gamma='auto').fit(X)
>>> clf.predict(X)
array([-1, 1, 1, 1, -1])
>>> clf.score_samples(X)
array([1.7798..., 2.0547..., 2.0556..., 2.0561..., 1.7332...])
Methods
decision_function(X) Signed distance to the separating hyperplane.
fit(X[, y, sample_weight]) Detects the soft boundary of the set of samples X.
fit_predict(X[, y]) Perform fit on X and returns labels for X.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on samples in X.
score_samples(X) Raw scoring function of the samples.
set_params(**params) Set the parameters of this estimator.
decision_function(X) [source]
Signed distance to the separating hyperplane. Signed distance is positive for an inlier and negative for an outlier. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
decndarray of shape (n_samples,)
Returns the decision function of the samples.
fit(X, y=None, sample_weight=None, **params) [source]
Detects the soft boundary of the set of samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Set of samples, where n_samples is the number of samples and n_features is the number of features.
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points.
yIgnored
not used, present for API consistency by convention. Returns
selfobject
Notes If X is not a C-ordered contiguous array it is copied.
fit_predict(X, y=None) [source]
Perform fit on X and returns labels for X. Returns -1 for outliers and 1 for inliers. Parameters
X{array-like, sparse matrix, dataframe} of shape (n_samples, n_features)
yIgnored
Not used, present for API consistency by convention. Returns
yndarray of shape (n_samples,)
1 for inliers, -1 for outliers.
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 samples in X. For a one-class model, +1 or -1 is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
Class labels for samples in X.
score_samples(X) [source]
Raw scoring function of the samples. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
score_samplesndarray of shape (n_samples,)
Returns the (unshifted) scoring function of the samples.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | sklearn.modules.generated.sklearn.svm.oneclasssvm#sklearn.svm.OneClassSVM |
sklearn.svm.OneClassSVM
class sklearn.svm.OneClassSVM(*, kernel='rbf', degree=3, gamma='scale', coef0=0.0, tol=0.001, nu=0.5, shrinking=True, cache_size=200, verbose=False, max_iter=- 1) [source]
Unsupervised Outlier Detection. Estimate the support of a high-dimensional distribution. The implementation is based on libsvm. Read more in the User Guide. Parameters
kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’
Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to precompute the kernel matrix.
degreeint, default=3
Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.
gamma{‘scale’, ‘auto’} or float, default=’scale’
Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma, if ‘auto’, uses 1 / n_features. Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’.
coef0float, default=0.0
Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.
tolfloat, default=1e-3
Tolerance for stopping criterion.
nufloat, default=0.5
An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By default 0.5 will be taken.
shrinkingbool, default=True
Whether to use the shrinking heuristic. See the User Guide.
cache_sizefloat, default=200
Specify the size of the kernel cache (in MB).
verbosebool, default=False
Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.
max_iterint, default=-1
Hard limit on iterations within solver, or -1 for no limit. Attributes
class_weight_ndarray of shape (n_classes,)
Multipliers of parameter C for each class. Computed based on the class_weight parameter.
coef_ndarray of shape (1, n_features)
Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel. coef_ is readonly property derived from dual_coef_ and support_vectors_.
dual_coef_ndarray of shape (1, n_SV)
Coefficients of the support vectors in the decision function.
fit_status_int
0 if correctly fitted, 1 otherwise (will raise warning)
intercept_ndarray of shape (1,)
Constant in the decision function.
n_support_ndarray of shape (n_classes,), dtype=int32
Number of support vectors for each class.
offset_float
Offset used to define the decision function from the raw scores. We have the relation: decision_function = score_samples - offset_. The offset is the opposite of intercept_ and is provided for consistency with other outlier detection algorithms. New in version 0.20.
shape_fit_tuple of int of shape (n_dimensions_of_X,)
Array dimensions of training vector X.
support_ndarray of shape (n_SV,)
Indices of support vectors.
support_vectors_ndarray of shape (n_SV, n_features)
Support vectors. Examples >>> from sklearn.svm import OneClassSVM
>>> X = [[0], [0.44], [0.45], [0.46], [1]]
>>> clf = OneClassSVM(gamma='auto').fit(X)
>>> clf.predict(X)
array([-1, 1, 1, 1, -1])
>>> clf.score_samples(X)
array([1.7798..., 2.0547..., 2.0556..., 2.0561..., 1.7332...])
Methods
decision_function(X) Signed distance to the separating hyperplane.
fit(X[, y, sample_weight]) Detects the soft boundary of the set of samples X.
fit_predict(X[, y]) Perform fit on X and returns labels for X.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on samples in X.
score_samples(X) Raw scoring function of the samples.
set_params(**params) Set the parameters of this estimator.
decision_function(X) [source]
Signed distance to the separating hyperplane. Signed distance is positive for an inlier and negative for an outlier. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
decndarray of shape (n_samples,)
Returns the decision function of the samples.
fit(X, y=None, sample_weight=None, **params) [source]
Detects the soft boundary of the set of samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Set of samples, where n_samples is the number of samples and n_features is the number of features.
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points.
yIgnored
not used, present for API consistency by convention. Returns
selfobject
Notes If X is not a C-ordered contiguous array it is copied.
fit_predict(X, y=None) [source]
Perform fit on X and returns labels for X. Returns -1 for outliers and 1 for inliers. Parameters
X{array-like, sparse matrix, dataframe} of shape (n_samples, n_features)
yIgnored
Not used, present for API consistency by convention. Returns
yndarray of shape (n_samples,)
1 for inliers, -1 for outliers.
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 samples in X. For a one-class model, +1 or -1 is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
Class labels for samples in X.
score_samples(X) [source]
Raw scoring function of the samples. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
score_samplesndarray of shape (n_samples,)
Returns the (unshifted) scoring function of the samples.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
Examples using sklearn.svm.OneClassSVM
Outlier detection on a real data set
Species distribution modeling
Libsvm GUI
Comparing anomaly detection algorithms for outlier detection on toy datasets
One-class SVM with non-linear kernel (RBF) | sklearn.modules.generated.sklearn.svm.oneclasssvm |
decision_function(X) [source]
Signed distance to the separating hyperplane. Signed distance is positive for an inlier and negative for an outlier. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
decndarray of shape (n_samples,)
Returns the decision function of the samples. | sklearn.modules.generated.sklearn.svm.oneclasssvm#sklearn.svm.OneClassSVM.decision_function |
fit(X, y=None, sample_weight=None, **params) [source]
Detects the soft boundary of the set of samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Set of samples, where n_samples is the number of samples and n_features is the number of features.
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points.
yIgnored
not used, present for API consistency by convention. Returns
selfobject
Notes If X is not a C-ordered contiguous array it is copied. | sklearn.modules.generated.sklearn.svm.oneclasssvm#sklearn.svm.OneClassSVM.fit |
fit_predict(X, y=None) [source]
Perform fit on X and returns labels for X. Returns -1 for outliers and 1 for inliers. Parameters
X{array-like, sparse matrix, dataframe} of shape (n_samples, n_features)
yIgnored
Not used, present for API consistency by convention. Returns
yndarray of shape (n_samples,)
1 for inliers, -1 for outliers. | sklearn.modules.generated.sklearn.svm.oneclasssvm#sklearn.svm.OneClassSVM.fit_predict |
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.svm.oneclasssvm#sklearn.svm.OneClassSVM.get_params |
predict(X) [source]
Perform classification on samples in X. For a one-class model, +1 or -1 is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
Class labels for samples in X. | sklearn.modules.generated.sklearn.svm.oneclasssvm#sklearn.svm.OneClassSVM.predict |
score_samples(X) [source]
Raw scoring function of the samples. Parameters
Xarray-like of shape (n_samples, n_features)
The data matrix. Returns
score_samplesndarray of shape (n_samples,)
Returns the (unshifted) scoring function of the samples. | sklearn.modules.generated.sklearn.svm.oneclasssvm#sklearn.svm.OneClassSVM.score_samples |
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | sklearn.modules.generated.sklearn.svm.oneclasssvm#sklearn.svm.OneClassSVM.set_params |
class sklearn.svm.SVC(*, C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=- 1, decision_function_shape='ovr', break_ties=False, random_state=None) [source]
C-Support Vector Classification. The implementation is based on libsvm. The fit time scales at least quadratically with the number of samples and may be impractical beyond tens of thousands of samples. For large datasets consider using LinearSVC or SGDClassifier instead, possibly after a Nystroem transformer. The multiclass support is handled according to a one-vs-one scheme. For details on the precise mathematical formulation of the provided kernel functions and how gamma, coef0 and degree affect each other, see the corresponding section in the narrative documentation: Kernel functions. Read more in the User Guide. Parameters
Cfloat, default=1.0
Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.
kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’
Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to pre-compute the kernel matrix from data matrices; that matrix should be an array of shape (n_samples, n_samples).
degreeint, default=3
Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.
gamma{‘scale’, ‘auto’} or float, default=’scale’
Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma, if ‘auto’, uses 1 / n_features. Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’.
coef0float, default=0.0
Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.
shrinkingbool, default=True
Whether to use the shrinking heuristic. See the User Guide.
probabilitybool, default=False
Whether to enable probability estimates. This must be enabled prior to calling fit, will slow down that method as it internally uses 5-fold cross-validation, and predict_proba may be inconsistent with predict. Read more in the User Guide.
tolfloat, default=1e-3
Tolerance for stopping criterion.
cache_sizefloat, default=200
Specify the size of the kernel cache (in MB).
class_weightdict or ‘balanced’, default=None
Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. 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))
verbosebool, default=False
Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.
max_iterint, default=-1
Hard limit on iterations within solver, or -1 for no limit.
decision_function_shape{‘ovo’, ‘ovr’}, default=’ovr’
Whether to return a one-vs-rest (‘ovr’) decision function of shape (n_samples, n_classes) as all other classifiers, or the original one-vs-one (‘ovo’) decision function of libsvm which has shape (n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one (‘ovo’) is always used as multi-class strategy. The parameter is ignored for binary classification. Changed in version 0.19: decision_function_shape is ‘ovr’ by default. New in version 0.17: decision_function_shape=’ovr’ is recommended. Changed in version 0.17: Deprecated decision_function_shape=’ovo’ and None.
break_tiesbool, default=False
If true, decision_function_shape='ovr', and number of classes > 2, predict will break ties according to the confidence values of decision_function; otherwise the first class among the tied classes is returned. Please note that breaking ties comes at a relatively high computational cost compared to a simple predict. New in version 0.22.
random_stateint, RandomState instance or None, default=None
Controls the pseudo random number generation for shuffling the data for probability estimates. Ignored when probability is False. Pass an int for reproducible output across multiple function calls. See Glossary. Attributes
class_weight_ndarray of shape (n_classes,)
Multipliers of parameter C for each class. Computed based on the class_weight parameter.
classes_ndarray of shape (n_classes,)
The classes labels.
coef_ndarray of shape (n_classes * (n_classes - 1) / 2, n_features)
Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel. coef_ is a readonly property derived from dual_coef_ and support_vectors_.
dual_coef_ndarray of shape (n_classes -1, n_SV)
Dual coefficients of the support vector in the decision function (see Mathematical formulation), multiplied by their targets. For multiclass, coefficient for all 1-vs-1 classifiers. The layout of the coefficients in the multiclass case is somewhat non-trivial. See the multi-class section of the User Guide for details.
fit_status_int
0 if correctly fitted, 1 otherwise (will raise warning)
intercept_ndarray of shape (n_classes * (n_classes - 1) / 2,)
Constants in decision function.
support_ndarray of shape (n_SV)
Indices of support vectors.
support_vectors_ndarray of shape (n_SV, n_features)
Support vectors.
n_support_ndarray of shape (n_classes,), dtype=int32
Number of support vectors for each class.
probA_ndarray of shape (n_classes * (n_classes - 1) / 2)
probB_ndarray of shape (n_classes * (n_classes - 1) / 2)
If probability=True, it corresponds to the parameters learned in Platt scaling to produce probability estimates from decision values. If probability=False, it’s an empty array. Platt scaling uses the logistic function 1 / (1 + exp(decision_value * probA_ + probB_)) where probA_ and probB_ are learned from the dataset [2]. For more information on the multiclass case and training procedure see section 8 of [1].
shape_fit_tuple of int of shape (n_dimensions_of_X,)
Array dimensions of training vector X. See also
SVR
Support Vector Machine for Regression implemented using libsvm.
LinearSVC
Scalable Linear Support Vector Machine for classification implemented using liblinear. Check the See Also section of LinearSVC for more comparison element. References
1
LIBSVM: A Library for Support Vector Machines
2
Platt, John (1999). “Probabilistic outputs for support vector machines and comparison to regularizedlikelihood methods.” Examples >>> import numpy as np
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
>>> y = np.array([1, 1, 2, 2])
>>> from sklearn.svm import SVC
>>> clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
>>> clf.fit(X, y)
Pipeline(steps=[('standardscaler', StandardScaler()),
('svc', SVC(gamma='auto'))])
>>> print(clf.predict([[-0.8, -1]]))
[1]
Methods
decision_function(X) Evaluates the decision function for the samples in X.
fit(X, y[, sample_weight]) Fit the SVM model according to the given training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on samples in 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]
Evaluates the decision function for the samples in X. Parameters
Xarray-like of shape (n_samples, n_features)
Returns
Xndarray of shape (n_samples, n_classes * (n_classes-1) / 2)
Returns the decision function of the sample for each class in the model. If decision_function_shape=’ovr’, the shape is (n_samples, n_classes). Notes If decision_function_shape=’ovo’, the function values are proportional to the distance of the samples X to the separating hyperplane. If the exact distances are required, divide the function values by the norm of the weight vector (coef_). See also this question for further details. If decision_function_shape=’ovr’, the decision function is a monotonic transformation of ovo decision function.
fit(X, y, sample_weight=None) [source]
Fit the SVM model according to the given training data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where n_samples is the number of samples and n_features is the number of features. For kernel=”precomputed”, the expected shape of X is (n_samples, n_samples).
yarray-like of shape (n_samples,)
Target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns
selfobject
Notes If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied. If X is a dense array, then the other methods will not support sparse matrices as input.
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 samples in X. For an one-class model, +1 or -1 is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
Class labels for samples in X.
property predict_log_proba
Compute log probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute probability set to True. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
Tndarray of shape (n_samples, n_classes)
Returns the log-probabilities of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Notes The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets.
property predict_proba
Compute probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute probability set to True. Parameters
Xarray-like of shape (n_samples, n_features)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
Tndarray of shape (n_samples, n_classes)
Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Notes The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets.
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.svm.svc#sklearn.svm.SVC |
sklearn.svm.SVC
class sklearn.svm.SVC(*, C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=- 1, decision_function_shape='ovr', break_ties=False, random_state=None) [source]
C-Support Vector Classification. The implementation is based on libsvm. The fit time scales at least quadratically with the number of samples and may be impractical beyond tens of thousands of samples. For large datasets consider using LinearSVC or SGDClassifier instead, possibly after a Nystroem transformer. The multiclass support is handled according to a one-vs-one scheme. For details on the precise mathematical formulation of the provided kernel functions and how gamma, coef0 and degree affect each other, see the corresponding section in the narrative documentation: Kernel functions. Read more in the User Guide. Parameters
Cfloat, default=1.0
Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.
kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’
Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to pre-compute the kernel matrix from data matrices; that matrix should be an array of shape (n_samples, n_samples).
degreeint, default=3
Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.
gamma{‘scale’, ‘auto’} or float, default=’scale’
Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma, if ‘auto’, uses 1 / n_features. Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’.
coef0float, default=0.0
Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.
shrinkingbool, default=True
Whether to use the shrinking heuristic. See the User Guide.
probabilitybool, default=False
Whether to enable probability estimates. This must be enabled prior to calling fit, will slow down that method as it internally uses 5-fold cross-validation, and predict_proba may be inconsistent with predict. Read more in the User Guide.
tolfloat, default=1e-3
Tolerance for stopping criterion.
cache_sizefloat, default=200
Specify the size of the kernel cache (in MB).
class_weightdict or ‘balanced’, default=None
Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. 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))
verbosebool, default=False
Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.
max_iterint, default=-1
Hard limit on iterations within solver, or -1 for no limit.
decision_function_shape{‘ovo’, ‘ovr’}, default=’ovr’
Whether to return a one-vs-rest (‘ovr’) decision function of shape (n_samples, n_classes) as all other classifiers, or the original one-vs-one (‘ovo’) decision function of libsvm which has shape (n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one (‘ovo’) is always used as multi-class strategy. The parameter is ignored for binary classification. Changed in version 0.19: decision_function_shape is ‘ovr’ by default. New in version 0.17: decision_function_shape=’ovr’ is recommended. Changed in version 0.17: Deprecated decision_function_shape=’ovo’ and None.
break_tiesbool, default=False
If true, decision_function_shape='ovr', and number of classes > 2, predict will break ties according to the confidence values of decision_function; otherwise the first class among the tied classes is returned. Please note that breaking ties comes at a relatively high computational cost compared to a simple predict. New in version 0.22.
random_stateint, RandomState instance or None, default=None
Controls the pseudo random number generation for shuffling the data for probability estimates. Ignored when probability is False. Pass an int for reproducible output across multiple function calls. See Glossary. Attributes
class_weight_ndarray of shape (n_classes,)
Multipliers of parameter C for each class. Computed based on the class_weight parameter.
classes_ndarray of shape (n_classes,)
The classes labels.
coef_ndarray of shape (n_classes * (n_classes - 1) / 2, n_features)
Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel. coef_ is a readonly property derived from dual_coef_ and support_vectors_.
dual_coef_ndarray of shape (n_classes -1, n_SV)
Dual coefficients of the support vector in the decision function (see Mathematical formulation), multiplied by their targets. For multiclass, coefficient for all 1-vs-1 classifiers. The layout of the coefficients in the multiclass case is somewhat non-trivial. See the multi-class section of the User Guide for details.
fit_status_int
0 if correctly fitted, 1 otherwise (will raise warning)
intercept_ndarray of shape (n_classes * (n_classes - 1) / 2,)
Constants in decision function.
support_ndarray of shape (n_SV)
Indices of support vectors.
support_vectors_ndarray of shape (n_SV, n_features)
Support vectors.
n_support_ndarray of shape (n_classes,), dtype=int32
Number of support vectors for each class.
probA_ndarray of shape (n_classes * (n_classes - 1) / 2)
probB_ndarray of shape (n_classes * (n_classes - 1) / 2)
If probability=True, it corresponds to the parameters learned in Platt scaling to produce probability estimates from decision values. If probability=False, it’s an empty array. Platt scaling uses the logistic function 1 / (1 + exp(decision_value * probA_ + probB_)) where probA_ and probB_ are learned from the dataset [2]. For more information on the multiclass case and training procedure see section 8 of [1].
shape_fit_tuple of int of shape (n_dimensions_of_X,)
Array dimensions of training vector X. See also
SVR
Support Vector Machine for Regression implemented using libsvm.
LinearSVC
Scalable Linear Support Vector Machine for classification implemented using liblinear. Check the See Also section of LinearSVC for more comparison element. References
1
LIBSVM: A Library for Support Vector Machines
2
Platt, John (1999). “Probabilistic outputs for support vector machines and comparison to regularizedlikelihood methods.” Examples >>> import numpy as np
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
>>> y = np.array([1, 1, 2, 2])
>>> from sklearn.svm import SVC
>>> clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
>>> clf.fit(X, y)
Pipeline(steps=[('standardscaler', StandardScaler()),
('svc', SVC(gamma='auto'))])
>>> print(clf.predict([[-0.8, -1]]))
[1]
Methods
decision_function(X) Evaluates the decision function for the samples in X.
fit(X, y[, sample_weight]) Fit the SVM model according to the given training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on samples in 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]
Evaluates the decision function for the samples in X. Parameters
Xarray-like of shape (n_samples, n_features)
Returns
Xndarray of shape (n_samples, n_classes * (n_classes-1) / 2)
Returns the decision function of the sample for each class in the model. If decision_function_shape=’ovr’, the shape is (n_samples, n_classes). Notes If decision_function_shape=’ovo’, the function values are proportional to the distance of the samples X to the separating hyperplane. If the exact distances are required, divide the function values by the norm of the weight vector (coef_). See also this question for further details. If decision_function_shape=’ovr’, the decision function is a monotonic transformation of ovo decision function.
fit(X, y, sample_weight=None) [source]
Fit the SVM model according to the given training data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where n_samples is the number of samples and n_features is the number of features. For kernel=”precomputed”, the expected shape of X is (n_samples, n_samples).
yarray-like of shape (n_samples,)
Target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns
selfobject
Notes If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied. If X is a dense array, then the other methods will not support sparse matrices as input.
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 samples in X. For an one-class model, +1 or -1 is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
Class labels for samples in X.
property predict_log_proba
Compute log probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute probability set to True. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
Tndarray of shape (n_samples, n_classes)
Returns the log-probabilities of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Notes The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets.
property predict_proba
Compute probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute probability set to True. Parameters
Xarray-like of shape (n_samples, n_features)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
Tndarray of shape (n_samples, n_classes)
Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Notes The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets.
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.svm.SVC
Release Highlights for scikit-learn 0.24
Release Highlights for scikit-learn 0.22
Recognizing hand-written digits
Plot classification probability
Classifier comparison
Plot the decision boundaries of a VotingClassifier
Faces recognition example using eigenfaces and SVMs
Libsvm GUI
Recursive feature elimination
Recursive feature elimination with cross-validation
Test with permutations the significance of a classification score
Scalable learning with polynomial kernel aproximation
ROC Curve with Visualization API
Multilabel classification
Explicit feature map approximation for RBF kernels
Confusion matrix
Plotting Validation Curves
Parameter estimation using grid search with cross-validation
Receiver Operating Characteristic (ROC) with cross validation
Nested versus non-nested cross-validation
Comparison between grid search and successive halving
Receiver Operating Characteristic (ROC)
Plotting Learning Curves
Statistical comparison of models using grid search
Concatenating multiple feature extraction methods
Feature discretization
Decision boundary of semi-supervised classifiers versus SVM on the Iris dataset
Effect of varying threshold for self-training
SVM: Maximum margin separating hyperplane
SVM with custom kernel
SVM Tie Breaking Example
SVM: Weighted samples
SVM: Separating hyperplane for unbalanced classes
SVM-Kernels
SVM-Anova: SVM with univariate feature selection
SVM Margins Example
Plot different SVM classifiers in the iris dataset
RBF SVM parameters
Cross-validation on Digits Dataset Exercise
SVM Exercise | sklearn.modules.generated.sklearn.svm.svc |
decision_function(X) [source]
Evaluates the decision function for the samples in X. Parameters
Xarray-like of shape (n_samples, n_features)
Returns
Xndarray of shape (n_samples, n_classes * (n_classes-1) / 2)
Returns the decision function of the sample for each class in the model. If decision_function_shape=’ovr’, the shape is (n_samples, n_classes). Notes If decision_function_shape=’ovo’, the function values are proportional to the distance of the samples X to the separating hyperplane. If the exact distances are required, divide the function values by the norm of the weight vector (coef_). See also this question for further details. If decision_function_shape=’ovr’, the decision function is a monotonic transformation of ovo decision function. | sklearn.modules.generated.sklearn.svm.svc#sklearn.svm.SVC.decision_function |
fit(X, y, sample_weight=None) [source]
Fit the SVM model according to the given training data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where n_samples is the number of samples and n_features is the number of features. For kernel=”precomputed”, the expected shape of X is (n_samples, n_samples).
yarray-like of shape (n_samples,)
Target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns
selfobject
Notes If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied. If X is a dense array, then the other methods will not support sparse matrices as input. | sklearn.modules.generated.sklearn.svm.svc#sklearn.svm.SVC.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.svm.svc#sklearn.svm.SVC.get_params |
predict(X) [source]
Perform classification on samples in X. For an one-class model, +1 or -1 is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
Class labels for samples in X. | sklearn.modules.generated.sklearn.svm.svc#sklearn.svm.SVC.predict |
property predict_log_proba
Compute log probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute probability set to True. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples_test, n_samples_train)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
Tndarray of shape (n_samples, n_classes)
Returns the log-probabilities of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Notes The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets. | sklearn.modules.generated.sklearn.svm.svc#sklearn.svm.SVC.predict_log_proba |
property predict_proba
Compute probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute probability set to True. Parameters
Xarray-like of shape (n_samples, n_features)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
Tndarray of shape (n_samples, n_classes)
Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Notes The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets. | sklearn.modules.generated.sklearn.svm.svc#sklearn.svm.SVC.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.svm.svc#sklearn.svm.SVC.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.svm.svc#sklearn.svm.SVC.set_params |
class sklearn.svm.SVR(*, kernel='rbf', degree=3, gamma='scale', coef0=0.0, tol=0.001, C=1.0, epsilon=0.1, shrinking=True, cache_size=200, verbose=False, max_iter=- 1) [source]
Epsilon-Support Vector Regression. The free parameters in the model are C and epsilon. The implementation is based on libsvm. The fit time complexity is more than quadratic with the number of samples which makes it hard to scale to datasets with more than a couple of 10000 samples. For large datasets consider using LinearSVR or SGDRegressor instead, possibly after a Nystroem transformer. Read more in the User Guide. Parameters
kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’
Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to precompute the kernel matrix.
degreeint, default=3
Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.
gamma{‘scale’, ‘auto’} or float, default=’scale’
Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma, if ‘auto’, uses 1 / n_features. Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’.
coef0float, default=0.0
Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.
tolfloat, default=1e-3
Tolerance for stopping criterion.
Cfloat, default=1.0
Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.
epsilonfloat, default=0.1
Epsilon in the epsilon-SVR model. It specifies the epsilon-tube within which no penalty is associated in the training loss function with points predicted within a distance epsilon from the actual value.
shrinkingbool, default=True
Whether to use the shrinking heuristic. See the User Guide.
cache_sizefloat, default=200
Specify the size of the kernel cache (in MB).
verbosebool, default=False
Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.
max_iterint, default=-1
Hard limit on iterations within solver, or -1 for no limit. Attributes
class_weight_ndarray of shape (n_classes,)
Multipliers of parameter C for each class. Computed based on the class_weight parameter.
coef_ndarray of shape (1, n_features)
Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel. coef_ is readonly property derived from dual_coef_ and support_vectors_.
dual_coef_ndarray of shape (1, n_SV)
Coefficients of the support vector in the decision function.
fit_status_int
0 if correctly fitted, 1 otherwise (will raise warning)
intercept_ndarray of shape (1,)
Constants in decision function.
n_support_ndarray of shape (n_classes,), dtype=int32
Number of support vectors for each class.
shape_fit_tuple of int of shape (n_dimensions_of_X,)
Array dimensions of training vector X.
support_ndarray of shape (n_SV,)
Indices of support vectors.
support_vectors_ndarray of shape (n_SV, n_features)
Support vectors. See also
NuSVR
Support Vector Machine for regression implemented using libsvm using a parameter to control the number of support vectors.
LinearSVR
Scalable Linear Support Vector Machine for regression implemented using liblinear. References
1
LIBSVM: A Library for Support Vector Machines
2
Platt, John (1999). “Probabilistic outputs for support vector machines and comparison to regularizedlikelihood methods.” Examples >>> from sklearn.svm import SVR
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> import numpy as np
>>> n_samples, n_features = 10, 5
>>> rng = np.random.RandomState(0)
>>> y = rng.randn(n_samples)
>>> X = rng.randn(n_samples, n_features)
>>> regr = make_pipeline(StandardScaler(), SVR(C=1.0, epsilon=0.2))
>>> regr.fit(X, y)
Pipeline(steps=[('standardscaler', StandardScaler()),
('svr', SVR(epsilon=0.2))])
Methods
fit(X, y[, sample_weight]) Fit the SVM model according to the given training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform regression on samples in X.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit the SVM model according to the given training data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where n_samples is the number of samples and n_features is the number of features. For kernel=”precomputed”, the expected shape of X is (n_samples, n_samples).
yarray-like of shape (n_samples,)
Target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns
selfobject
Notes If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied. If X is a dense array, then the other methods will not support sparse matrices as input.
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 regression on samples in X. For an one-class model, +1 (inlier) or -1 (outlier) is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
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.svm.svr#sklearn.svm.SVR |
sklearn.svm.SVR
class sklearn.svm.SVR(*, kernel='rbf', degree=3, gamma='scale', coef0=0.0, tol=0.001, C=1.0, epsilon=0.1, shrinking=True, cache_size=200, verbose=False, max_iter=- 1) [source]
Epsilon-Support Vector Regression. The free parameters in the model are C and epsilon. The implementation is based on libsvm. The fit time complexity is more than quadratic with the number of samples which makes it hard to scale to datasets with more than a couple of 10000 samples. For large datasets consider using LinearSVR or SGDRegressor instead, possibly after a Nystroem transformer. Read more in the User Guide. Parameters
kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’
Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to precompute the kernel matrix.
degreeint, default=3
Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.
gamma{‘scale’, ‘auto’} or float, default=’scale’
Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma, if ‘auto’, uses 1 / n_features. Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’.
coef0float, default=0.0
Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.
tolfloat, default=1e-3
Tolerance for stopping criterion.
Cfloat, default=1.0
Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.
epsilonfloat, default=0.1
Epsilon in the epsilon-SVR model. It specifies the epsilon-tube within which no penalty is associated in the training loss function with points predicted within a distance epsilon from the actual value.
shrinkingbool, default=True
Whether to use the shrinking heuristic. See the User Guide.
cache_sizefloat, default=200
Specify the size of the kernel cache (in MB).
verbosebool, default=False
Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.
max_iterint, default=-1
Hard limit on iterations within solver, or -1 for no limit. Attributes
class_weight_ndarray of shape (n_classes,)
Multipliers of parameter C for each class. Computed based on the class_weight parameter.
coef_ndarray of shape (1, n_features)
Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel. coef_ is readonly property derived from dual_coef_ and support_vectors_.
dual_coef_ndarray of shape (1, n_SV)
Coefficients of the support vector in the decision function.
fit_status_int
0 if correctly fitted, 1 otherwise (will raise warning)
intercept_ndarray of shape (1,)
Constants in decision function.
n_support_ndarray of shape (n_classes,), dtype=int32
Number of support vectors for each class.
shape_fit_tuple of int of shape (n_dimensions_of_X,)
Array dimensions of training vector X.
support_ndarray of shape (n_SV,)
Indices of support vectors.
support_vectors_ndarray of shape (n_SV, n_features)
Support vectors. See also
NuSVR
Support Vector Machine for regression implemented using libsvm using a parameter to control the number of support vectors.
LinearSVR
Scalable Linear Support Vector Machine for regression implemented using liblinear. References
1
LIBSVM: A Library for Support Vector Machines
2
Platt, John (1999). “Probabilistic outputs for support vector machines and comparison to regularizedlikelihood methods.” Examples >>> from sklearn.svm import SVR
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> import numpy as np
>>> n_samples, n_features = 10, 5
>>> rng = np.random.RandomState(0)
>>> y = rng.randn(n_samples)
>>> X = rng.randn(n_samples, n_features)
>>> regr = make_pipeline(StandardScaler(), SVR(C=1.0, epsilon=0.2))
>>> regr.fit(X, y)
Pipeline(steps=[('standardscaler', StandardScaler()),
('svr', SVR(epsilon=0.2))])
Methods
fit(X, y[, sample_weight]) Fit the SVM model according to the given training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform regression on samples in X.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]
Fit the SVM model according to the given training data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where n_samples is the number of samples and n_features is the number of features. For kernel=”precomputed”, the expected shape of X is (n_samples, n_samples).
yarray-like of shape (n_samples,)
Target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns
selfobject
Notes If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied. If X is a dense array, then the other methods will not support sparse matrices as input.
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 regression on samples in X. For an one-class model, +1 (inlier) or -1 (outlier) is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,)
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.svm.SVR
Prediction Latency
Comparison of kernel ridge regression and SVR
Support Vector Regression (SVR) using linear and non-linear kernels | sklearn.modules.generated.sklearn.svm.svr |
fit(X, y, sample_weight=None) [source]
Fit the SVM model according to the given training data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
Training vectors, where n_samples is the number of samples and n_features is the number of features. For kernel=”precomputed”, the expected shape of X is (n_samples, n_samples).
yarray-like of shape (n_samples,)
Target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns
selfobject
Notes If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied. If X is a dense array, then the other methods will not support sparse matrices as input. | sklearn.modules.generated.sklearn.svm.svr#sklearn.svm.SVR.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.svm.svr#sklearn.svm.SVR.get_params |
predict(X) [source]
Perform regression on samples in X. For an one-class model, +1 (inlier) or -1 (outlier) is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
y_predndarray of shape (n_samples,) | sklearn.modules.generated.sklearn.svm.svr#sklearn.svm.SVR.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.svm.svr#sklearn.svm.SVR.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.svm.svr#sklearn.svm.SVR.set_params |
class sklearn.tree.DecisionTreeClassifier(*, criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, class_weight=None, ccp_alpha=0.0) [source]
A decision tree classifier. Read more in the User Guide. Parameters
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.
splitter{“best”, “random”}, default=”best”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
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_featuresint, float or {“auto”, “sqrt”, “log2”}, default=None
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 int(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.
random_stateint, RandomState instance or None, default=None
Controls the randomness of the estimator. The features are always randomly permuted at each split, even if splitter is set to "best". When max_features < n_features, the algorithm will select max_features at random at each split before finding the best split among them. But the best found split may vary across different runs, even if max_features=n_features. That is the case, if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting, random_state has to be fixed to an integer. See Glossary for details.
max_leaf_nodesint, default=None
Grow a tree 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=0
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.
class_weightdict, list of dict or “balanced”, default=None
Weights associated with classes in the form {class_label: weight}. If None, 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)) 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. Attributes
classes_ndarray of shape (n_classes,) or list of ndarray
The classes labels (single output problem), or a list of arrays of class labels (multi-output problem).
feature_importances_ndarray of shape (n_features,)
Return the feature importances.
max_features_int
The inferred value of max_features.
n_classes_int or list of int
The number of classes (for single output problems), or a list containing the number of classes for each output (for multi-output problems).
n_features_int
The number of features when fit is performed.
n_outputs_int
The number of outputs when fit is performed.
tree_Tree instance
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes. See also
DecisionTreeRegressor
A decision tree regressor. 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. The predict method operates using the numpy.argmax function on the outputs of predict_proba. This means that in case the highest predicted probabilities are tied, the classifier will predict the tied class with the lowest index in classes_. References
1
https://en.wikipedia.org/wiki/Decision_tree_learning
2
L. Breiman, J. Friedman, R. Olshen, and C. Stone, “Classification and Regression Trees”, Wadsworth, Belmont, CA, 1984.
3
T. Hastie, R. Tibshirani and J. Friedman. “Elements of Statistical Learning”, Springer, 2009.
4
L. Breiman, and A. Cutler, “Random Forests”, https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import cross_val_score
>>> from sklearn.tree import DecisionTreeClassifier
>>> clf = DecisionTreeClassifier(random_state=0)
>>> iris = load_iris()
>>> cross_val_score(clf, iris.data, iris.target, cv=10)
...
...
array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,
0.93..., 0.93..., 1. , 0.93..., 1. ])
Methods
apply(X[, check_input]) Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …]) Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input]) Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …]) Build a decision tree classifier from the training set (X, y).
get_depth() Return the depth of the decision tree.
get_n_leaves() Return the number of leaves of the decision tree.
get_params([deep]) Get parameters for this estimator.
predict(X[, check_input]) Predict class or regression value for X.
predict_log_proba(X) Predict class log-probabilities of the input samples X.
predict_proba(X[, check_input]) Predict class probabilities of the input samples 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, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance).
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeClassifier
Fitted estimator.
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree.
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves.
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, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict values.
predict_log_proba(X) [source]
Predict class log-probabilities of the input samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
predict_proba(X, check_input=True) [source]
Predict class probabilities of the input samples X. The predicted class probability 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, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
probandarray of shape (n_samples, n_classes) or 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.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier |
sklearn.tree.DecisionTreeClassifier
class sklearn.tree.DecisionTreeClassifier(*, criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, class_weight=None, ccp_alpha=0.0) [source]
A decision tree classifier. Read more in the User Guide. Parameters
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.
splitter{“best”, “random”}, default=”best”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
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_featuresint, float or {“auto”, “sqrt”, “log2”}, default=None
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 int(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.
random_stateint, RandomState instance or None, default=None
Controls the randomness of the estimator. The features are always randomly permuted at each split, even if splitter is set to "best". When max_features < n_features, the algorithm will select max_features at random at each split before finding the best split among them. But the best found split may vary across different runs, even if max_features=n_features. That is the case, if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting, random_state has to be fixed to an integer. See Glossary for details.
max_leaf_nodesint, default=None
Grow a tree 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=0
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.
class_weightdict, list of dict or “balanced”, default=None
Weights associated with classes in the form {class_label: weight}. If None, 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)) 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. Attributes
classes_ndarray of shape (n_classes,) or list of ndarray
The classes labels (single output problem), or a list of arrays of class labels (multi-output problem).
feature_importances_ndarray of shape (n_features,)
Return the feature importances.
max_features_int
The inferred value of max_features.
n_classes_int or list of int
The number of classes (for single output problems), or a list containing the number of classes for each output (for multi-output problems).
n_features_int
The number of features when fit is performed.
n_outputs_int
The number of outputs when fit is performed.
tree_Tree instance
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes. See also
DecisionTreeRegressor
A decision tree regressor. 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. The predict method operates using the numpy.argmax function on the outputs of predict_proba. This means that in case the highest predicted probabilities are tied, the classifier will predict the tied class with the lowest index in classes_. References
1
https://en.wikipedia.org/wiki/Decision_tree_learning
2
L. Breiman, J. Friedman, R. Olshen, and C. Stone, “Classification and Regression Trees”, Wadsworth, Belmont, CA, 1984.
3
T. Hastie, R. Tibshirani and J. Friedman. “Elements of Statistical Learning”, Springer, 2009.
4
L. Breiman, and A. Cutler, “Random Forests”, https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import cross_val_score
>>> from sklearn.tree import DecisionTreeClassifier
>>> clf = DecisionTreeClassifier(random_state=0)
>>> iris = load_iris()
>>> cross_val_score(clf, iris.data, iris.target, cv=10)
...
...
array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,
0.93..., 0.93..., 1. , 0.93..., 1. ])
Methods
apply(X[, check_input]) Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …]) Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input]) Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …]) Build a decision tree classifier from the training set (X, y).
get_depth() Return the depth of the decision tree.
get_n_leaves() Return the number of leaves of the decision tree.
get_params([deep]) Get parameters for this estimator.
predict(X[, check_input]) Predict class or regression value for X.
predict_log_proba(X) Predict class log-probabilities of the input samples X.
predict_proba(X[, check_input]) Predict class probabilities of the input samples 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, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance).
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeClassifier
Fitted estimator.
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree.
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves.
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, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict values.
predict_log_proba(X) [source]
Predict class log-probabilities of the input samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
predict_proba(X, check_input=True) [source]
Predict class probabilities of the input samples X. The predicted class probability 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, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
probandarray of shape (n_samples, n_classes) or 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.tree.DecisionTreeClassifier
Classifier comparison
Plot the decision surface of a decision tree on the iris dataset
Post pruning decision trees with cost complexity pruning
Understanding the decision tree structure
Plot the decision boundaries of a VotingClassifier
Two-class AdaBoost
Multi-class AdaBoosted Decision Trees
Discrete versus Real AdaBoost
Plot the decision surfaces of ensembles of trees on the iris dataset
Demonstration of multi-metric evaluation on cross_val_score and GridSearchCV | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier |
apply(X, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.apply |
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.cost_complexity_pruning_path |
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.decision_path |
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance). | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.feature_importances_ |
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeClassifier
Fitted estimator. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.fit |
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.get_depth |
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.get_n_leaves |
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.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.get_params |
predict(X, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict values. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.predict |
predict_log_proba(X) [source]
Predict class log-probabilities of the input samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.predict_log_proba |
predict_proba(X, check_input=True) [source]
Predict class probabilities of the input samples X. The predicted class probability 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, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
probandarray of shape (n_samples, n_classes) or 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_. | sklearn.modules.generated.sklearn.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.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.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.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.tree.decisiontreeclassifier#sklearn.tree.DecisionTreeClassifier.set_params |
class sklearn.tree.DecisionTreeRegressor(*, criterion='mse', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, ccp_alpha=0.0) [source]
A decision tree regressor. Read more in the User Guide. Parameters
criterion{“mse”, “friedman_mse”, “mae”, “poisson”}, default=”mse”
The function to measure the quality of a split. Supported criteria are “mse” for the mean squared error, which is equal to variance reduction as feature selection criterion and minimizes the L2 loss using the mean of each terminal node, “friedman_mse”, which uses mean squared error with Friedman’s improvement score for potential splits, “mae” for the mean absolute error, which minimizes the L1 loss using the median of each terminal node, and “poisson” which uses reduction in Poisson deviance to find splits. New in version 0.18: Mean Absolute Error (MAE) criterion. New in version 0.24: Poisson deviance criterion.
splitter{“best”, “random”}, default=”best”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
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_featuresint, float or {“auto”, “sqrt”, “log2”}, default=None
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 int(max_features * n_features) features are considered at each split. If “auto”, then max_features=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.
random_stateint, RandomState instance or None, default=None
Controls the randomness of the estimator. The features are always randomly permuted at each split, even if splitter is set to "best". When max_features < n_features, the algorithm will select max_features at random at each split before finding the best split among them. But the best found split may vary across different runs, even if max_features=n_features. That is the case, if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting, random_state has to be fixed to an integer. See Glossary for details.
max_leaf_nodesint, default=None
Grow a tree 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=0
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.
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. Attributes
feature_importances_ndarray of shape (n_features,)
Return the feature importances.
max_features_int
The inferred value of max_features.
n_features_int
The number of features when fit is performed.
n_outputs_int
The number of outputs when fit is performed.
tree_Tree instance
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes. See also
DecisionTreeClassifier
A decision tree classifier. 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
https://en.wikipedia.org/wiki/Decision_tree_learning
2
L. Breiman, J. Friedman, R. Olshen, and C. Stone, “Classification and Regression Trees”, Wadsworth, Belmont, CA, 1984.
3
T. Hastie, R. Tibshirani and J. Friedman. “Elements of Statistical Learning”, Springer, 2009.
4
L. Breiman, and A. Cutler, “Random Forests”, https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Examples >>> from sklearn.datasets import load_diabetes
>>> from sklearn.model_selection import cross_val_score
>>> from sklearn.tree import DecisionTreeRegressor
>>> X, y = load_diabetes(return_X_y=True)
>>> regressor = DecisionTreeRegressor(random_state=0)
>>> cross_val_score(regressor, X, y, cv=10)
...
...
array([-0.39..., -0.46..., 0.02..., 0.06..., -0.50...,
0.16..., 0.11..., -0.73..., -0.30..., -0.00...])
Methods
apply(X[, check_input]) Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …]) Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input]) Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …]) Build a decision tree regressor from the training set (X, y).
get_depth() Return the depth of the decision tree.
get_n_leaves() Return the number of leaves of the decision tree.
get_params([deep]) Get parameters for this estimator.
predict(X[, check_input]) Predict class or 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.
apply(X, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance).
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (real numbers). Use dtype=np.float64 and order='C' for maximum efficiency.
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.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeRegressor
Fitted estimator.
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree.
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves.
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, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict 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.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor |
sklearn.tree.DecisionTreeRegressor
class sklearn.tree.DecisionTreeRegressor(*, criterion='mse', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, ccp_alpha=0.0) [source]
A decision tree regressor. Read more in the User Guide. Parameters
criterion{“mse”, “friedman_mse”, “mae”, “poisson”}, default=”mse”
The function to measure the quality of a split. Supported criteria are “mse” for the mean squared error, which is equal to variance reduction as feature selection criterion and minimizes the L2 loss using the mean of each terminal node, “friedman_mse”, which uses mean squared error with Friedman’s improvement score for potential splits, “mae” for the mean absolute error, which minimizes the L1 loss using the median of each terminal node, and “poisson” which uses reduction in Poisson deviance to find splits. New in version 0.18: Mean Absolute Error (MAE) criterion. New in version 0.24: Poisson deviance criterion.
splitter{“best”, “random”}, default=”best”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
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_featuresint, float or {“auto”, “sqrt”, “log2”}, default=None
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 int(max_features * n_features) features are considered at each split. If “auto”, then max_features=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.
random_stateint, RandomState instance or None, default=None
Controls the randomness of the estimator. The features are always randomly permuted at each split, even if splitter is set to "best". When max_features < n_features, the algorithm will select max_features at random at each split before finding the best split among them. But the best found split may vary across different runs, even if max_features=n_features. That is the case, if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting, random_state has to be fixed to an integer. See Glossary for details.
max_leaf_nodesint, default=None
Grow a tree 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=0
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.
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. Attributes
feature_importances_ndarray of shape (n_features,)
Return the feature importances.
max_features_int
The inferred value of max_features.
n_features_int
The number of features when fit is performed.
n_outputs_int
The number of outputs when fit is performed.
tree_Tree instance
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes. See also
DecisionTreeClassifier
A decision tree classifier. 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
https://en.wikipedia.org/wiki/Decision_tree_learning
2
L. Breiman, J. Friedman, R. Olshen, and C. Stone, “Classification and Regression Trees”, Wadsworth, Belmont, CA, 1984.
3
T. Hastie, R. Tibshirani and J. Friedman. “Elements of Statistical Learning”, Springer, 2009.
4
L. Breiman, and A. Cutler, “Random Forests”, https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Examples >>> from sklearn.datasets import load_diabetes
>>> from sklearn.model_selection import cross_val_score
>>> from sklearn.tree import DecisionTreeRegressor
>>> X, y = load_diabetes(return_X_y=True)
>>> regressor = DecisionTreeRegressor(random_state=0)
>>> cross_val_score(regressor, X, y, cv=10)
...
...
array([-0.39..., -0.46..., 0.02..., 0.06..., -0.50...,
0.16..., 0.11..., -0.73..., -0.30..., -0.00...])
Methods
apply(X[, check_input]) Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …]) Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input]) Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …]) Build a decision tree regressor from the training set (X, y).
get_depth() Return the depth of the decision tree.
get_n_leaves() Return the number of leaves of the decision tree.
get_params([deep]) Get parameters for this estimator.
predict(X[, check_input]) Predict class or 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.
apply(X, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance).
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (real numbers). Use dtype=np.float64 and order='C' for maximum efficiency.
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.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeRegressor
Fitted estimator.
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree.
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves.
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, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict 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.tree.DecisionTreeRegressor
Release Highlights for scikit-learn 0.24
Release Highlights for scikit-learn 0.22
Decision Tree Regression
Multi-output Decision Tree Regression
Decision Tree Regression with AdaBoost
Single estimator versus bagging: bias-variance decomposition
Advanced Plotting With Partial Dependence
Imputing missing values with variants of IterativeImputer
Using KBinsDiscretizer to discretize continuous features | sklearn.modules.generated.sklearn.tree.decisiontreeregressor |
apply(X, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering. | sklearn.modules.generated.sklearn.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.apply |
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas. | sklearn.modules.generated.sklearn.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.cost_complexity_pruning_path |
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes. | sklearn.modules.generated.sklearn.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.decision_path |
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance). | sklearn.modules.generated.sklearn.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.feature_importances_ |
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (real numbers). Use dtype=np.float64 and order='C' for maximum efficiency.
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.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeRegressor
Fitted estimator. | sklearn.modules.generated.sklearn.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.fit |
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree. | sklearn.modules.generated.sklearn.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.get_depth |
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves. | sklearn.modules.generated.sklearn.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.get_n_leaves |
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.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.get_params |
predict(X, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict values. | sklearn.modules.generated.sklearn.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.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.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.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.tree.decisiontreeregressor#sklearn.tree.DecisionTreeRegressor.set_params |
sklearn.tree.export_graphviz(decision_tree, out_file=None, *, max_depth=None, feature_names=None, class_names=None, label='all', filled=False, leaves_parallel=False, impurity=True, node_ids=False, proportion=False, rotate=False, rounded=False, special_characters=False, precision=3) [source]
Export a decision tree in DOT format. This function generates a GraphViz representation of the decision tree, which is then written into out_file. Once exported, graphical renderings can be generated using, for example: $ dot -Tps tree.dot -o tree.ps (PostScript format)
$ dot -Tpng tree.dot -o tree.png (PNG format)
The sample counts that are shown are weighted with any sample_weights that might be present. Read more in the User Guide. Parameters
decision_treedecision tree classifier
The decision tree to be exported to GraphViz.
out_fileobject or str, default=None
Handle or name of the output file. If None, the result is returned as a string. Changed in version 0.20: Default of out_file changed from “tree.dot” to None.
max_depthint, default=None
The maximum depth of the representation. If None, the tree is fully generated.
feature_nameslist of str, default=None
Names of each of the features. If None generic names will be used (“feature_0”, “feature_1”, …).
class_nameslist of str or bool, default=None
Names of each of the target classes in ascending numerical order. Only relevant for classification and not supported for multi-output. If True, shows a symbolic representation of the class name.
label{‘all’, ‘root’, ‘none’}, default=’all’
Whether to show informative labels for impurity, etc. Options include ‘all’ to show at every node, ‘root’ to show only at the top root node, or ‘none’ to not show at any node.
filledbool, default=False
When set to True, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output.
leaves_parallelbool, default=False
When set to True, draw all leaf nodes at the bottom of the tree.
impuritybool, default=True
When set to True, show the impurity at each node.
node_idsbool, default=False
When set to True, show the ID number on each node.
proportionbool, default=False
When set to True, change the display of ‘values’ and/or ‘samples’ to be proportions and percentages respectively.
rotatebool, default=False
When set to True, orient tree left to right rather than top-down.
roundedbool, default=False
When set to True, draw node boxes with rounded corners and use Helvetica fonts instead of Times-Roman.
special_charactersbool, default=False
When set to False, ignore special characters for PostScript compatibility.
precisionint, default=3
Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node. Returns
dot_datastring
String representation of the input tree in GraphViz dot format. Only returned if out_file is None. New in version 0.18. Examples >>> from sklearn.datasets import load_iris
>>> from sklearn import tree
>>> clf = tree.DecisionTreeClassifier()
>>> iris = load_iris()
>>> clf = clf.fit(iris.data, iris.target)
>>> tree.export_graphviz(clf)
'digraph Tree {... | sklearn.modules.generated.sklearn.tree.export_graphviz#sklearn.tree.export_graphviz |
sklearn.tree.export_text(decision_tree, *, feature_names=None, max_depth=10, spacing=3, decimals=2, show_weights=False) [source]
Build a text report showing the rules of a decision tree. Note that backwards compatibility may not be supported. Parameters
decision_treeobject
The decision tree estimator to be exported. It can be an instance of DecisionTreeClassifier or DecisionTreeRegressor.
feature_nameslist of str, default=None
A list of length n_features containing the feature names. If None generic names will be used (“feature_0”, “feature_1”, …).
max_depthint, default=10
Only the first max_depth levels of the tree are exported. Truncated branches will be marked with “…”.
spacingint, default=3
Number of spaces between edges. The higher it is, the wider the result.
decimalsint, default=2
Number of decimal digits to display.
show_weightsbool, default=False
If true the classification weights will be exported on each leaf. The classification weights are the number of samples each class. Returns
reportstring
Text summary of all the rules in the decision tree. Examples >>> from sklearn.datasets import load_iris
>>> from sklearn.tree import DecisionTreeClassifier
>>> from sklearn.tree import export_text
>>> iris = load_iris()
>>> X = iris['data']
>>> y = iris['target']
>>> decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
>>> decision_tree = decision_tree.fit(X, y)
>>> r = export_text(decision_tree, feature_names=iris['feature_names'])
>>> print(r)
|--- petal width (cm) <= 0.80
| |--- class: 0
|--- petal width (cm) > 0.80
| |--- petal width (cm) <= 1.75
| | |--- class: 1
| |--- petal width (cm) > 1.75
| | |--- class: 2 | sklearn.modules.generated.sklearn.tree.export_text#sklearn.tree.export_text |
class sklearn.tree.ExtraTreeClassifier(*, criterion='gini', splitter='random', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, class_weight=None, ccp_alpha=0.0) [source]
An extremely randomized tree classifier. Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the max_features randomly selected features and the best split among those is chosen. When max_features is set 1, this amounts to building a totally random decision tree. Warning: Extra-trees should only be used within ensemble methods. Read more in the User Guide. Parameters
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.
splitter{“random”, “best”}, default=”random”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
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_featuresint, float, {“auto”, “sqrt”, “log2”} or None, 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 int(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.
random_stateint, RandomState instance or None, default=None
Used to pick randomly the max_features used at each split. See Glossary for details.
max_leaf_nodesint, default=None
Grow a tree 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.
class_weightdict, list of dict or “balanced”, default=None
Weights associated with classes in the form {class_label: weight}. If None, 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)) 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. Attributes
classes_ndarray of shape (n_classes,) or list of ndarray
The classes labels (single output problem), or a list of arrays of class labels (multi-output problem).
max_features_int
The inferred value of max_features.
n_classes_int or list of int
The number of classes (for single output problems), or a list containing the number of classes for each output (for multi-output problems).
feature_importances_ndarray of shape (n_features,)
Return the feature importances.
n_features_int
The number of features when fit is performed.
n_outputs_int
The number of outputs when fit is performed.
tree_Tree instance
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes. See also
ExtraTreeRegressor
An extremely randomized tree regressor.
sklearn.ensemble.ExtraTreesClassifier
An extra-trees classifier.
sklearn.ensemble.ExtraTreesRegressor
An extra-trees regressor. 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.datasets import load_iris
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.ensemble import BaggingClassifier
>>> from sklearn.tree import ExtraTreeClassifier
>>> X, y = load_iris(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, random_state=0)
>>> extra_tree = ExtraTreeClassifier(random_state=0)
>>> cls = BaggingClassifier(extra_tree, random_state=0).fit(
... X_train, y_train)
>>> cls.score(X_test, y_test)
0.8947...
Methods
apply(X[, check_input]) Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …]) Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input]) Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …]) Build a decision tree classifier from the training set (X, y).
get_depth() Return the depth of the decision tree.
get_n_leaves() Return the number of leaves of the decision tree.
get_params([deep]) Get parameters for this estimator.
predict(X[, check_input]) Predict class or regression value for X.
predict_log_proba(X) Predict class log-probabilities of the input samples X.
predict_proba(X[, check_input]) Predict class probabilities of the input samples 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, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance).
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeClassifier
Fitted estimator.
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree.
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves.
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, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict values.
predict_log_proba(X) [source]
Predict class log-probabilities of the input samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
predict_proba(X, check_input=True) [source]
Predict class probabilities of the input samples X. The predicted class probability 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, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
probandarray of shape (n_samples, n_classes) or 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.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier |
sklearn.tree.ExtraTreeClassifier
class sklearn.tree.ExtraTreeClassifier(*, criterion='gini', splitter='random', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, class_weight=None, ccp_alpha=0.0) [source]
An extremely randomized tree classifier. Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the max_features randomly selected features and the best split among those is chosen. When max_features is set 1, this amounts to building a totally random decision tree. Warning: Extra-trees should only be used within ensemble methods. Read more in the User Guide. Parameters
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.
splitter{“random”, “best”}, default=”random”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
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_featuresint, float, {“auto”, “sqrt”, “log2”} or None, 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 int(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.
random_stateint, RandomState instance or None, default=None
Used to pick randomly the max_features used at each split. See Glossary for details.
max_leaf_nodesint, default=None
Grow a tree 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.
class_weightdict, list of dict or “balanced”, default=None
Weights associated with classes in the form {class_label: weight}. If None, 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)) 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. Attributes
classes_ndarray of shape (n_classes,) or list of ndarray
The classes labels (single output problem), or a list of arrays of class labels (multi-output problem).
max_features_int
The inferred value of max_features.
n_classes_int or list of int
The number of classes (for single output problems), or a list containing the number of classes for each output (for multi-output problems).
feature_importances_ndarray of shape (n_features,)
Return the feature importances.
n_features_int
The number of features when fit is performed.
n_outputs_int
The number of outputs when fit is performed.
tree_Tree instance
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes. See also
ExtraTreeRegressor
An extremely randomized tree regressor.
sklearn.ensemble.ExtraTreesClassifier
An extra-trees classifier.
sklearn.ensemble.ExtraTreesRegressor
An extra-trees regressor. 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.datasets import load_iris
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.ensemble import BaggingClassifier
>>> from sklearn.tree import ExtraTreeClassifier
>>> X, y = load_iris(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, random_state=0)
>>> extra_tree = ExtraTreeClassifier(random_state=0)
>>> cls = BaggingClassifier(extra_tree, random_state=0).fit(
... X_train, y_train)
>>> cls.score(X_test, y_test)
0.8947...
Methods
apply(X[, check_input]) Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …]) Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input]) Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …]) Build a decision tree classifier from the training set (X, y).
get_depth() Return the depth of the decision tree.
get_n_leaves() Return the number of leaves of the decision tree.
get_params([deep]) Get parameters for this estimator.
predict(X[, check_input]) Predict class or regression value for X.
predict_log_proba(X) Predict class log-probabilities of the input samples X.
predict_proba(X[, check_input]) Predict class probabilities of the input samples 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, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance).
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeClassifier
Fitted estimator.
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree.
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves.
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, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict values.
predict_log_proba(X) [source]
Predict class log-probabilities of the input samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
predict_proba(X, check_input=True) [source]
Predict class probabilities of the input samples X. The predicted class probability 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, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
probandarray of shape (n_samples, n_classes) or 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.tree.extratreeclassifier |
apply(X, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.apply |
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.cost_complexity_pruning_path |
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.decision_path |
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance). | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.feature_importances_ |
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree classifier from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeClassifier
Fitted estimator. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.fit |
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.get_depth |
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.get_n_leaves |
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.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.get_params |
predict(X, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict values. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.predict |
predict_log_proba(X) [source]
Predict class log-probabilities of the input samples X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix. Returns
probandarray of shape (n_samples, n_classes) or list of n_outputs such arrays if n_outputs > 1
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.predict_log_proba |
predict_proba(X, check_input=True) [source]
Predict class probabilities of the input samples X. The predicted class probability 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, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
probandarray of shape (n_samples, n_classes) or 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_. | sklearn.modules.generated.sklearn.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.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.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.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.tree.extratreeclassifier#sklearn.tree.ExtraTreeClassifier.set_params |
class sklearn.tree.ExtraTreeRegressor(*, criterion='mse', splitter='random', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', random_state=None, min_impurity_decrease=0.0, min_impurity_split=None, max_leaf_nodes=None, ccp_alpha=0.0) [source]
An extremely randomized tree regressor. Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the max_features randomly selected features and the best split among those is chosen. When max_features is set 1, this amounts to building a totally random decision tree. Warning: Extra-trees should only be used within ensemble methods. Read more in the User Guide. Parameters
criterion{“mse”, “friedman_mse”, “mae”}, default=”mse”
The function to measure the quality of a split. Supported criteria are “mse” for the mean squared error, which is equal to variance reduction as feature selection criterion and “mae” for the mean absolute error. New in version 0.18: Mean Absolute Error (MAE) criterion. New in version 0.24: Poisson deviance criterion.
splitter{“random”, “best”}, default=”random”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
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_featuresint, float, {“auto”, “sqrt”, “log2”} or None, 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 int(max_features * n_features) features are considered at each split. If “auto”, then max_features=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.
random_stateint, RandomState instance or None, default=None
Used to pick randomly the max_features used at each split. See Glossary for details.
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.
max_leaf_nodesint, default=None
Grow a tree 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.
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. Attributes
max_features_int
The inferred value of max_features.
n_features_int
The number of features when fit is performed.
feature_importances_ndarray of shape (n_features,)
Return the feature importances.
n_outputs_int
The number of outputs when fit is performed.
tree_Tree instance
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes. See also
ExtraTreeClassifier
An extremely randomized tree classifier.
sklearn.ensemble.ExtraTreesClassifier
An extra-trees classifier.
sklearn.ensemble.ExtraTreesRegressor
An extra-trees regressor. 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.datasets import load_diabetes
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.ensemble import BaggingRegressor
>>> from sklearn.tree import ExtraTreeRegressor
>>> X, y = load_diabetes(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, random_state=0)
>>> extra_tree = ExtraTreeRegressor(random_state=0)
>>> reg = BaggingRegressor(extra_tree, random_state=0).fit(
... X_train, y_train)
>>> reg.score(X_test, y_test)
0.33...
Methods
apply(X[, check_input]) Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …]) Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input]) Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …]) Build a decision tree regressor from the training set (X, y).
get_depth() Return the depth of the decision tree.
get_n_leaves() Return the number of leaves of the decision tree.
get_params([deep]) Get parameters for this estimator.
predict(X[, check_input]) Predict class or 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.
apply(X, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance).
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (real numbers). Use dtype=np.float64 and order='C' for maximum efficiency.
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.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeRegressor
Fitted estimator.
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree.
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves.
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, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict 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.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor |
sklearn.tree.ExtraTreeRegressor
class sklearn.tree.ExtraTreeRegressor(*, criterion='mse', splitter='random', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', random_state=None, min_impurity_decrease=0.0, min_impurity_split=None, max_leaf_nodes=None, ccp_alpha=0.0) [source]
An extremely randomized tree regressor. Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the max_features randomly selected features and the best split among those is chosen. When max_features is set 1, this amounts to building a totally random decision tree. Warning: Extra-trees should only be used within ensemble methods. Read more in the User Guide. Parameters
criterion{“mse”, “friedman_mse”, “mae”}, default=”mse”
The function to measure the quality of a split. Supported criteria are “mse” for the mean squared error, which is equal to variance reduction as feature selection criterion and “mae” for the mean absolute error. New in version 0.18: Mean Absolute Error (MAE) criterion. New in version 0.24: Poisson deviance criterion.
splitter{“random”, “best”}, default=”random”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split.
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_featuresint, float, {“auto”, “sqrt”, “log2”} or None, 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 int(max_features * n_features) features are considered at each split. If “auto”, then max_features=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.
random_stateint, RandomState instance or None, default=None
Used to pick randomly the max_features used at each split. See Glossary for details.
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.
max_leaf_nodesint, default=None
Grow a tree 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.
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. Attributes
max_features_int
The inferred value of max_features.
n_features_int
The number of features when fit is performed.
feature_importances_ndarray of shape (n_features,)
Return the feature importances.
n_outputs_int
The number of outputs when fit is performed.
tree_Tree instance
The underlying Tree object. Please refer to help(sklearn.tree._tree.Tree) for attributes of Tree object and Understanding the decision tree structure for basic usage of these attributes. See also
ExtraTreeClassifier
An extremely randomized tree classifier.
sklearn.ensemble.ExtraTreesClassifier
An extra-trees classifier.
sklearn.ensemble.ExtraTreesRegressor
An extra-trees regressor. 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.datasets import load_diabetes
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.ensemble import BaggingRegressor
>>> from sklearn.tree import ExtraTreeRegressor
>>> X, y = load_diabetes(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, random_state=0)
>>> extra_tree = ExtraTreeRegressor(random_state=0)
>>> reg = BaggingRegressor(extra_tree, random_state=0).fit(
... X_train, y_train)
>>> reg.score(X_test, y_test)
0.33...
Methods
apply(X[, check_input]) Return the index of the leaf that each sample is predicted as.
cost_complexity_pruning_path(X, y[, …]) Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path(X[, check_input]) Return the decision path in the tree.
fit(X, y[, sample_weight, check_input, …]) Build a decision tree regressor from the training set (X, y).
get_depth() Return the depth of the decision tree.
get_n_leaves() Return the number of leaves of the decision tree.
get_params([deep]) Get parameters for this estimator.
predict(X[, check_input]) Predict class or 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.
apply(X, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering.
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas.
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance).
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (real numbers). Use dtype=np.float64 and order='C' for maximum efficiency.
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.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeRegressor
Fitted estimator.
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree.
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves.
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, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict 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.tree.extratreeregressor |
apply(X, check_input=True) [source]
Return the index of the leaf that each sample is predicted as. New in version 0.17. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within [0; self.tree_.node_count), possibly with gaps in the numbering. | sklearn.modules.generated.sklearn.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.apply |
cost_complexity_pruning_path(X, y, sample_weight=None) [source]
Compute the pruning path during Minimal Cost-Complexity Pruning. See Minimal Cost-Complexity Pruning for details on the pruning process. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
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. Splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns
ccp_pathBunch
Dictionary-like object, with the following attributes.
ccp_alphasndarray
Effective alphas of subtree during pruning.
impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in ccp_alphas. | sklearn.modules.generated.sklearn.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.cost_complexity_pruning_path |
decision_path(X, check_input=True) [source]
Return the decision path in the tree. New in version 0.18. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes. | sklearn.modules.generated.sklearn.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.decision_path |
property feature_importances_
Return the feature importances. 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,)
Normalized total reduction of criteria by feature (Gini importance). | sklearn.modules.generated.sklearn.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.feature_importances_ |
fit(X, y, sample_weight=None, check_input=True, X_idx_sorted='deprecated') [source]
Build a decision tree regressor from the training set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (real numbers). Use dtype=np.float64 and order='C' for maximum efficiency.
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.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
X_idx_sorteddeprecated, default=”deprecated”
This parameter is deprecated and has no effect. It will be removed in 1.1 (renaming of 0.26). Deprecated since version 0.24. Returns
selfDecisionTreeRegressor
Fitted estimator. | sklearn.modules.generated.sklearn.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.fit |
get_depth() [source]
Return the depth of the decision tree. The depth of a tree is the maximum distance between the root and any leaf. Returns
self.tree_.max_depthint
The maximum depth of the tree. | sklearn.modules.generated.sklearn.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.get_depth |
get_n_leaves() [source]
Return the number of leaves of the decision tree. Returns
self.tree_.n_leavesint
Number of leaves. | sklearn.modules.generated.sklearn.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.get_n_leaves |
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.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.get_params |
predict(X, check_input=True) [source]
Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csr_matrix.
check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you do. Returns
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The predicted classes, or the predict values. | sklearn.modules.generated.sklearn.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.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.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.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.tree.extratreeregressor#sklearn.tree.ExtraTreeRegressor.set_params |
sklearn.tree.plot_tree(decision_tree, *, max_depth=None, feature_names=None, class_names=None, label='all', filled=False, impurity=True, node_ids=False, proportion=False, rotate='deprecated', rounded=False, precision=3, ax=None, fontsize=None) [source]
Plot a decision tree. The sample counts that are shown are weighted with any sample_weights that might be present. The visualization is fit automatically to the size of the axis. Use the figsize or dpi arguments of plt.figure to control the size of the rendering. Read more in the User Guide. New in version 0.21. Parameters
decision_treedecision tree regressor or classifier
The decision tree to be plotted.
max_depthint, default=None
The maximum depth of the representation. If None, the tree is fully generated.
feature_nameslist of strings, default=None
Names of each of the features. If None, generic names will be used (“X[0]”, “X[1]”, …).
class_nameslist of str or bool, default=None
Names of each of the target classes in ascending numerical order. Only relevant for classification and not supported for multi-output. If True, shows a symbolic representation of the class name.
label{‘all’, ‘root’, ‘none’}, default=’all’
Whether to show informative labels for impurity, etc. Options include ‘all’ to show at every node, ‘root’ to show only at the top root node, or ‘none’ to not show at any node.
filledbool, default=False
When set to True, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output.
impuritybool, default=True
When set to True, show the impurity at each node.
node_idsbool, default=False
When set to True, show the ID number on each node.
proportionbool, default=False
When set to True, change the display of ‘values’ and/or ‘samples’ to be proportions and percentages respectively.
rotatebool, default=False
This parameter has no effect on the matplotlib tree visualisation and it is kept here for backward compatibility. Deprecated since version 0.23: rotate is deprecated in 0.23 and will be removed in 1.0 (renaming of 0.25).
roundedbool, default=False
When set to True, draw node boxes with rounded corners and use Helvetica fonts instead of Times-Roman.
precisionint, default=3
Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node.
axmatplotlib axis, default=None
Axes to plot to. If None, use current axis. Any previous content is cleared.
fontsizeint, default=None
Size of text font. If None, determined automatically to fit figure. Returns
annotationslist of artists
List containing the artists for the annotation boxes making up the tree. Examples >>> from sklearn.datasets import load_iris
>>> from sklearn import tree
>>> clf = tree.DecisionTreeClassifier(random_state=0)
>>> iris = load_iris()
>>> clf = clf.fit(iris.data, iris.target)
>>> tree.plot_tree(clf)
[Text(251.5,345.217,'X[3] <= 0.8... | sklearn.modules.generated.sklearn.tree.plot_tree#sklearn.tree.plot_tree |
sklearn.utils.all_estimators(type_filter=None) [source]
Get a list of all estimators from sklearn. This function crawls the module and gets all classes that inherit from BaseEstimator. Classes that are defined in test-modules are not included. Parameters
type_filter{“classifier”, “regressor”, “cluster”, “transformer”} or list of such str, default=None
Which kind of estimators should be returned. If None, no filter is applied and all estimators are returned. Possible values are ‘classifier’, ‘regressor’, ‘cluster’ and ‘transformer’ to get estimators only of these specific types, or a list of these to get the estimators that fit at least one of the types. Returns
estimatorslist of tuples
List of (name, class), where name is the class name as string and class is the actuall type of the class. | sklearn.modules.generated.sklearn.utils.all_estimators#sklearn.utils.all_estimators |
sklearn.utils.arrayfuncs.min_pos()
Find the minimum value of an array over positive values Returns a huge value if none of the values are positive | sklearn.modules.generated.sklearn.utils.arrayfuncs.min_pos#sklearn.utils.arrayfuncs.min_pos |
sklearn.utils.assert_all_finite(X, *, allow_nan=False) [source]
Throw a ValueError if X contains NaN or infinity. Parameters
X{ndarray, sparse matrix}
allow_nanbool, default=False | sklearn.modules.generated.sklearn.utils.assert_all_finite#sklearn.utils.assert_all_finite |
sklearn.utils.as_float_array(X, *, copy=True, force_all_finite=True) [source]
Converts an array-like to an array of floats. The new dtype will be np.float32 or np.float64, depending on the original type. The function can create a copy or modify the argument depending on the argument copy. Parameters
X{array-like, sparse matrix}
copybool, default=True
If True, a copy of X will be created. If False, a copy may still be returned if X’s dtype is not a floating point type.
force_all_finitebool or ‘allow-nan’, default=True
Whether to raise an error on np.inf, np.nan, pd.NA in X. The possibilities are: True: Force all values of X to be finite. False: accepts np.inf, np.nan, pd.NA in X. ‘allow-nan’: accepts only np.nan and pd.NA values in X. Values cannot be infinite. New in version 0.20: force_all_finite accepts the string 'allow-nan'. Changed in version 0.23: Accepts pd.NA and converts it into np.nan Returns
XT{ndarray, sparse matrix}
An array of type float. | sklearn.modules.generated.sklearn.utils.as_float_array#sklearn.utils.as_float_array |
sklearn.utils.Bunch(**kwargs) [source]
Container object exposing keys as attributes. Bunch objects are sometimes used as an output for functions and methods. They extend dictionaries by enabling values to be accessed by key, bunch["value_key"], or by an attribute, bunch.value_key. Examples >>> b = Bunch(a=1, b=2)
>>> b['b']
2
>>> b.b
2
>>> b.a = 3
>>> b['a']
3
>>> b.c = 6
>>> b['c']
6 | sklearn.modules.generated.sklearn.utils.bunch#sklearn.utils.Bunch |
sklearn.utils.check_array(array, accept_sparse=False, *, accept_large_sparse=True, dtype='numeric', order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, ensure_min_samples=1, ensure_min_features=1, estimator=None) [source]
Input validation on an array, list, sparse matrix or similar. By default, the input is checked to be a non-empty 2D array containing only finite values. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters
arrayobject
Input object to check / convert.
accept_sparsestr, bool or list/tuple of str, default=False
String[s] representing allowed sparse matrix formats, such as ‘csc’, ‘csr’, etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error.
accept_large_sparsebool, default=True
If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by accept_sparse, accept_large_sparse=False will cause it to be accepted only if its indices are stored with a 32-bit dtype. New in version 0.20.
dtype‘numeric’, type, list of type or None, default=’numeric’
Data type of result. If None, the dtype of the input is preserved. If “numeric”, dtype is preserved unless array.dtype is object. If dtype is a list of types, conversion on the first type is only performed if the dtype of the input is not in the list.
order{‘F’, ‘C’} or None, default=None
Whether an array will be forced to be fortran or c-style. When order is None (default), then if copy=False, nothing is ensured about the memory layout of the output array; otherwise (copy=True) the memory layout of the returned array is kept as close as possible to the original array.
copybool, default=False
Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion.
force_all_finitebool or ‘allow-nan’, default=True
Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: True: Force all values of array to be finite. False: accepts np.inf, np.nan, pd.NA in array. ‘allow-nan’: accepts only np.nan and pd.NA values in array. Values cannot be infinite. New in version 0.20: force_all_finite accepts the string 'allow-nan'. Changed in version 0.23: Accepts pd.NA and converts it into np.nan
ensure_2dbool, default=True
Whether to raise a value error if array is not 2D.
allow_ndbool, default=False
Whether to allow array.ndim > 2.
ensure_min_samplesint, default=1
Make sure that the array has a minimum number of samples in its first axis (rows for a 2D array). Setting to 0 disables this check.
ensure_min_featuresint, default=1
Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when the input data has effectively 2 dimensions or is originally 1D and ensure_2d is True. Setting to 0 disables this check.
estimatorstr or estimator instance, default=None
If passed, include the name of the estimator in warning messages. Returns
array_convertedobject
The converted and validated array. | sklearn.modules.generated.sklearn.utils.check_array#sklearn.utils.check_array |
sklearn.utils.check_consistent_length(*arrays) [source]
Check that all arrays have consistent first dimensions. Checks whether all objects in arrays have the same shape or length. Parameters
*arrayslist or tuple of input objects.
Objects that will be checked for consistent length. | sklearn.modules.generated.sklearn.utils.check_consistent_length#sklearn.utils.check_consistent_length |
sklearn.utils.check_random_state(seed) [source]
Turn seed into a np.random.RandomState instance Parameters
seedNone, int or instance of RandomState
If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError. | sklearn.modules.generated.sklearn.utils.check_random_state#sklearn.utils.check_random_state |
sklearn.utils.check_scalar(x, name, target_type, *, min_val=None, max_val=None) [source]
Validate scalar parameters type and value. Parameters
xobject
The scalar parameter to validate.
namestr
The name of the parameter to be printed in error messages.
target_typetype or tuple
Acceptable data types for the parameter.
min_valfloat or int, default=None
The minimum valid value the parameter can take. If None (default) it is implied that the parameter does not have a lower bound.
max_valfloat or int, default=None
The maximum valid value the parameter can take. If None (default) it is implied that the parameter does not have an upper bound. Raises
TypeError
If the parameter’s type does not match the desired type. ValueError
If the parameter’s value violates the given bounds. | sklearn.modules.generated.sklearn.utils.check_scalar#sklearn.utils.check_scalar |
sklearn.utils.check_X_y(X, y, accept_sparse=False, *, accept_large_sparse=True, dtype='numeric', order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, multi_output=False, ensure_min_samples=1, ensure_min_features=1, y_numeric=False, estimator=None) [source]
Input validation for standard estimators. Checks X and y for consistent length, enforces X to be 2D and y 1D. By default, X is checked to be non-empty and containing only finite values. Standard input checks are also applied to y, such as checking that y does not have np.nan or np.inf targets. For multi-label y, set multi_output=True to allow 2D and sparse y. If the dtype of X is object, attempt converting to float, raising on failure. Parameters
X{ndarray, list, sparse matrix}
Input data.
y{ndarray, list, sparse matrix}
Labels.
accept_sparsestr, bool or list of str, default=False
String[s] representing allowed sparse matrix formats, such as ‘csc’, ‘csr’, etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error.
accept_large_sparsebool, default=True
If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by accept_sparse, accept_large_sparse will cause it to be accepted only if its indices are stored with a 32-bit dtype. New in version 0.20.
dtype‘numeric’, type, list of type or None, default=’numeric’
Data type of result. If None, the dtype of the input is preserved. If “numeric”, dtype is preserved unless array.dtype is object. If dtype is a list of types, conversion on the first type is only performed if the dtype of the input is not in the list.
order{‘F’, ‘C’}, default=None
Whether an array will be forced to be fortran or c-style.
copybool, default=False
Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion.
force_all_finitebool or ‘allow-nan’, default=True
Whether to raise an error on np.inf, np.nan, pd.NA in X. This parameter does not influence whether y can have np.inf, np.nan, pd.NA values. The possibilities are: True: Force all values of X to be finite. False: accepts np.inf, np.nan, pd.NA in X. ‘allow-nan’: accepts only np.nan or pd.NA values in X. Values cannot be infinite. New in version 0.20: force_all_finite accepts the string 'allow-nan'. Changed in version 0.23: Accepts pd.NA and converts it into np.nan
ensure_2dbool, default=True
Whether to raise a value error if X is not 2D.
allow_ndbool, default=False
Whether to allow X.ndim > 2.
multi_outputbool, default=False
Whether to allow 2D y (array or sparse matrix). If false, y will be validated as a vector. y cannot have np.nan or np.inf values if multi_output=True.
ensure_min_samplesint, default=1
Make sure that X has a minimum number of samples in its first axis (rows for a 2D array).
ensure_min_featuresint, default=1
Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when X has effectively 2 dimensions or is originally 1D and ensure_2d is True. Setting to 0 disables this check.
y_numericbool, default=False
Whether to ensure that y has a numeric type. If dtype of y is object, it is converted to float64. Should only be used for regression algorithms.
estimatorstr or estimator instance, default=None
If passed, include the name of the estimator in warning messages. Returns
X_convertedobject
The converted and validated X.
y_convertedobject
The converted and validated y. | sklearn.modules.generated.sklearn.utils.check_x_y#sklearn.utils.check_X_y |
sklearn.utils.class_weight.compute_class_weight(class_weight, *, classes, y) [source]
Estimate class weights for unbalanced datasets. Parameters
class_weightdict, ‘balanced’ or None
If ‘balanced’, class weights will be given by n_samples / (n_classes * np.bincount(y)). If a dictionary is given, keys are classes and values are corresponding class weights. If None is given, the class weights will be uniform.
classesndarray
Array of the classes occurring in the data, as given by np.unique(y_org) with y_org the original class labels.
yarray-like of shape (n_samples,)
Array of original class labels per sample. Returns
class_weight_vectndarray of shape (n_classes,)
Array with class_weight_vect[i] the weight for i-th class. References The “balanced” heuristic is inspired by Logistic Regression in Rare Events Data, King, Zen, 2001. | sklearn.modules.generated.sklearn.utils.class_weight.compute_class_weight#sklearn.utils.class_weight.compute_class_weight |
sklearn.utils.class_weight.compute_sample_weight(class_weight, y, *, indices=None) [source]
Estimate sample weights by class for unbalanced datasets. Parameters
class_weightdict, list of dicts, “balanced”, or 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: n_samples / (n_classes * np.bincount(y)). For multi-output, the weights of each column of y will be multiplied.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
Array of original class labels per sample.
indicesarray-like of shape (n_subsample,), default=None
Array of indices to be used in a subsample. Can be of length less than n_samples in the case of a subsample, or equal to n_samples in the case of a bootstrap subsample with repeated indices. If None, the sample weight will be calculated over the full sample. Only “balanced” is supported for class_weight if this is provided. Returns
sample_weight_vectndarray of shape (n_samples,)
Array with sample weights as applied to the original y. | sklearn.modules.generated.sklearn.utils.class_weight.compute_sample_weight#sklearn.utils.class_weight.compute_sample_weight |
sklearn.utils.deprecated(extra='') [source]
Decorator to mark a function or class as deprecated. Issue a warning when the function is called/the class is instantiated and adds a warning to the docstring. The optional extra argument will be appended to the deprecation message and the docstring. Note: to use this with the default value for extra, put in an empty of parentheses: >>> from sklearn.utils import deprecated
>>> deprecated()
<sklearn.utils.deprecation.deprecated object at ...>
>>> @deprecated()
... def some_function(): pass
Parameters
extrastr, default=’’
To be added to the deprecation messages. | sklearn.modules.generated.sklearn.utils.deprecated#sklearn.utils.deprecated |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.