2011-11-07 17:54:14 +08:00
|
|
|
"""
|
|
|
|
|
This module gathers tree-based methods, including decision, regression and
|
2012-07-02 17:51:50 +08:00
|
|
|
randomized trees. Single and multi-output problems are both handled.
|
2011-11-07 17:54:14 +08:00
|
|
|
"""
|
|
|
|
|
|
2013-07-09 15:03:00 +08:00
|
|
|
# Authors: Gilles Louppe <g.louppe@gmail.com>
|
|
|
|
|
# Peter Prettenhofer <peter.prettenhofer@gmail.com>
|
|
|
|
|
# Brian Holt <bdholt1@gmail.com>
|
|
|
|
|
# Noel Dawe <noel@dawe.me>
|
|
|
|
|
# Satrajit Gosh <satrajit.ghosh@gmail.com>
|
2013-09-12 19:57:47 +08:00
|
|
|
# Joly Arnaud <arnaud.v.joly@gmail.com>
|
2014-04-04 04:28:08 +08:00
|
|
|
# Fares Hedayati <fares.hedayati@gmail.com>
|
2016-07-27 23:46:49 +08:00
|
|
|
# Nelson Liu <nelson@nelsonliu.me>
|
2014-04-04 04:28:08 +08:00
|
|
|
#
|
2016-04-01 08:25:31 +08:00
|
|
|
# License: BSD 3 clause
|
2011-02-12 20:58:01 +08:00
|
|
|
|
2013-02-26 15:26:35 +08:00
|
|
|
import numbers
|
2017-04-04 00:38:53 +08:00
|
|
|
import warnings
|
2021-03-02 09:04:58 +08:00
|
|
|
import copy
|
2015-09-11 16:39:21 +08:00
|
|
|
from abc import ABCMeta
|
|
|
|
|
from abc import abstractmethod
|
2014-07-10 14:48:20 +08:00
|
|
|
from math import ceil
|
2011-09-09 01:40:57 +08:00
|
|
|
|
2014-04-04 04:28:08 +08:00
|
|
|
import numpy as np
|
|
|
|
|
from scipy.sparse import issparse
|
|
|
|
|
|
2015-09-11 16:39:21 +08:00
|
|
|
from ..base import BaseEstimator
|
|
|
|
|
from ..base import ClassifierMixin
|
2019-08-20 21:02:45 +08:00
|
|
|
from ..base import clone
|
2015-09-11 16:39:21 +08:00
|
|
|
from ..base import RegressorMixin
|
2017-08-08 20:36:03 +08:00
|
|
|
from ..base import is_classifier
|
2019-02-24 05:54:41 +08:00
|
|
|
from ..base import MultiOutputMixin
|
2019-08-20 21:02:45 +08:00
|
|
|
from ..utils import Bunch
|
2015-09-11 16:39:21 +08:00
|
|
|
from ..utils import check_random_state
|
2022-01-25 03:25:36 +08:00
|
|
|
from ..utils import check_scalar
|
2021-06-16 02:36:13 +08:00
|
|
|
from ..utils.deprecation import deprecated
|
2019-11-05 00:13:38 +08:00
|
|
|
from ..utils.validation import _check_sample_weight
|
2015-09-11 16:39:21 +08:00
|
|
|
from ..utils import compute_sample_weight
|
2015-08-04 20:57:58 +08:00
|
|
|
from ..utils.multiclass import check_classification_targets
|
2016-12-12 18:57:43 +08:00
|
|
|
from ..utils.validation import check_is_fitted
|
2014-04-04 04:28:08 +08:00
|
|
|
|
2015-09-09 03:07:30 +08:00
|
|
|
from ._criterion import Criterion
|
|
|
|
|
from ._splitter import Splitter
|
2015-09-11 16:39:21 +08:00
|
|
|
from ._tree import DepthFirstTreeBuilder
|
|
|
|
|
from ._tree import BestFirstTreeBuilder
|
2013-11-22 00:41:57 +08:00
|
|
|
from ._tree import Tree
|
2019-08-20 21:02:45 +08:00
|
|
|
from ._tree import _build_pruned_tree_ccp
|
|
|
|
|
from ._tree import ccp_pruning_path
|
2015-09-09 03:07:30 +08:00
|
|
|
from . import _tree, _splitter, _criterion
|
2011-02-12 20:58:01 +08:00
|
|
|
|
2011-11-12 23:20:43 +08:00
|
|
|
__all__ = [
|
|
|
|
|
"DecisionTreeClassifier",
|
|
|
|
|
"DecisionTreeRegressor",
|
|
|
|
|
"ExtraTreeClassifier",
|
|
|
|
|
"ExtraTreeRegressor",
|
|
|
|
|
]
|
2011-02-12 20:58:01 +08:00
|
|
|
|
2013-07-04 23:19:45 +08:00
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Types and constants
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
2011-09-22 02:08:58 +08:00
|
|
|
DTYPE = _tree.DTYPE
|
2012-07-21 21:54:36 +08:00
|
|
|
DOUBLE = _tree.DOUBLE
|
2011-09-13 21:00:06 +08:00
|
|
|
|
2020-11-02 23:32:29 +08:00
|
|
|
CRITERIA_CLF = {"gini": _criterion.Gini, "entropy": _criterion.Entropy}
|
2021-05-11 04:10:21 +08:00
|
|
|
# TODO: Remove "mse" and "mae" in version 1.2.
|
2021-03-19 22:21:34 +08:00
|
|
|
CRITERIA_REG = {
|
|
|
|
|
"squared_error": _criterion.MSE,
|
|
|
|
|
"mse": _criterion.MSE,
|
2020-11-02 23:32:29 +08:00
|
|
|
"friedman_mse": _criterion.FriedmanMSE,
|
2021-05-11 04:10:21 +08:00
|
|
|
"absolute_error": _criterion.MAE,
|
2020-11-02 23:32:29 +08:00
|
|
|
"mae": _criterion.MAE,
|
|
|
|
|
"poisson": _criterion.Poisson,
|
|
|
|
|
}
|
2021-06-18 02:21:09 +08:00
|
|
|
|
2015-09-09 03:07:30 +08:00
|
|
|
DENSE_SPLITTERS = {"best": _splitter.BestSplitter, "random": _splitter.RandomSplitter}
|
2021-06-18 02:21:09 +08:00
|
|
|
|
2015-09-09 03:07:30 +08:00
|
|
|
SPARSE_SPLITTERS = {
|
|
|
|
|
"best": _splitter.BestSparseSplitter,
|
|
|
|
|
"random": _splitter.RandomSparseSplitter,
|
|
|
|
|
}
|
2011-08-02 01:36:46 +08:00
|
|
|
|
2013-07-04 23:19:45 +08:00
|
|
|
# =============================================================================
|
|
|
|
|
# Base decision tree
|
|
|
|
|
# =============================================================================
|
2011-10-05 16:16:51 +08:00
|
|
|
|
2014-04-04 04:28:08 +08:00
|
|
|
|
2019-09-05 16:13:30 +08:00
|
|
|
class BaseDecisionTree(MultiOutputMixin, BaseEstimator, metaclass=ABCMeta):
|
2011-11-04 23:53:20 +08:00
|
|
|
"""Base class for decision trees.
|
2011-02-12 20:58:01 +08:00
|
|
|
|
2011-11-12 01:23:09 +08:00
|
|
|
Warning: This class should not be used directly.
|
|
|
|
|
Use derived classes instead.
|
2011-11-04 23:53:20 +08:00
|
|
|
"""
|
2012-06-08 01:13:30 +08:00
|
|
|
|
|
|
|
|
@abstractmethod
|
2020-04-22 21:20:57 +08:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
2012-11-26 21:57:51 +08:00
|
|
|
criterion,
|
2013-07-04 23:19:45 +08:00
|
|
|
splitter,
|
2012-11-26 21:57:51 +08:00
|
|
|
max_depth,
|
|
|
|
|
min_samples_split,
|
2018-09-08 22:43:21 +08:00
|
|
|
min_samples_leaf,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf,
|
2012-11-26 21:57:51 +08:00
|
|
|
max_features,
|
2013-11-03 15:40:24 +08:00
|
|
|
max_leaf_nodes,
|
2014-12-23 08:50:58 +08:00
|
|
|
random_state,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease,
|
2015-09-11 16:39:21 +08:00
|
|
|
class_weight=None,
|
2019-08-20 21:02:45 +08:00
|
|
|
ccp_alpha=0.0,
|
|
|
|
|
):
|
2011-02-12 20:58:01 +08:00
|
|
|
self.criterion = criterion
|
2013-07-04 23:19:45 +08:00
|
|
|
self.splitter = splitter
|
2011-11-16 23:24:31 +08:00
|
|
|
self.max_depth = max_depth
|
2012-02-16 06:38:11 +08:00
|
|
|
self.min_samples_split = min_samples_split
|
2018-09-08 22:43:21 +08:00
|
|
|
self.min_samples_leaf = min_samples_leaf
|
2014-05-27 18:39:54 +08:00
|
|
|
self.min_weight_fraction_leaf = min_weight_fraction_leaf
|
2011-11-16 23:24:31 +08:00
|
|
|
self.max_features = max_features
|
2013-11-03 15:40:24 +08:00
|
|
|
self.max_leaf_nodes = max_leaf_nodes
|
2019-11-19 19:36:20 +08:00
|
|
|
self.random_state = random_state
|
2017-04-04 00:38:53 +08:00
|
|
|
self.min_impurity_decrease = min_impurity_decrease
|
2014-12-23 08:50:58 +08:00
|
|
|
self.class_weight = class_weight
|
2019-08-20 21:02:45 +08:00
|
|
|
self.ccp_alpha = ccp_alpha
|
2011-09-26 00:57:49 +08:00
|
|
|
|
2018-10-10 19:01:11 +08:00
|
|
|
def get_depth(self):
|
2019-11-06 06:36:57 +08:00
|
|
|
"""Return the depth of the decision tree.
|
2018-10-10 19:01:11 +08:00
|
|
|
|
|
|
|
|
The depth of a tree is the maximum distance between the root
|
|
|
|
|
and any leaf.
|
2019-11-06 06:36:57 +08:00
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
self.tree_.max_depth : int
|
|
|
|
|
The maximum depth of the tree.
|
2018-10-10 19:01:11 +08:00
|
|
|
"""
|
2019-08-14 04:09:07 +08:00
|
|
|
check_is_fitted(self)
|
2018-10-10 19:01:11 +08:00
|
|
|
return self.tree_.max_depth
|
|
|
|
|
|
|
|
|
|
def get_n_leaves(self):
|
2019-11-06 06:36:57 +08:00
|
|
|
"""Return the number of leaves of the decision tree.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
self.tree_.n_leaves : int
|
|
|
|
|
Number of leaves.
|
2018-10-10 19:01:11 +08:00
|
|
|
"""
|
2019-08-14 04:09:07 +08:00
|
|
|
check_is_fitted(self)
|
2018-10-10 19:01:11 +08:00
|
|
|
return self.tree_.n_leaves
|
|
|
|
|
|
2021-11-08 15:08:43 +08:00
|
|
|
def fit(self, X, y, sample_weight=None, check_input=True):
|
2015-09-11 16:39:21 +08:00
|
|
|
|
2013-07-19 15:53:29 +08:00
|
|
|
random_state = check_random_state(self.random_state)
|
2019-08-20 21:02:45 +08:00
|
|
|
|
2022-01-25 03:25:36 +08:00
|
|
|
check_scalar(
|
|
|
|
|
self.ccp_alpha,
|
|
|
|
|
name="ccp_alpha",
|
|
|
|
|
target_type=numbers.Real,
|
|
|
|
|
min_val=0.0,
|
|
|
|
|
)
|
2019-08-20 21:02:45 +08:00
|
|
|
|
2012-11-02 00:23:07 +08:00
|
|
|
if check_input:
|
2020-04-22 20:41:45 +08:00
|
|
|
# Need to validate separately here.
|
|
|
|
|
# We can't pass multi_ouput=True because that would allow y to be
|
|
|
|
|
# csr.
|
|
|
|
|
check_X_params = dict(dtype=DTYPE, accept_sparse="csc")
|
|
|
|
|
check_y_params = dict(ensure_2d=False, dtype=None)
|
|
|
|
|
X, y = self._validate_data(
|
|
|
|
|
X, y, validate_separately=(check_X_params, check_y_params)
|
|
|
|
|
)
|
2014-04-04 04:28:08 +08:00
|
|
|
if issparse(X):
|
|
|
|
|
X.sort_indices()
|
|
|
|
|
|
|
|
|
|
if X.indices.dtype != np.intc or X.indptr.dtype != np.intc:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"No support for np.int64 index based sparse matrices"
|
|
|
|
|
)
|
2012-07-11 17:58:18 +08:00
|
|
|
|
2020-11-02 23:32:29 +08:00
|
|
|
if self.criterion == "poisson":
|
|
|
|
|
if np.any(y < 0):
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Some value(s) of y are negative which is"
|
|
|
|
|
" not allowed for Poisson regression."
|
|
|
|
|
)
|
|
|
|
|
if np.sum(y) <= 0:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Sum of y is not positive which is "
|
|
|
|
|
"necessary for Poisson regression."
|
|
|
|
|
)
|
|
|
|
|
|
2013-07-19 15:53:29 +08:00
|
|
|
# Determine output settings
|
2021-06-16 02:36:13 +08:00
|
|
|
n_samples, self.n_features_in_ = X.shape
|
2017-08-08 20:36:03 +08:00
|
|
|
is_classification = is_classifier(self)
|
2011-11-04 15:20:10 +08:00
|
|
|
|
2012-06-28 16:09:21 +08:00
|
|
|
y = np.atleast_1d(y)
|
2015-01-11 03:49:42 +08:00
|
|
|
expanded_class_weight = None
|
2013-07-28 22:08:16 +08:00
|
|
|
|
2012-06-28 16:09:21 +08:00
|
|
|
if y.ndim == 1:
|
2012-11-26 21:11:36 +08:00
|
|
|
# reshape is necessary to preserve the data contiguity against vs
|
|
|
|
|
# [:, np.newaxis] that does not.
|
2012-11-26 17:21:12 +08:00
|
|
|
y = np.reshape(y, (-1, 1))
|
2012-06-28 16:09:21 +08:00
|
|
|
|
|
|
|
|
self.n_outputs_ = y.shape[1]
|
|
|
|
|
|
2011-11-04 15:20:10 +08:00
|
|
|
if is_classification:
|
2015-08-04 20:57:58 +08:00
|
|
|
check_classification_targets(y)
|
2012-07-12 21:03:13 +08:00
|
|
|
y = np.copy(y)
|
|
|
|
|
|
2012-12-04 23:24:07 +08:00
|
|
|
self.classes_ = []
|
|
|
|
|
self.n_classes_ = []
|
|
|
|
|
|
2014-12-23 08:50:58 +08:00
|
|
|
if self.class_weight is not None:
|
2015-01-08 18:31:24 +08:00
|
|
|
y_original = np.copy(y)
|
2014-12-23 08:50:58 +08:00
|
|
|
|
2020-06-24 22:51:51 +08:00
|
|
|
y_encoded = np.zeros(y.shape, dtype=int)
|
2014-04-04 04:28:08 +08:00
|
|
|
for k in range(self.n_outputs_):
|
2014-07-10 14:48:20 +08:00
|
|
|
classes_k, y_encoded[:, k] = np.unique(y[:, k], return_inverse=True)
|
2013-07-19 15:27:20 +08:00
|
|
|
self.classes_.append(classes_k)
|
|
|
|
|
self.n_classes_.append(classes_k.shape[0])
|
2014-07-10 14:48:20 +08:00
|
|
|
y = y_encoded
|
2011-08-16 04:40:55 +08:00
|
|
|
|
2014-12-23 08:50:58 +08:00
|
|
|
if self.class_weight is not None:
|
2015-02-01 10:27:29 +08:00
|
|
|
expanded_class_weight = compute_sample_weight(
|
|
|
|
|
self.class_weight, y_original
|
|
|
|
|
)
|
2014-12-23 08:50:58 +08:00
|
|
|
|
2019-09-20 19:27:21 +08:00
|
|
|
self.n_classes_ = np.array(self.n_classes_, dtype=np.intp)
|
2013-07-07 16:13:09 +08:00
|
|
|
|
2012-07-21 21:54:36 +08:00
|
|
|
if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:
|
|
|
|
|
y = np.ascontiguousarray(y, dtype=DOUBLE)
|
2012-06-28 16:09:21 +08:00
|
|
|
|
2011-11-02 19:32:48 +08:00
|
|
|
# Check parameters
|
2022-01-25 03:25:36 +08:00
|
|
|
if self.max_depth is not None:
|
|
|
|
|
check_scalar(
|
|
|
|
|
self.max_depth,
|
|
|
|
|
name="max_depth",
|
|
|
|
|
target_type=numbers.Integral,
|
|
|
|
|
min_val=1,
|
|
|
|
|
)
|
2019-12-24 16:41:21 +08:00
|
|
|
max_depth = np.iinfo(np.int32).max if self.max_depth is None else self.max_depth
|
2012-01-03 17:11:52 +08:00
|
|
|
|
2019-06-13 07:24:59 +08:00
|
|
|
if isinstance(self.min_samples_leaf, numbers.Integral):
|
2022-01-25 03:25:36 +08:00
|
|
|
check_scalar(
|
|
|
|
|
self.min_samples_leaf,
|
|
|
|
|
name="min_samples_leaf",
|
|
|
|
|
target_type=numbers.Integral,
|
|
|
|
|
min_val=1,
|
|
|
|
|
)
|
2018-09-08 22:43:21 +08:00
|
|
|
min_samples_leaf = self.min_samples_leaf
|
2014-07-10 14:48:20 +08:00
|
|
|
else: # float
|
2022-01-25 03:25:36 +08:00
|
|
|
check_scalar(
|
|
|
|
|
self.min_samples_leaf,
|
|
|
|
|
name="min_samples_leaf",
|
|
|
|
|
target_type=numbers.Real,
|
|
|
|
|
min_val=0.0,
|
2022-01-27 02:16:12 +08:00
|
|
|
include_boundaries="neither",
|
2022-01-25 03:25:36 +08:00
|
|
|
)
|
2018-09-08 22:43:21 +08:00
|
|
|
min_samples_leaf = int(ceil(self.min_samples_leaf * n_samples))
|
2014-07-10 14:48:20 +08:00
|
|
|
|
2019-06-13 07:24:59 +08:00
|
|
|
if isinstance(self.min_samples_split, numbers.Integral):
|
2022-01-25 03:25:36 +08:00
|
|
|
check_scalar(
|
|
|
|
|
self.min_samples_split,
|
|
|
|
|
name="min_samples_split",
|
|
|
|
|
target_type=numbers.Integral,
|
|
|
|
|
min_val=2,
|
|
|
|
|
)
|
2014-07-10 14:48:20 +08:00
|
|
|
min_samples_split = self.min_samples_split
|
|
|
|
|
else: # float
|
2022-01-25 03:25:36 +08:00
|
|
|
check_scalar(
|
|
|
|
|
self.min_samples_split,
|
|
|
|
|
name="min_samples_split",
|
|
|
|
|
target_type=numbers.Real,
|
|
|
|
|
min_val=0.0,
|
|
|
|
|
max_val=1.0,
|
|
|
|
|
include_boundaries="right",
|
|
|
|
|
)
|
2014-07-10 14:48:20 +08:00
|
|
|
min_samples_split = int(ceil(self.min_samples_split * n_samples))
|
|
|
|
|
min_samples_split = max(2, min_samples_split)
|
|
|
|
|
|
|
|
|
|
min_samples_split = max(min_samples_split, 2 * min_samples_leaf)
|
|
|
|
|
|
2022-01-25 03:25:36 +08:00
|
|
|
check_scalar(
|
|
|
|
|
self.min_weight_fraction_leaf,
|
|
|
|
|
name="min_weight_fraction_leaf",
|
|
|
|
|
target_type=numbers.Real,
|
|
|
|
|
min_val=0.0,
|
|
|
|
|
max_val=0.5,
|
|
|
|
|
)
|
|
|
|
|
|
2019-01-03 21:50:05 +08:00
|
|
|
if isinstance(self.max_features, str):
|
2012-01-03 17:11:52 +08:00
|
|
|
if self.max_features == "auto":
|
|
|
|
|
if is_classification:
|
2021-06-16 02:36:13 +08:00
|
|
|
max_features = max(1, int(np.sqrt(self.n_features_in_)))
|
2022-03-24 00:59:23 +08:00
|
|
|
warnings.warn(
|
|
|
|
|
"`max_features='auto'` has been deprecated in 1.1 "
|
|
|
|
|
"and will be removed in 1.3. To keep the past behaviour, "
|
|
|
|
|
"explicitly set `max_features='sqrt'`.",
|
|
|
|
|
FutureWarning,
|
|
|
|
|
)
|
2012-01-03 17:11:52 +08:00
|
|
|
else:
|
2021-06-16 02:36:13 +08:00
|
|
|
max_features = self.n_features_in_
|
2022-03-24 00:59:23 +08:00
|
|
|
warnings.warn(
|
|
|
|
|
"`max_features='auto'` has been deprecated in 1.1 "
|
|
|
|
|
"and will be removed in 1.3. To keep the past behaviour, "
|
|
|
|
|
"explicitly set `max_features=1.0'`.",
|
|
|
|
|
FutureWarning,
|
|
|
|
|
)
|
2012-01-03 17:11:52 +08:00
|
|
|
elif self.max_features == "sqrt":
|
2021-06-16 02:36:13 +08:00
|
|
|
max_features = max(1, int(np.sqrt(self.n_features_in_)))
|
2012-01-03 17:11:52 +08:00
|
|
|
elif self.max_features == "log2":
|
2021-06-16 02:36:13 +08:00
|
|
|
max_features = max(1, int(np.log2(self.n_features_in_)))
|
2012-01-03 17:11:52 +08:00
|
|
|
else:
|
2019-12-14 06:10:17 +08:00
|
|
|
raise ValueError(
|
|
|
|
|
"Invalid value for max_features. "
|
|
|
|
|
"Allowed string values are 'auto', "
|
|
|
|
|
"'sqrt' or 'log2'."
|
|
|
|
|
)
|
2012-01-03 17:11:52 +08:00
|
|
|
elif self.max_features is None:
|
2021-06-16 02:36:13 +08:00
|
|
|
max_features = self.n_features_in_
|
2019-06-13 07:24:59 +08:00
|
|
|
elif isinstance(self.max_features, numbers.Integral):
|
2022-01-25 03:25:36 +08:00
|
|
|
check_scalar(
|
|
|
|
|
self.max_features,
|
|
|
|
|
name="max_features",
|
|
|
|
|
target_type=numbers.Integral,
|
|
|
|
|
min_val=1,
|
2022-02-08 04:32:22 +08:00
|
|
|
include_boundaries="left",
|
2022-01-25 03:25:36 +08:00
|
|
|
)
|
2012-01-03 17:11:52 +08:00
|
|
|
max_features = self.max_features
|
2013-03-05 04:57:52 +08:00
|
|
|
else: # float
|
2022-01-25 03:25:36 +08:00
|
|
|
check_scalar(
|
|
|
|
|
self.max_features,
|
|
|
|
|
name="max_features",
|
|
|
|
|
target_type=numbers.Real,
|
|
|
|
|
min_val=0.0,
|
|
|
|
|
max_val=1.0,
|
|
|
|
|
include_boundaries="right",
|
|
|
|
|
)
|
2014-05-28 23:03:48 +08:00
|
|
|
if self.max_features > 0.0:
|
2021-06-16 02:36:13 +08:00
|
|
|
max_features = max(1, int(self.max_features * self.n_features_in_))
|
2014-05-28 23:03:48 +08:00
|
|
|
else:
|
|
|
|
|
max_features = 0
|
2011-11-16 23:24:31 +08:00
|
|
|
|
2013-09-12 19:57:47 +08:00
|
|
|
self.max_features_ = max_features
|
|
|
|
|
|
2022-01-25 03:25:36 +08:00
|
|
|
if self.max_leaf_nodes is not None:
|
|
|
|
|
check_scalar(
|
|
|
|
|
self.max_leaf_nodes,
|
|
|
|
|
name="max_leaf_nodes",
|
|
|
|
|
target_type=numbers.Integral,
|
|
|
|
|
min_val=2,
|
|
|
|
|
)
|
|
|
|
|
max_leaf_nodes = -1 if self.max_leaf_nodes is None else self.max_leaf_nodes
|
|
|
|
|
|
|
|
|
|
check_scalar(
|
|
|
|
|
self.min_impurity_decrease,
|
|
|
|
|
name="min_impurity_decrease",
|
|
|
|
|
target_type=numbers.Real,
|
|
|
|
|
min_val=0.0,
|
|
|
|
|
)
|
|
|
|
|
|
2011-11-02 19:32:48 +08:00
|
|
|
if len(y) != n_samples:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Number of labels=%d does not match number of samples=%d"
|
2012-01-03 17:21:18 +08:00
|
|
|
% (len(y), n_samples)
|
2021-06-18 02:21:09 +08:00
|
|
|
)
|
2013-01-06 07:24:22 +08:00
|
|
|
|
|
|
|
|
if sample_weight is not None:
|
2019-11-05 00:13:38 +08:00
|
|
|
sample_weight = _check_sample_weight(sample_weight, X, DOUBLE)
|
2013-01-06 07:24:22 +08:00
|
|
|
|
2015-01-11 03:49:42 +08:00
|
|
|
if expanded_class_weight is not None:
|
2014-12-23 08:50:58 +08:00
|
|
|
if sample_weight is not None:
|
2015-01-13 13:27:13 +08:00
|
|
|
sample_weight = sample_weight * expanded_class_weight
|
2014-12-23 08:50:58 +08:00
|
|
|
else:
|
2015-01-11 03:49:42 +08:00
|
|
|
sample_weight = expanded_class_weight
|
2014-12-23 08:50:58 +08:00
|
|
|
|
2014-06-28 15:26:46 +08:00
|
|
|
# Set min_weight_leaf from min_weight_fraction_leaf
|
2016-09-28 12:48:23 +08:00
|
|
|
if sample_weight is None:
|
2018-09-08 22:43:21 +08:00
|
|
|
min_weight_leaf = self.min_weight_fraction_leaf * n_samples
|
2014-06-28 15:26:46 +08:00
|
|
|
else:
|
2018-09-08 22:43:21 +08:00
|
|
|
min_weight_leaf = self.min_weight_fraction_leaf * np.sum(sample_weight)
|
2014-06-28 15:26:46 +08:00
|
|
|
|
2011-11-01 21:29:00 +08:00
|
|
|
# Build tree
|
2013-07-08 20:50:48 +08:00
|
|
|
criterion = self.criterion
|
|
|
|
|
if not isinstance(criterion, Criterion):
|
2013-07-08 20:47:47 +08:00
|
|
|
if is_classification:
|
|
|
|
|
criterion = CRITERIA_CLF[self.criterion](
|
|
|
|
|
self.n_outputs_, self.n_classes_
|
|
|
|
|
)
|
|
|
|
|
else:
|
2016-07-25 14:44:59 +08:00
|
|
|
criterion = CRITERIA_REG[self.criterion](self.n_outputs_, n_samples)
|
2021-03-19 22:21:34 +08:00
|
|
|
# TODO: Remove in v1.2
|
|
|
|
|
if self.criterion == "mse":
|
|
|
|
|
warnings.warn(
|
|
|
|
|
"Criterion 'mse' was deprecated in v1.0 and will be "
|
|
|
|
|
"removed in version 1.2. Use `criterion='squared_error'` "
|
|
|
|
|
"which is equivalent.",
|
|
|
|
|
FutureWarning,
|
|
|
|
|
)
|
2021-05-11 04:10:21 +08:00
|
|
|
elif self.criterion == "mae":
|
|
|
|
|
warnings.warn(
|
|
|
|
|
"Criterion 'mae' was deprecated in v1.0 and will be "
|
|
|
|
|
"removed in version 1.2. Use `criterion='absolute_error'` "
|
|
|
|
|
"which is equivalent.",
|
|
|
|
|
FutureWarning,
|
|
|
|
|
)
|
2021-03-02 09:04:58 +08:00
|
|
|
else:
|
|
|
|
|
# Make a deepcopy in case the criterion has mutable attributes that
|
|
|
|
|
# might be shared and modified concurrently during parallel fitting
|
|
|
|
|
criterion = copy.deepcopy(criterion)
|
2013-07-08 20:47:47 +08:00
|
|
|
|
2014-04-04 04:28:08 +08:00
|
|
|
SPLITTERS = SPARSE_SPLITTERS if issparse(X) else DENSE_SPLITTERS
|
|
|
|
|
|
2013-07-08 20:50:48 +08:00
|
|
|
splitter = self.splitter
|
2013-07-08 20:47:47 +08:00
|
|
|
if not isinstance(self.splitter, Splitter):
|
2013-07-08 20:50:48 +08:00
|
|
|
splitter = SPLITTERS[self.splitter](
|
|
|
|
|
criterion,
|
2013-09-12 19:57:47 +08:00
|
|
|
self.max_features_,
|
2014-07-10 14:48:20 +08:00
|
|
|
min_samples_leaf,
|
2014-06-28 15:26:46 +08:00
|
|
|
min_weight_leaf,
|
2019-09-11 02:39:52 +08:00
|
|
|
random_state,
|
|
|
|
|
)
|
2013-07-08 20:47:47 +08:00
|
|
|
|
2019-09-20 19:27:21 +08:00
|
|
|
if is_classifier(self):
|
2021-06-16 02:36:13 +08:00
|
|
|
self.tree_ = Tree(self.n_features_in_, self.n_classes_, self.n_outputs_)
|
2019-09-20 19:27:21 +08:00
|
|
|
else:
|
2021-06-16 02:36:13 +08:00
|
|
|
self.tree_ = Tree(
|
|
|
|
|
self.n_features_in_,
|
2021-09-18 01:04:54 +08:00
|
|
|
# TODO: tree shouldn't need this in this case
|
2019-09-20 19:27:21 +08:00
|
|
|
np.array([1] * self.n_outputs_, dtype=np.intp),
|
|
|
|
|
self.n_outputs_,
|
|
|
|
|
)
|
2012-07-11 17:58:18 +08:00
|
|
|
|
2013-11-30 22:35:59 +08:00
|
|
|
# Use BestFirst if max_leaf_nodes given; use DepthFirst otherwise
|
2013-12-01 01:34:13 +08:00
|
|
|
if max_leaf_nodes < 0:
|
2014-03-18 04:45:27 +08:00
|
|
|
builder = DepthFirstTreeBuilder(
|
|
|
|
|
splitter,
|
|
|
|
|
min_samples_split,
|
2014-07-10 14:48:20 +08:00
|
|
|
min_samples_leaf,
|
2014-06-28 15:26:46 +08:00
|
|
|
min_weight_leaf,
|
2017-04-04 00:38:53 +08:00
|
|
|
max_depth,
|
2021-06-16 00:18:47 +08:00
|
|
|
self.min_impurity_decrease,
|
|
|
|
|
)
|
2013-11-21 04:10:16 +08:00
|
|
|
else:
|
2014-03-18 04:45:27 +08:00
|
|
|
builder = BestFirstTreeBuilder(
|
|
|
|
|
splitter,
|
|
|
|
|
min_samples_split,
|
2014-07-10 14:48:20 +08:00
|
|
|
min_samples_leaf,
|
2014-06-28 15:26:46 +08:00
|
|
|
min_weight_leaf,
|
2014-05-27 18:39:54 +08:00
|
|
|
max_depth,
|
2016-10-09 21:39:17 +08:00
|
|
|
max_leaf_nodes,
|
2021-06-16 00:18:47 +08:00
|
|
|
self.min_impurity_decrease,
|
|
|
|
|
)
|
2013-12-01 01:34:13 +08:00
|
|
|
|
2020-06-18 01:58:47 +08:00
|
|
|
builder.build(self.tree_, X, y, sample_weight)
|
2011-09-26 00:41:50 +08:00
|
|
|
|
2019-09-20 19:27:21 +08:00
|
|
|
if self.n_outputs_ == 1 and is_classifier(self):
|
2012-12-04 21:25:14 +08:00
|
|
|
self.n_classes_ = self.n_classes_[0]
|
|
|
|
|
self.classes_ = self.classes_[0]
|
|
|
|
|
|
2019-08-20 21:02:45 +08:00
|
|
|
self._prune_tree()
|
|
|
|
|
|
2011-08-09 20:29:39 +08:00
|
|
|
return self
|
|
|
|
|
|
2015-04-16 16:34:33 +08:00
|
|
|
def _validate_X_predict(self, X, check_input):
|
2020-08-31 19:58:23 +08:00
|
|
|
"""Validate the training data on predict (probabilities)."""
|
2015-04-16 16:34:33 +08:00
|
|
|
if check_input:
|
2020-11-03 01:40:20 +08:00
|
|
|
X = self._validate_data(X, dtype=DTYPE, accept_sparse="csr", reset=False)
|
2015-04-16 16:34:33 +08:00
|
|
|
if issparse(X) and (
|
|
|
|
|
X.indices.dtype != np.intc or X.indptr.dtype != np.intc
|
|
|
|
|
):
|
|
|
|
|
raise ValueError("No support for np.int64 index based sparse matrices")
|
2020-11-03 01:40:20 +08:00
|
|
|
else:
|
|
|
|
|
# The number of features is checked regardless of `check_input`
|
|
|
|
|
self._check_n_features(X, reset=False)
|
2015-04-16 16:34:33 +08:00
|
|
|
return X
|
|
|
|
|
|
2015-04-14 07:30:02 +08:00
|
|
|
def predict(self, X, check_input=True):
|
2012-12-23 20:13:21 +08:00
|
|
|
"""Predict class or regression value for X.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
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.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
2014-04-04 04:28:08 +08:00
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
check_input : bool, default=True
|
2015-04-14 07:30:02 +08:00
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
|
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
2019-10-03 08:54:32 +08:00
|
|
|
y : array-like of shape (n_samples,) or (n_samples, n_outputs)
|
2011-09-26 19:25:39 +08:00
|
|
|
The predicted classes, or the predict values.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
"""
|
2019-08-14 04:09:07 +08:00
|
|
|
check_is_fitted(self)
|
2015-04-16 16:34:33 +08:00
|
|
|
X = self._validate_X_predict(X, check_input)
|
2012-12-05 05:10:09 +08:00
|
|
|
proba = self.tree_.predict(X)
|
2015-04-16 16:34:33 +08:00
|
|
|
n_samples = X.shape[0]
|
2012-06-28 16:09:21 +08:00
|
|
|
|
2012-12-04 23:24:07 +08:00
|
|
|
# Classification
|
2017-08-08 20:36:03 +08:00
|
|
|
if is_classifier(self):
|
2012-12-04 21:25:14 +08:00
|
|
|
if self.n_outputs_ == 1:
|
2013-07-16 17:00:53 +08:00
|
|
|
return self.classes_.take(np.argmax(proba, axis=1), axis=0)
|
2012-06-28 16:09:21 +08:00
|
|
|
|
2012-12-04 21:25:14 +08:00
|
|
|
else:
|
2019-02-19 17:46:30 +08:00
|
|
|
class_type = self.classes_[0].dtype
|
|
|
|
|
predictions = np.zeros((n_samples, self.n_outputs_), dtype=class_type)
|
2014-04-04 04:28:08 +08:00
|
|
|
for k in range(self.n_outputs_):
|
2012-12-05 05:10:09 +08:00
|
|
|
predictions[:, k] = self.classes_[k].take(
|
2012-12-23 20:56:35 +08:00
|
|
|
np.argmax(proba[:, k], axis=1), axis=0
|
|
|
|
|
)
|
2011-08-09 20:29:39 +08:00
|
|
|
|
2012-12-05 05:10:09 +08:00
|
|
|
return predictions
|
2012-12-04 21:25:14 +08:00
|
|
|
|
2012-12-04 23:24:07 +08:00
|
|
|
# Regression
|
2012-12-04 21:25:14 +08:00
|
|
|
else:
|
|
|
|
|
if self.n_outputs_ == 1:
|
2013-07-16 17:00:53 +08:00
|
|
|
return proba[:, 0]
|
2012-12-04 21:25:14 +08:00
|
|
|
|
|
|
|
|
else:
|
2012-12-05 05:10:09 +08:00
|
|
|
return proba[:, :, 0]
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2015-04-16 16:19:57 +08:00
|
|
|
def apply(self, X, check_input=True):
|
2019-12-14 06:10:17 +08:00
|
|
|
"""Return the index of the leaf that each sample is predicted as.
|
2015-01-08 02:30:57 +08:00
|
|
|
|
2015-11-04 06:43:19 +08:00
|
|
|
.. versionadded:: 0.17
|
|
|
|
|
|
2015-01-08 10:55:23 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-10-03 08:54:32 +08:00
|
|
|
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
2015-01-10 12:36:15 +08:00
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
2015-01-08 02:30:57 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
check_input : bool, default=True
|
2015-04-16 16:19:57 +08:00
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
|
|
|
|
|
2015-01-08 10:55:23 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
2019-12-14 06:10:17 +08:00
|
|
|
X_leaves : array-like of shape (n_samples,)
|
2015-04-02 17:51:00 +08:00
|
|
|
For each datapoint x in X, return the index of the leaf x
|
|
|
|
|
ends up in. Leaves are numbered within
|
2015-04-11 21:53:41 +08:00
|
|
|
``[0; self.tree_.node_count)``, possibly with gaps in the
|
|
|
|
|
numbering.
|
2015-01-08 10:55:23 +08:00
|
|
|
"""
|
2019-08-14 04:09:07 +08:00
|
|
|
check_is_fitted(self)
|
2015-04-16 16:34:33 +08:00
|
|
|
X = self._validate_X_predict(X, check_input)
|
2015-01-08 02:03:10 +08:00
|
|
|
return self.tree_.apply(X)
|
|
|
|
|
|
2015-10-21 16:37:55 +08:00
|
|
|
def decision_path(self, X, check_input=True):
|
2019-11-06 06:36:57 +08:00
|
|
|
"""Return the decision path in the tree.
|
2015-10-20 19:15:24 +08:00
|
|
|
|
2016-09-28 04:19:47 +08:00
|
|
|
.. versionadded:: 0.18
|
|
|
|
|
|
2015-10-20 19:15:24 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-10-03 08:54:32 +08:00
|
|
|
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
2015-10-20 19:15:24 +08:00
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
check_input : bool, default=True
|
2015-10-20 19:15:24 +08:00
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
2019-12-14 06:10:17 +08:00
|
|
|
indicator : sparse matrix of shape (n_samples, n_nodes)
|
|
|
|
|
Return a node indicator CSR matrix where non zero elements
|
2015-10-21 00:02:09 +08:00
|
|
|
indicates that the samples goes through the nodes.
|
2015-10-20 19:15:24 +08:00
|
|
|
"""
|
|
|
|
|
X = self._validate_X_predict(X, check_input)
|
2015-10-21 16:37:55 +08:00
|
|
|
return self.tree_.decision_path(X)
|
2015-10-20 19:15:24 +08:00
|
|
|
|
2019-08-20 21:02:45 +08:00
|
|
|
def _prune_tree(self):
|
|
|
|
|
"""Prune tree using Minimal Cost-Complexity Pruning."""
|
|
|
|
|
check_is_fitted(self)
|
|
|
|
|
|
|
|
|
|
if self.ccp_alpha == 0.0:
|
|
|
|
|
return
|
|
|
|
|
|
2019-09-20 19:27:21 +08:00
|
|
|
# build pruned tree
|
|
|
|
|
if is_classifier(self):
|
|
|
|
|
n_classes = np.atleast_1d(self.n_classes_)
|
2021-06-16 02:36:13 +08:00
|
|
|
pruned_tree = Tree(self.n_features_in_, n_classes, self.n_outputs_)
|
2019-09-20 19:27:21 +08:00
|
|
|
else:
|
2021-06-16 02:36:13 +08:00
|
|
|
pruned_tree = Tree(
|
|
|
|
|
self.n_features_in_,
|
2019-09-20 19:27:21 +08:00
|
|
|
# TODO: the tree shouldn't need this param
|
|
|
|
|
np.array([1] * self.n_outputs_, dtype=np.intp),
|
|
|
|
|
self.n_outputs_,
|
|
|
|
|
)
|
2019-08-20 21:02:45 +08:00
|
|
|
_build_pruned_tree_ccp(pruned_tree, self.tree_, self.ccp_alpha)
|
|
|
|
|
|
|
|
|
|
self.tree_ = pruned_tree
|
|
|
|
|
|
|
|
|
|
def cost_complexity_pruning_path(self, X, y, sample_weight=None):
|
|
|
|
|
"""Compute the pruning path during Minimal Cost-Complexity Pruning.
|
|
|
|
|
|
2019-11-02 03:39:28 +08:00
|
|
|
See :ref:`minimal_cost_complexity_pruning` for details on the pruning
|
2019-08-20 21:02:45 +08:00
|
|
|
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``.
|
|
|
|
|
|
|
|
|
|
y : array-like of shape (n_samples,) or (n_samples, n_outputs)
|
|
|
|
|
The target values (class labels) as integers or strings.
|
|
|
|
|
|
|
|
|
|
sample_weight : array-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
|
|
|
|
|
-------
|
2020-02-27 17:04:04 +08:00
|
|
|
ccp_path : :class:`~sklearn.utils.Bunch`
|
|
|
|
|
Dictionary-like object, with the following attributes.
|
2019-08-20 21:02:45 +08:00
|
|
|
|
|
|
|
|
ccp_alphas : ndarray
|
|
|
|
|
Effective alphas of subtree during pruning.
|
|
|
|
|
|
|
|
|
|
impurities : ndarray
|
|
|
|
|
Sum of the impurities of the subtree leaves for the
|
|
|
|
|
corresponding alpha value in ``ccp_alphas``.
|
|
|
|
|
"""
|
|
|
|
|
est = clone(self).set_params(ccp_alpha=0.0)
|
|
|
|
|
est.fit(X, y, sample_weight=sample_weight)
|
|
|
|
|
return Bunch(**ccp_pruning_path(est.tree_))
|
|
|
|
|
|
2015-04-02 17:51:00 +08:00
|
|
|
@property
|
|
|
|
|
def feature_importances_(self):
|
|
|
|
|
"""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.
|
|
|
|
|
|
2020-02-05 22:20:20 +08:00
|
|
|
Warning: impurity-based feature importances can be misleading for
|
|
|
|
|
high cardinality features (many unique values). See
|
|
|
|
|
:func:`sklearn.inspection.permutation_importance` as an alternative.
|
|
|
|
|
|
2015-04-02 17:51:00 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
2019-12-14 06:10:17 +08:00
|
|
|
feature_importances_ : ndarray of shape (n_features,)
|
2019-12-20 08:26:02 +08:00
|
|
|
Normalized total reduction of criteria by feature
|
|
|
|
|
(Gini importance).
|
2015-04-02 17:51:00 +08:00
|
|
|
"""
|
2019-08-14 04:09:07 +08:00
|
|
|
check_is_fitted(self)
|
2015-04-02 17:51:00 +08:00
|
|
|
|
|
|
|
|
return self.tree_.compute_feature_importances()
|
|
|
|
|
|
2011-04-02 05:28:20 +08:00
|
|
|
|
2013-07-04 23:19:45 +08:00
|
|
|
# =============================================================================
|
|
|
|
|
# Public estimators
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
2021-06-18 02:21:09 +08:00
|
|
|
|
2019-09-05 16:13:30 +08:00
|
|
|
class DecisionTreeClassifier(ClassifierMixin, BaseDecisionTree):
|
2011-09-26 20:09:03 +08:00
|
|
|
"""A decision tree classifier.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2015-06-03 12:24:04 +08:00
|
|
|
Read more in the :ref:`User Guide <tree>`.
|
|
|
|
|
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
criterion : {"gini", "entropy"}, default="gini"
|
2011-09-26 20:09:03 +08:00
|
|
|
The function to measure the quality of a split. Supported criteria are
|
|
|
|
|
"gini" for the Gini impurity and "entropy" for the information gain.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
splitter : {"best", "random"}, default="best"
|
2013-08-23 07:24:07 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_depth : int, default=None
|
2011-11-02 04:42:57 +08:00
|
|
|
The maximum depth of the tree. If None, then nodes are expanded until
|
2012-02-16 18:29:52 +08:00
|
|
|
all leaves are pure or until all leaves contain less than
|
|
|
|
|
min_samples_split samples.
|
2011-08-09 20:29:39 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_samples_split : int or float, default=2
|
2014-07-10 14:48:20 +08:00
|
|
|
The minimum number of samples required to split an internal node:
|
|
|
|
|
|
2018-09-08 22:43:21 +08:00
|
|
|
- If int, then consider `min_samples_split` as the minimum number.
|
|
|
|
|
- If float, then `min_samples_split` is a fraction and
|
2014-07-10 14:48:20 +08:00
|
|
|
`ceil(min_samples_split * n_samples)` are the minimum
|
|
|
|
|
number of samples for each split.
|
|
|
|
|
|
2016-09-28 04:19:47 +08:00
|
|
|
.. versionchanged:: 0.18
|
2018-02-18 07:46:05 +08:00
|
|
|
Added float values for fractions.
|
2016-09-28 04:19:47 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_samples_leaf : int or float, default=1
|
2018-09-08 22:43:21 +08:00
|
|
|
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
|
2014-07-10 14:48:20 +08:00
|
|
|
`ceil(min_samples_leaf * n_samples)` are the minimum
|
|
|
|
|
number of samples for each node.
|
2012-02-14 18:09:40 +08:00
|
|
|
|
2016-09-28 04:19:47 +08:00
|
|
|
.. versionchanged:: 0.18
|
2018-02-18 07:46:05 +08:00
|
|
|
Added float values for fractions.
|
2016-09-28 04:19:47 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_weight_fraction_leaf : float, default=0.0
|
2016-09-28 12:48:23 +08:00
|
|
|
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.
|
2014-05-27 18:39:54 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_features : int, float or {"auto", "sqrt", "log2"}, default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
The number of features to consider when looking for the best split:
|
2014-12-23 08:50:58 +08:00
|
|
|
|
2017-07-12 00:42:10 +08:00
|
|
|
- If int, then consider `max_features` features at each split.
|
2018-02-18 07:46:05 +08:00
|
|
|
- If float, then `max_features` is a fraction and
|
2017-07-12 00:42:10 +08:00
|
|
|
`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`.
|
2014-12-23 08:50:58 +08:00
|
|
|
|
2022-03-24 00:59:23 +08:00
|
|
|
.. deprecated:: 1.1
|
|
|
|
|
The `"auto"` option was deprecated in 1.1 and will be removed
|
|
|
|
|
in 1.3.
|
|
|
|
|
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
2014-12-23 08:50:58 +08:00
|
|
|
|
2020-08-31 19:58:23 +08:00
|
|
|
random_state : int, RandomState instance or None, default=None
|
2020-01-08 23:11:24 +08:00
|
|
|
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 :term:`Glossary <random_state>` for details.
|
2011-11-01 21:22:31 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_leaf_nodes : int, default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
2017-05-23 14:42:08 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_impurity_decrease : float, default=0.0
|
2017-04-04 00:38:53 +08:00
|
|
|
A node will be split if this split induces a decrease of the impurity
|
|
|
|
|
greater than or equal to this value.
|
2016-07-27 23:46:49 +08:00
|
|
|
|
2017-04-04 00:38:53 +08:00
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.19
|
2016-07-29 02:31:55 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
class_weight : dict, list of dict or "balanced", default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
Weights associated with classes in the form ``{class_label: weight}``.
|
2019-12-14 06:10:17 +08:00
|
|
|
If None, all classes are supposed to have weight one. For
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
ccp_alpha : non-negative float, default=0.0
|
2019-08-20 21:02:45 +08:00
|
|
|
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
|
|
|
|
|
:ref:`minimal_cost_complexity_pruning` for details.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.22
|
|
|
|
|
|
2011-12-28 00:44:04 +08:00
|
|
|
Attributes
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
classes_ : ndarray of shape (n_classes,) or list of ndarray
|
2013-01-19 22:45:09 +08:00
|
|
|
The classes labels (single output problem),
|
|
|
|
|
or a list of arrays of class labels (multi-output problem).
|
2012-12-23 20:13:21 +08:00
|
|
|
|
2019-10-03 08:54:32 +08:00
|
|
|
feature_importances_ : ndarray of shape (n_features,)
|
2020-02-01 20:18:11 +08:00
|
|
|
The impurity-based feature importances.
|
|
|
|
|
The higher, the more important the feature.
|
|
|
|
|
The importance of a feature is computed as the (normalized)
|
2013-03-12 05:51:22 +08:00
|
|
|
total reduction of the criterion brought by that feature. It is also
|
|
|
|
|
known as the Gini importance [4]_.
|
2011-12-28 00:44:04 +08:00
|
|
|
|
2020-02-05 22:20:20 +08:00
|
|
|
Warning: impurity-based feature importances can be misleading for
|
|
|
|
|
high cardinality features (many unique values). See
|
|
|
|
|
:func:`sklearn.inspection.permutation_importance` as an alternative.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_features_ : int
|
2015-05-12 21:00:27 +08:00
|
|
|
The inferred value of max_features.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
n_classes_ : int or list of int
|
2015-05-12 21:00:27 +08:00
|
|
|
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.
|
|
|
|
|
|
2021-06-16 02:36:13 +08:00
|
|
|
.. deprecated:: 1.0
|
|
|
|
|
`n_features_` is deprecated in 1.0 and will be removed in
|
|
|
|
|
1.2. Use `n_features_in_` instead.
|
|
|
|
|
|
2021-06-09 22:58:03 +08:00
|
|
|
n_features_in_ : int
|
|
|
|
|
Number of features seen during :term:`fit`.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.24
|
|
|
|
|
|
2021-08-26 19:44:45 +08:00
|
|
|
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
|
|
|
|
Names of features seen during :term:`fit`. Defined only when `X`
|
|
|
|
|
has feature names that are all strings.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 1.0
|
|
|
|
|
|
2015-05-12 21:00:27 +08:00
|
|
|
n_outputs_ : int
|
|
|
|
|
The number of outputs when ``fit`` is performed.
|
|
|
|
|
|
2020-08-31 19:58:23 +08:00
|
|
|
tree_ : Tree instance
|
2018-06-11 07:00:55 +08:00
|
|
|
The underlying Tree object. Please refer to
|
|
|
|
|
``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and
|
|
|
|
|
:ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`
|
|
|
|
|
for basic usage of these attributes.
|
2015-05-12 21:00:27 +08:00
|
|
|
|
2019-11-04 02:15:16 +08:00
|
|
|
See Also
|
|
|
|
|
--------
|
|
|
|
|
DecisionTreeRegressor : A decision tree regressor.
|
|
|
|
|
|
2017-02-27 01:48:19 +08:00
|
|
|
Notes
|
|
|
|
|
-----
|
2017-04-09 23:16:19 +08:00
|
|
|
The default values for the parameters controlling the size of the trees
|
2018-09-08 22:43:21 +08:00
|
|
|
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
|
2017-04-09 23:16:19 +08:00
|
|
|
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.
|
|
|
|
|
|
2020-07-05 04:35:16 +08:00
|
|
|
The :meth:`predict` method operates using the :func:`numpy.argmax`
|
|
|
|
|
function on the outputs of :meth:`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 :term:`classes_`.
|
|
|
|
|
|
2012-03-04 04:15:56 +08:00
|
|
|
References
|
|
|
|
|
----------
|
2011-12-22 02:29:01 +08:00
|
|
|
|
2015-12-03 07:16:40 +08:00
|
|
|
.. [1] https://en.wikipedia.org/wiki/Decision_tree_learning
|
2011-09-03 19:19:02 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
.. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification
|
|
|
|
|
and Regression Trees", Wadsworth, Belmont, CA, 1984.
|
2011-09-03 19:19:02 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
.. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical
|
|
|
|
|
Learning", Springer, 2009.
|
2011-09-03 19:19:02 +08:00
|
|
|
|
2011-12-28 00:44:04 +08:00
|
|
|
.. [4] L. Breiman, and A. Cutler, "Random Forests",
|
2018-10-05 05:06:14 +08:00
|
|
|
https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
|
2011-12-28 00:44:04 +08:00
|
|
|
|
2011-09-26 19:25:39 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
2011-09-04 02:54:12 +08:00
|
|
|
>>> from sklearn.datasets import load_iris
|
Main Commits - Major
--------------------
* ENH Reogranize classes/fn from grid_search into search.py
* ENH Reogranize classes/fn from cross_validation into split.py
* ENH Reogranize cls/fn from cross_validation/learning_curve into validate.py
* MAINT Merge _check_cv into check_cv inside the model_selection module
* MAINT Update all the imports to point to the model_selection module
* FIX use iter_cv to iterate throught the new style/old style cv objs
* TST Add tests for the new model_selection members
* ENH Wrap the old-style cv obj/iterables instead of using iter_cv
* ENH Use scipy's binomial coefficient function comb for calucation of nCk
* ENH Few enhancements to the split module
* ENH Improve check_cv input validation and docstring
* MAINT _get_test_folds(X, y, labels) --> _get_test_folds(labels)
* TST if 1d arrays for X introduce any errors
* ENH use 1d X arrays for all tests;
* ENH X_10 --> X (global var)
Minor
-----
* ENH _PartitionIterator --> _BaseCrossValidator;
* ENH CVIterator --> CVIterableWrapper
* TST Import the old SKF locally
* FIX/TST Clean up the split module's tests.
* DOC Improve documentation of the cv parameter
* COSMIT consistently hyphenate cross-validation/cross-validator
* TST Calculate n_samples from X
* COSMIT Use separate lines for each import.
* COSMIT cross_validation_generator --> cross_validator
Commits merged manually
-----------------------
* FIX Document the random_state attribute in RandomSearchCV
* MAINT Use check_cv instead of _check_cv
* ENH refactor OVO decision function, use it in SVC for sklearn-like
decision_function shape
* FIX avoid memory cost when sampling from large parameter grids
ENH Major to Minor incremental enhancements to the model_selection
Squashed commit messages - (For reference)
Major
-----
* ENH p --> n_labels
* FIX *ShuffleSplit: all float/invalid type errors at init and int error at split
* FIX make PredefinedSplit accept test_folds in constructor; Cleanup docstrings
* ENH+TST KFold: make rng to be generated at every split call for reproducibility
* FIX/MAINT KFold: make shuffle a public attr
* FIX Make CVIterableWrapper private.
* FIX reuse len_cv instead of recalculating it
* FIX Prevent adding *SearchCV estimators from the old grid_search module
* re-FIX In all_estimators: the sorting to use only the 1st item (name)
To avoid collision between the old and the new GridSearch classes.
* FIX test_validate.py: Use 2D X (1D X is being detected as a single sample)
* MAINT validate.py --> validation.py
* MAINT make the submodules private
* MAINT Support old cv/gs/lc until 0.19
* FIX/MAINT n_splits --> get_n_splits
* FIX/TST test_logistic.py/test_ovr_multinomial_iris:
pass predefined folds as an iterable
* MAINT expose BaseCrossValidator
* Update the model_selection module with changes from master
- From #5161
- - MAINT remove redundant p variable
- - Add check for sparse prediction in cross_val_predict
- From #5201 - DOC improve random_state param doc
- From #5190 - LabelKFold and test
- From #4583 - LabelShuffleSplit and tests
- From #5300 - shuffle the `labels` not the `indxs` in LabelKFold + tests
- From #5378 - Make the GridSearchCV docs more accurate.
- From #5458 - Remove shuffle from LabelKFold
- From #5466(#4270) - Gaussian Process by Jan Metzen
- From #4826 - Move custom error / warnings into sklearn.exception
Minor
-----
* ENH Make the KFold shuffling test stronger
* FIX/DOC Use the higher level model_selection module as ref
* DOC in check_cv "y : array-like, optional"
* DOC a supervised learning problem --> supervised learning problems
* DOC cross-validators --> cross-validation strategies
* DOC Correct Olivier Grisel's name ;)
* MINOR/FIX cv_indices --> kfold
* FIX/DOC Align the 'See also' section of the new KFold, LeaveOneOut
* TST/FIX imports on separate lines
* FIX use __class__ instead of classmethod
* TST/FIX import directly from model_selection
* COSMIT Relocate the random_state documentation
* COSMIT remove pass
* MAINT Remove deprecation warnings from old tests
* FIX correct import at test_split
* FIX/MAINT Move P_sparse, X, y defns to top; rm unused W_sparse, X_sparse
* FIX random state to avoid doctest failure
* TST n_splits and split wrapping of _CVIterableWrapper
* FIX/MAINT Use multilabel indicator matrix directly
* TST/DOC clarify why we conflate classes 0 and 1
* DOC add comment that this was taken from BaseEstimator
* FIX use of labels is not needed in stratified k fold
* Fix cross_validation reference
* Fix the labels param doc
FIX/DOC/MAINT Addressing the review comments by Arnaud and Andy
COSMIT Sort the members alphabetically
COSMIT len_cv --> n_splits
COSMIT Merge 2 if; FIX Use kwargs
DOC Add my name to the authors :D
DOC make labels parameter consistent
FIX Remove hack for boolean indices; + COSMIT idx --> indices; DOC Add Returns
COSMIT preds --> predictions
DOC Add Returns and neatly arrange X, y, labels
FIX idx(s)/ind(s)--> indice(s)
COSMIT Merge if and else to elif
COSMIT n --> n_samples
COSMIT Use bincount only once
COSMIT cls --> class_i / class_i (ith class indices) -->
perm_indices_class_i
FIX/ENH/TST Addressing the final reviews
COSMIT c --> count
FIX/TST make check_cv raise ValueError for string cv value
TST nested cv (gs inside cross_val_score) works for diff cvs
FIX/ENH Raise ValueError when labels is None for label based cvs;
TST if labels is being passed correctly to the cv and that the
ValueError is being propagated to the cross_val_score/predict and grid
search
FIX pass labels to cross_val_score
FIX use make_classification
DOC Add Returns; COSMIT Remove scaffolding
TST add a test to check the _build_repr helper
REVERT the old GS/RS should also be tested by the common tests.
ENH Add a tuple of all/label based CVS
FIX raise VE even at get_n_splits if labels is None
FIX Fabian's comments
PEP8
2015-06-05 03:45:10 +08:00
|
|
|
>>> from sklearn.model_selection import cross_val_score
|
2011-11-24 05:31:17 +08:00
|
|
|
>>> from sklearn.tree import DecisionTreeClassifier
|
2011-09-04 21:45:15 +08:00
|
|
|
>>> clf = DecisionTreeClassifier(random_state=0)
|
|
|
|
|
>>> iris = load_iris()
|
|
|
|
|
>>> cross_val_score(clf, iris.data, iris.target, cv=10)
|
2011-09-26 17:05:39 +08:00
|
|
|
... # doctest: +SKIP
|
2011-08-11 19:49:38 +08:00
|
|
|
...
|
2011-09-04 21:45:15 +08:00
|
|
|
array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,
|
|
|
|
|
0.93..., 0.93..., 1. , 0.93..., 1. ])
|
2011-04-02 05:28:20 +08:00
|
|
|
"""
|
2021-06-18 02:21:09 +08:00
|
|
|
|
2020-04-22 21:20:57 +08:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
2012-11-26 21:57:51 +08:00
|
|
|
criterion="gini",
|
2013-07-04 23:19:45 +08:00
|
|
|
splitter="best",
|
2012-11-26 21:57:51 +08:00
|
|
|
max_depth=None,
|
2013-01-07 03:05:50 +08:00
|
|
|
min_samples_split=2,
|
2018-09-08 22:43:21 +08:00
|
|
|
min_samples_leaf=1,
|
|
|
|
|
min_weight_fraction_leaf=0.0,
|
2012-11-26 21:57:51 +08:00
|
|
|
max_features=None,
|
2013-07-11 15:25:45 +08:00
|
|
|
random_state=None,
|
2014-12-23 08:50:58 +08:00
|
|
|
max_leaf_nodes=None,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease=0.0,
|
2015-09-11 16:39:21 +08:00
|
|
|
class_weight=None,
|
2019-08-20 21:02:45 +08:00
|
|
|
ccp_alpha=0.0,
|
|
|
|
|
):
|
2019-01-11 05:27:06 +08:00
|
|
|
super().__init__(
|
2014-01-16 20:44:43 +08:00
|
|
|
criterion=criterion,
|
|
|
|
|
splitter=splitter,
|
|
|
|
|
max_depth=max_depth,
|
|
|
|
|
min_samples_split=min_samples_split,
|
|
|
|
|
min_samples_leaf=min_samples_leaf,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf=min_weight_fraction_leaf,
|
2014-01-16 20:44:43 +08:00
|
|
|
max_features=max_features,
|
|
|
|
|
max_leaf_nodes=max_leaf_nodes,
|
2014-12-23 08:50:58 +08:00
|
|
|
class_weight=class_weight,
|
2015-09-11 16:39:21 +08:00
|
|
|
random_state=random_state,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease=min_impurity_decrease,
|
2019-08-20 21:02:45 +08:00
|
|
|
ccp_alpha=ccp_alpha,
|
|
|
|
|
)
|
2014-01-16 20:44:43 +08:00
|
|
|
|
2021-11-08 15:08:43 +08:00
|
|
|
def fit(self, X, y, sample_weight=None, check_input=True):
|
2016-11-10 02:32:22 +08:00
|
|
|
"""Build a decision tree classifier from the training set (X, y).
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
2016-11-10 02:32:22 +08:00
|
|
|
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``.
|
|
|
|
|
|
2019-10-03 08:54:32 +08:00
|
|
|
y : array-like of shape (n_samples,) or (n_samples, n_outputs)
|
2016-11-10 02:32:22 +08:00
|
|
|
The target values (class labels) as integers or strings.
|
|
|
|
|
|
2019-10-03 08:54:32 +08:00
|
|
|
sample_weight : array-like of shape (n_samples,), default=None
|
2016-11-10 02:32:22 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
check_input : bool, default=True
|
2016-11-10 02:32:22 +08:00
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
2019-12-14 06:10:17 +08:00
|
|
|
self : DecisionTreeClassifier
|
2019-11-06 06:36:57 +08:00
|
|
|
Fitted estimator.
|
2016-11-10 02:32:22 +08:00
|
|
|
"""
|
|
|
|
|
|
2019-01-11 05:27:06 +08:00
|
|
|
super().fit(
|
2016-11-10 02:32:22 +08:00
|
|
|
X,
|
|
|
|
|
y,
|
|
|
|
|
sample_weight=sample_weight,
|
|
|
|
|
check_input=check_input,
|
|
|
|
|
)
|
|
|
|
|
return self
|
|
|
|
|
|
2015-04-14 07:30:02 +08:00
|
|
|
def predict_proba(self, X, check_input=True):
|
2011-09-26 20:09:03 +08:00
|
|
|
"""Predict class probabilities of the input samples X.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2015-02-17 05:48:35 +08:00
|
|
|
The predicted class probability is the fraction of samples of the same
|
|
|
|
|
class in a leaf.
|
|
|
|
|
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
2014-04-04 04:28:08 +08:00
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
check_input : bool, default=True
|
|
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
2019-12-14 06:10:17 +08:00
|
|
|
proba : ndarray of shape (n_samples, n_classes) or list of n_outputs \
|
|
|
|
|
such arrays if n_outputs > 1
|
2014-02-17 18:47:51 +08:00
|
|
|
The class probabilities of the input samples. The order of the
|
2019-09-05 17:37:05 +08:00
|
|
|
classes corresponds to that in the attribute :term:`classes_`.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
"""
|
2019-08-14 04:09:07 +08:00
|
|
|
check_is_fitted(self)
|
2015-04-16 16:34:33 +08:00
|
|
|
X = self._validate_X_predict(X, check_input)
|
2012-12-05 05:10:09 +08:00
|
|
|
proba = self.tree_.predict(X)
|
2012-06-28 16:09:21 +08:00
|
|
|
|
2012-12-04 21:25:14 +08:00
|
|
|
if self.n_outputs_ == 1:
|
2013-07-16 17:00:53 +08:00
|
|
|
proba = proba[:, : self.n_classes_]
|
2012-12-05 05:10:09 +08:00
|
|
|
normalizer = proba.sum(axis=1)[:, np.newaxis]
|
2012-06-28 16:09:21 +08:00
|
|
|
normalizer[normalizer == 0.0] = 1.0
|
2012-12-05 05:10:09 +08:00
|
|
|
proba /= normalizer
|
2012-06-28 16:09:21 +08:00
|
|
|
|
2012-12-05 05:10:09 +08:00
|
|
|
return proba
|
2012-06-28 16:09:21 +08:00
|
|
|
|
|
|
|
|
else:
|
2012-12-05 05:10:09 +08:00
|
|
|
all_proba = []
|
2012-12-04 21:25:14 +08:00
|
|
|
|
2014-04-04 04:28:08 +08:00
|
|
|
for k in range(self.n_outputs_):
|
2012-12-05 05:10:09 +08:00
|
|
|
proba_k = proba[:, k, : self.n_classes_[k]]
|
|
|
|
|
normalizer = proba_k.sum(axis=1)[:, np.newaxis]
|
2012-12-04 21:25:14 +08:00
|
|
|
normalizer[normalizer == 0.0] = 1.0
|
2012-12-05 05:10:09 +08:00
|
|
|
proba_k /= normalizer
|
|
|
|
|
all_proba.append(proba_k)
|
2012-12-04 21:25:14 +08:00
|
|
|
|
2012-12-05 05:10:09 +08:00
|
|
|
return all_proba
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
|
|
|
|
def predict_log_proba(self, X):
|
2011-09-26 20:09:03 +08:00
|
|
|
"""Predict class log-probabilities of the input samples X.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
2014-04-04 04:28:08 +08:00
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
2019-12-14 06:10:17 +08:00
|
|
|
proba : ndarray of shape (n_samples, n_classes) or list of n_outputs \
|
|
|
|
|
such arrays if n_outputs > 1
|
2014-02-17 18:47:51 +08:00
|
|
|
The class log-probabilities of the input samples. The order of the
|
2019-09-05 17:37:05 +08:00
|
|
|
classes corresponds to that in the attribute :term:`classes_`.
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
"""
|
2012-07-02 17:51:50 +08:00
|
|
|
proba = self.predict_proba(X)
|
|
|
|
|
|
|
|
|
|
if self.n_outputs_ == 1:
|
|
|
|
|
return np.log(proba)
|
|
|
|
|
|
|
|
|
|
else:
|
2014-04-04 04:28:08 +08:00
|
|
|
for k in range(self.n_outputs_):
|
2012-07-02 17:51:50 +08:00
|
|
|
proba[k] = np.log(proba[k])
|
|
|
|
|
|
|
|
|
|
return proba
|
|
|
|
|
|
2021-06-16 02:36:13 +08:00
|
|
|
@deprecated( # type: ignore
|
2021-06-29 02:09:30 +08:00
|
|
|
"The attribute `n_features_` is deprecated in 1.0 and will be removed "
|
|
|
|
|
"in 1.2. Use `n_features_in_` instead."
|
2021-06-16 02:36:13 +08:00
|
|
|
)
|
|
|
|
|
@property
|
|
|
|
|
def n_features_(self):
|
|
|
|
|
return self.n_features_in_
|
|
|
|
|
|
2021-08-06 16:57:55 +08:00
|
|
|
def _more_tags(self):
|
|
|
|
|
return {"multilabel": True}
|
|
|
|
|
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
|
2019-09-05 16:13:30 +08:00
|
|
|
class DecisionTreeRegressor(RegressorMixin, BaseDecisionTree):
|
2013-12-03 03:13:57 +08:00
|
|
|
"""A decision tree regressor.
|
2011-08-09 20:29:39 +08:00
|
|
|
|
2015-06-03 12:24:04 +08:00
|
|
|
Read more in the :ref:`User Guide <tree>`.
|
|
|
|
|
|
2011-07-29 20:57:39 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2021-10-15 00:07:10 +08:00
|
|
|
criterion : {"squared_error", "friedman_mse", "absolute_error", \
|
|
|
|
|
"poisson"}, default="squared_error"
|
2016-07-25 14:44:59 +08:00
|
|
|
The function to measure the quality of a split. Supported criteria
|
2021-03-19 22:21:34 +08:00
|
|
|
are "squared_error" 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
|
2021-05-11 04:10:21 +08:00
|
|
|
splits, "absolute_error" 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.
|
2011-07-29 20:57:39 +08:00
|
|
|
|
2016-07-29 01:50:52 +08:00
|
|
|
.. versionadded:: 0.18
|
|
|
|
|
Mean Absolute Error (MAE) criterion.
|
|
|
|
|
|
2020-11-02 23:32:29 +08:00
|
|
|
.. versionadded:: 0.24
|
|
|
|
|
Poisson deviance criterion.
|
|
|
|
|
|
2021-03-19 22:21:34 +08:00
|
|
|
.. deprecated:: 1.0
|
|
|
|
|
Criterion "mse" was deprecated in v1.0 and will be removed in
|
|
|
|
|
version 1.2. Use `criterion="squared_error"` which is equivalent.
|
|
|
|
|
|
2021-05-11 04:10:21 +08:00
|
|
|
.. deprecated:: 1.0
|
|
|
|
|
Criterion "mae" was deprecated in v1.0 and will be removed in
|
|
|
|
|
version 1.2. Use `criterion="absolute_error"` which is equivalent.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
splitter : {"best", "random"}, default="best"
|
2013-08-23 07:24:07 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_depth : int, default=None
|
2011-11-02 04:42:57 +08:00
|
|
|
The maximum depth of the tree. If None, then nodes are expanded until
|
2012-02-16 18:29:52 +08:00
|
|
|
all leaves are pure or until all leaves contain less than
|
|
|
|
|
min_samples_split samples.
|
2011-08-09 20:29:39 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_samples_split : int or float, default=2
|
2014-07-10 14:48:20 +08:00
|
|
|
The minimum number of samples required to split an internal node:
|
|
|
|
|
|
2018-09-08 22:43:21 +08:00
|
|
|
- If int, then consider `min_samples_split` as the minimum number.
|
|
|
|
|
- If float, then `min_samples_split` is a fraction and
|
2014-07-10 14:48:20 +08:00
|
|
|
`ceil(min_samples_split * n_samples)` are the minimum
|
|
|
|
|
number of samples for each split.
|
|
|
|
|
|
2016-09-28 04:19:47 +08:00
|
|
|
.. versionchanged:: 0.18
|
2018-02-18 07:46:05 +08:00
|
|
|
Added float values for fractions.
|
2016-09-28 04:19:47 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_samples_leaf : int or float, default=1
|
2018-09-08 22:43:21 +08:00
|
|
|
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
|
2014-07-10 14:48:20 +08:00
|
|
|
`ceil(min_samples_leaf * n_samples)` are the minimum
|
|
|
|
|
number of samples for each node.
|
2012-02-14 18:09:40 +08:00
|
|
|
|
2016-09-28 04:19:47 +08:00
|
|
|
.. versionchanged:: 0.18
|
2018-02-18 07:46:05 +08:00
|
|
|
Added float values for fractions.
|
2016-09-28 04:19:47 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_weight_fraction_leaf : float, default=0.0
|
2016-09-28 12:48:23 +08:00
|
|
|
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.
|
2014-05-27 18:39:54 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_features : int, float or {"auto", "sqrt", "log2"}, default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
The number of features to consider when looking for the best split:
|
|
|
|
|
|
|
|
|
|
- If int, then consider `max_features` features at each split.
|
2018-02-18 07:46:05 +08:00
|
|
|
- If float, then `max_features` is a fraction and
|
2017-07-12 00:42:10 +08:00
|
|
|
`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`.
|
|
|
|
|
|
2022-03-24 00:59:23 +08:00
|
|
|
.. deprecated:: 1.1
|
|
|
|
|
The `"auto"` option was deprecated in 1.1 and will be removed
|
|
|
|
|
in 1.3.
|
|
|
|
|
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
2013-11-02 07:04:23 +08:00
|
|
|
|
2020-08-31 19:58:23 +08:00
|
|
|
random_state : int, RandomState instance or None, default=None
|
2020-01-08 23:11:24 +08:00
|
|
|
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 :term:`Glossary <random_state>` for details.
|
2011-11-01 21:22:31 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_leaf_nodes : int, default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
2017-05-23 14:42:08 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_impurity_decrease : float, default=0.0
|
2017-04-04 00:38:53 +08:00
|
|
|
A node will be split if this split induces a decrease of the impurity
|
|
|
|
|
greater than or equal to this value.
|
2016-07-27 23:46:49 +08:00
|
|
|
|
2017-04-04 00:38:53 +08:00
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.19
|
2016-07-29 02:31:55 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
ccp_alpha : non-negative float, default=0.0
|
2019-08-20 21:02:45 +08:00
|
|
|
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
|
|
|
|
|
:ref:`minimal_cost_complexity_pruning` for details.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.22
|
|
|
|
|
|
2011-12-28 00:44:04 +08:00
|
|
|
Attributes
|
|
|
|
|
----------
|
2019-10-03 08:54:32 +08:00
|
|
|
feature_importances_ : ndarray of shape (n_features,)
|
2013-03-12 05:51:22 +08:00
|
|
|
The feature importances.
|
|
|
|
|
The higher, the more important the feature.
|
2013-01-19 22:45:09 +08:00
|
|
|
The importance of a feature is computed as the
|
2013-07-11 15:30:19 +08:00
|
|
|
(normalized) total reduction of the criterion brought
|
2013-03-12 05:51:22 +08:00
|
|
|
by that feature. It is also known as the Gini importance [4]_.
|
2011-12-28 00:44:04 +08:00
|
|
|
|
2020-02-05 22:20:20 +08:00
|
|
|
Warning: impurity-based feature importances can be misleading for
|
|
|
|
|
high cardinality features (many unique values). See
|
|
|
|
|
:func:`sklearn.inspection.permutation_importance` as an alternative.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_features_ : int
|
2015-05-12 21:00:27 +08:00
|
|
|
The inferred value of max_features.
|
|
|
|
|
|
|
|
|
|
n_features_ : int
|
|
|
|
|
The number of features when ``fit`` is performed.
|
|
|
|
|
|
2021-06-16 02:36:13 +08:00
|
|
|
.. deprecated:: 1.0
|
|
|
|
|
`n_features_` is deprecated in 1.0 and will be removed in
|
|
|
|
|
1.2. Use `n_features_in_` instead.
|
|
|
|
|
|
2021-06-09 22:58:03 +08:00
|
|
|
n_features_in_ : int
|
|
|
|
|
Number of features seen during :term:`fit`.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.24
|
|
|
|
|
|
2021-08-26 19:44:45 +08:00
|
|
|
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
|
|
|
|
Names of features seen during :term:`fit`. Defined only when `X`
|
|
|
|
|
has feature names that are all strings.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 1.0
|
|
|
|
|
|
2015-05-12 21:00:27 +08:00
|
|
|
n_outputs_ : int
|
|
|
|
|
The number of outputs when ``fit`` is performed.
|
|
|
|
|
|
2020-08-31 19:58:23 +08:00
|
|
|
tree_ : Tree instance
|
2018-06-11 07:00:55 +08:00
|
|
|
The underlying Tree object. Please refer to
|
|
|
|
|
``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and
|
|
|
|
|
:ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`
|
|
|
|
|
for basic usage of these attributes.
|
2015-05-12 21:00:27 +08:00
|
|
|
|
2019-11-06 06:36:57 +08:00
|
|
|
See Also
|
|
|
|
|
--------
|
|
|
|
|
DecisionTreeClassifier : A decision tree classifier.
|
|
|
|
|
|
2017-02-27 01:48:19 +08:00
|
|
|
Notes
|
|
|
|
|
-----
|
2017-04-09 23:16:19 +08:00
|
|
|
The default values for the parameters controlling the size of the trees
|
2018-09-08 22:43:21 +08:00
|
|
|
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
|
2017-04-09 23:16:19 +08:00
|
|
|
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.
|
|
|
|
|
|
2012-03-04 04:15:56 +08:00
|
|
|
References
|
|
|
|
|
----------
|
2011-12-22 02:29:01 +08:00
|
|
|
|
2015-12-03 07:16:40 +08:00
|
|
|
.. [1] https://en.wikipedia.org/wiki/Decision_tree_learning
|
2011-09-03 19:19:02 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
.. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification
|
|
|
|
|
and Regression Trees", Wadsworth, Belmont, CA, 1984.
|
2011-09-03 19:19:02 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
.. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical
|
|
|
|
|
Learning", Springer, 2009.
|
2011-09-03 19:19:02 +08:00
|
|
|
|
2011-12-28 00:44:04 +08:00
|
|
|
.. [4] L. Breiman, and A. Cutler, "Random Forests",
|
2018-10-05 05:06:14 +08:00
|
|
|
https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
|
2011-12-28 00:44:04 +08:00
|
|
|
|
2011-09-26 19:25:39 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
2020-04-14 16:42:15 +08:00
|
|
|
>>> from sklearn.datasets import load_diabetes
|
Main Commits - Major
--------------------
* ENH Reogranize classes/fn from grid_search into search.py
* ENH Reogranize classes/fn from cross_validation into split.py
* ENH Reogranize cls/fn from cross_validation/learning_curve into validate.py
* MAINT Merge _check_cv into check_cv inside the model_selection module
* MAINT Update all the imports to point to the model_selection module
* FIX use iter_cv to iterate throught the new style/old style cv objs
* TST Add tests for the new model_selection members
* ENH Wrap the old-style cv obj/iterables instead of using iter_cv
* ENH Use scipy's binomial coefficient function comb for calucation of nCk
* ENH Few enhancements to the split module
* ENH Improve check_cv input validation and docstring
* MAINT _get_test_folds(X, y, labels) --> _get_test_folds(labels)
* TST if 1d arrays for X introduce any errors
* ENH use 1d X arrays for all tests;
* ENH X_10 --> X (global var)
Minor
-----
* ENH _PartitionIterator --> _BaseCrossValidator;
* ENH CVIterator --> CVIterableWrapper
* TST Import the old SKF locally
* FIX/TST Clean up the split module's tests.
* DOC Improve documentation of the cv parameter
* COSMIT consistently hyphenate cross-validation/cross-validator
* TST Calculate n_samples from X
* COSMIT Use separate lines for each import.
* COSMIT cross_validation_generator --> cross_validator
Commits merged manually
-----------------------
* FIX Document the random_state attribute in RandomSearchCV
* MAINT Use check_cv instead of _check_cv
* ENH refactor OVO decision function, use it in SVC for sklearn-like
decision_function shape
* FIX avoid memory cost when sampling from large parameter grids
ENH Major to Minor incremental enhancements to the model_selection
Squashed commit messages - (For reference)
Major
-----
* ENH p --> n_labels
* FIX *ShuffleSplit: all float/invalid type errors at init and int error at split
* FIX make PredefinedSplit accept test_folds in constructor; Cleanup docstrings
* ENH+TST KFold: make rng to be generated at every split call for reproducibility
* FIX/MAINT KFold: make shuffle a public attr
* FIX Make CVIterableWrapper private.
* FIX reuse len_cv instead of recalculating it
* FIX Prevent adding *SearchCV estimators from the old grid_search module
* re-FIX In all_estimators: the sorting to use only the 1st item (name)
To avoid collision between the old and the new GridSearch classes.
* FIX test_validate.py: Use 2D X (1D X is being detected as a single sample)
* MAINT validate.py --> validation.py
* MAINT make the submodules private
* MAINT Support old cv/gs/lc until 0.19
* FIX/MAINT n_splits --> get_n_splits
* FIX/TST test_logistic.py/test_ovr_multinomial_iris:
pass predefined folds as an iterable
* MAINT expose BaseCrossValidator
* Update the model_selection module with changes from master
- From #5161
- - MAINT remove redundant p variable
- - Add check for sparse prediction in cross_val_predict
- From #5201 - DOC improve random_state param doc
- From #5190 - LabelKFold and test
- From #4583 - LabelShuffleSplit and tests
- From #5300 - shuffle the `labels` not the `indxs` in LabelKFold + tests
- From #5378 - Make the GridSearchCV docs more accurate.
- From #5458 - Remove shuffle from LabelKFold
- From #5466(#4270) - Gaussian Process by Jan Metzen
- From #4826 - Move custom error / warnings into sklearn.exception
Minor
-----
* ENH Make the KFold shuffling test stronger
* FIX/DOC Use the higher level model_selection module as ref
* DOC in check_cv "y : array-like, optional"
* DOC a supervised learning problem --> supervised learning problems
* DOC cross-validators --> cross-validation strategies
* DOC Correct Olivier Grisel's name ;)
* MINOR/FIX cv_indices --> kfold
* FIX/DOC Align the 'See also' section of the new KFold, LeaveOneOut
* TST/FIX imports on separate lines
* FIX use __class__ instead of classmethod
* TST/FIX import directly from model_selection
* COSMIT Relocate the random_state documentation
* COSMIT remove pass
* MAINT Remove deprecation warnings from old tests
* FIX correct import at test_split
* FIX/MAINT Move P_sparse, X, y defns to top; rm unused W_sparse, X_sparse
* FIX random state to avoid doctest failure
* TST n_splits and split wrapping of _CVIterableWrapper
* FIX/MAINT Use multilabel indicator matrix directly
* TST/DOC clarify why we conflate classes 0 and 1
* DOC add comment that this was taken from BaseEstimator
* FIX use of labels is not needed in stratified k fold
* Fix cross_validation reference
* Fix the labels param doc
FIX/DOC/MAINT Addressing the review comments by Arnaud and Andy
COSMIT Sort the members alphabetically
COSMIT len_cv --> n_splits
COSMIT Merge 2 if; FIX Use kwargs
DOC Add my name to the authors :D
DOC make labels parameter consistent
FIX Remove hack for boolean indices; + COSMIT idx --> indices; DOC Add Returns
COSMIT preds --> predictions
DOC Add Returns and neatly arrange X, y, labels
FIX idx(s)/ind(s)--> indice(s)
COSMIT Merge if and else to elif
COSMIT n --> n_samples
COSMIT Use bincount only once
COSMIT cls --> class_i / class_i (ith class indices) -->
perm_indices_class_i
FIX/ENH/TST Addressing the final reviews
COSMIT c --> count
FIX/TST make check_cv raise ValueError for string cv value
TST nested cv (gs inside cross_val_score) works for diff cvs
FIX/ENH Raise ValueError when labels is None for label based cvs;
TST if labels is being passed correctly to the cv and that the
ValueError is being propagated to the cross_val_score/predict and grid
search
FIX pass labels to cross_val_score
FIX use make_classification
DOC Add Returns; COSMIT Remove scaffolding
TST add a test to check the _build_repr helper
REVERT the old GS/RS should also be tested by the common tests.
ENH Add a tuple of all/label based CVS
FIX raise VE even at get_n_splits if labels is None
FIX Fabian's comments
PEP8
2015-06-05 03:45:10 +08:00
|
|
|
>>> from sklearn.model_selection import cross_val_score
|
2011-11-24 05:31:17 +08:00
|
|
|
>>> from sklearn.tree import DecisionTreeRegressor
|
2020-04-14 16:42:15 +08:00
|
|
|
>>> X, y = load_diabetes(return_X_y=True)
|
2011-09-04 21:45:15 +08:00
|
|
|
>>> regressor = DecisionTreeRegressor(random_state=0)
|
2019-08-20 10:08:23 +08:00
|
|
|
>>> cross_val_score(regressor, X, y, cv=10)
|
2011-09-25 23:37:03 +08:00
|
|
|
... # doctest: +SKIP
|
2011-08-11 19:49:38 +08:00
|
|
|
...
|
2020-04-14 16:42:15 +08:00
|
|
|
array([-0.39..., -0.46..., 0.02..., 0.06..., -0.50...,
|
|
|
|
|
0.16..., 0.11..., -0.73..., -0.30..., -0.00...])
|
Refactored decision trees and forests to support CART algorithm.
Notable changes:
1) Supports classification and regression
2) 3 classification criteria, 1 regression criterion
3) A new dataset is provided to test regression (Boston House Prices)
4) Weights are removed from the algorithm entirely. If the need for weights can be justified, I would welcome reintroducing them, but for the refactoring I left them out.
5) The subset of dimensions (F) to split on is fixed for the entire tree, not at each node. This is more in line with CART and RandomForests.
6) A max_depth parameter is offered to limit the size of the constructed trees.
7) Randomisation is fixed with python's random module, but can be seeded.
8) For classification, the number of classes must be provided when the tree is constructed. This is because the tree cannot necessarily infer the correct number of labels at the time of training if only a subset of the data is used for individual trees.
9) For classification, labels are not normalised internally. Labels must be provided to the algorithm in the range [0, ..., K)
10) For classification, the leaf nodes retain the distribution of classes. This means that it is possible to query the tree for the probability distribution of a test sample
2011-07-29 19:37:53 +08:00
|
|
|
"""
|
2021-06-18 02:21:09 +08:00
|
|
|
|
2020-04-22 21:20:57 +08:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
2021-03-19 22:21:34 +08:00
|
|
|
criterion="squared_error",
|
2013-07-04 23:19:45 +08:00
|
|
|
splitter="best",
|
2012-11-26 21:57:51 +08:00
|
|
|
max_depth=None,
|
2013-01-07 03:05:50 +08:00
|
|
|
min_samples_split=2,
|
2018-09-08 22:43:21 +08:00
|
|
|
min_samples_leaf=1,
|
|
|
|
|
min_weight_fraction_leaf=0.0,
|
2012-11-26 21:57:51 +08:00
|
|
|
max_features=None,
|
2013-07-11 15:25:45 +08:00
|
|
|
random_state=None,
|
2015-09-11 16:39:21 +08:00
|
|
|
max_leaf_nodes=None,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease=0.0,
|
2019-08-20 21:02:45 +08:00
|
|
|
ccp_alpha=0.0,
|
|
|
|
|
):
|
2019-01-11 05:27:06 +08:00
|
|
|
super().__init__(
|
2014-01-16 20:44:43 +08:00
|
|
|
criterion=criterion,
|
|
|
|
|
splitter=splitter,
|
|
|
|
|
max_depth=max_depth,
|
|
|
|
|
min_samples_split=min_samples_split,
|
|
|
|
|
min_samples_leaf=min_samples_leaf,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf=min_weight_fraction_leaf,
|
2014-01-16 20:44:43 +08:00
|
|
|
max_features=max_features,
|
|
|
|
|
max_leaf_nodes=max_leaf_nodes,
|
2015-09-11 16:39:21 +08:00
|
|
|
random_state=random_state,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease=min_impurity_decrease,
|
2019-08-20 21:02:45 +08:00
|
|
|
ccp_alpha=ccp_alpha,
|
|
|
|
|
)
|
2014-01-16 20:44:43 +08:00
|
|
|
|
2021-11-08 15:08:43 +08:00
|
|
|
def fit(self, X, y, sample_weight=None, check_input=True):
|
2016-11-10 02:32:22 +08:00
|
|
|
"""Build a decision tree regressor from the training set (X, y).
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
2016-11-10 02:32:22 +08:00
|
|
|
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``.
|
|
|
|
|
|
2019-10-03 08:54:32 +08:00
|
|
|
y : array-like of shape (n_samples,) or (n_samples, n_outputs)
|
2016-11-10 02:32:22 +08:00
|
|
|
The target values (real numbers). Use ``dtype=np.float64`` and
|
|
|
|
|
``order='C'`` for maximum efficiency.
|
|
|
|
|
|
2019-10-03 08:54:32 +08:00
|
|
|
sample_weight : array-like of shape (n_samples,), default=None
|
2016-11-10 02:32:22 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
check_input : bool, default=True
|
2016-11-10 02:32:22 +08:00
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
2019-12-14 06:10:17 +08:00
|
|
|
self : DecisionTreeRegressor
|
2019-11-06 06:36:57 +08:00
|
|
|
Fitted estimator.
|
2016-11-10 02:32:22 +08:00
|
|
|
"""
|
|
|
|
|
|
2019-01-11 05:27:06 +08:00
|
|
|
super().fit(
|
2016-11-10 02:32:22 +08:00
|
|
|
X,
|
|
|
|
|
y,
|
|
|
|
|
sample_weight=sample_weight,
|
|
|
|
|
check_input=check_input,
|
|
|
|
|
)
|
|
|
|
|
return self
|
|
|
|
|
|
2020-02-24 15:53:55 +08:00
|
|
|
def _compute_partial_dependence_recursion(self, grid, target_features):
|
|
|
|
|
"""Fast partial dependence computation.
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
grid : ndarray of shape (n_samples, n_target_features)
|
|
|
|
|
The grid points on which the partial dependence should be
|
|
|
|
|
evaluated.
|
|
|
|
|
target_features : ndarray of shape (n_target_features)
|
|
|
|
|
The set of target features for which the partial dependence
|
|
|
|
|
should be evaluated.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
averaged_predictions : ndarray of shape (n_samples,)
|
|
|
|
|
The value of the partial dependence function on each grid point.
|
|
|
|
|
"""
|
|
|
|
|
grid = np.asarray(grid, dtype=DTYPE, order="C")
|
|
|
|
|
averaged_predictions = np.zeros(
|
|
|
|
|
shape=grid.shape[0], dtype=np.float64, order="C"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
self.tree_.compute_partial_dependence(
|
|
|
|
|
grid, target_features, averaged_predictions
|
|
|
|
|
)
|
|
|
|
|
return averaged_predictions
|
|
|
|
|
|
2021-06-16 02:36:13 +08:00
|
|
|
@deprecated( # type: ignore
|
2021-06-29 02:09:30 +08:00
|
|
|
"The attribute `n_features_` is deprecated in 1.0 and will be removed "
|
|
|
|
|
"in 1.2. Use `n_features_in_` instead."
|
2021-06-16 02:36:13 +08:00
|
|
|
)
|
|
|
|
|
@property
|
|
|
|
|
def n_features_(self):
|
|
|
|
|
return self.n_features_in_
|
|
|
|
|
|
2011-11-12 23:20:43 +08:00
|
|
|
|
2011-11-12 18:29:38 +08:00
|
|
|
class ExtraTreeClassifier(DecisionTreeClassifier):
|
|
|
|
|
"""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.
|
|
|
|
|
|
2011-11-13 17:05:21 +08:00
|
|
|
Warning: Extra-trees should only be used within ensemble methods.
|
|
|
|
|
|
2015-06-03 12:24:04 +08:00
|
|
|
Read more in the :ref:`User Guide <tree>`.
|
|
|
|
|
|
2017-07-12 00:42:10 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
criterion : {"gini", "entropy"}, default="gini"
|
2017-07-12 00:42:10 +08:00
|
|
|
The function to measure the quality of a split. Supported criteria are
|
|
|
|
|
"gini" for the Gini impurity and "entropy" for the information gain.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
splitter : {"random", "best"}, default="random"
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_depth : int, default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_samples_split : int or float, default=2
|
2017-07-12 00:42:10 +08:00
|
|
|
The minimum number of samples required to split an internal node:
|
|
|
|
|
|
2018-09-08 22:43:21 +08:00
|
|
|
- If int, then consider `min_samples_split` as the minimum number.
|
|
|
|
|
- If float, then `min_samples_split` is a fraction and
|
2017-07-12 00:42:10 +08:00
|
|
|
`ceil(min_samples_split * n_samples)` are the minimum
|
|
|
|
|
number of samples for each split.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 0.18
|
2018-02-18 07:46:05 +08:00
|
|
|
Added float values for fractions.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_samples_leaf : int or float, default=1
|
2018-09-08 22:43:21 +08:00
|
|
|
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
|
2017-07-12 00:42:10 +08:00
|
|
|
`ceil(min_samples_leaf * n_samples)` are the minimum
|
|
|
|
|
number of samples for each node.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 0.18
|
2018-02-18 07:46:05 +08:00
|
|
|
Added float values for fractions.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_weight_fraction_leaf : float, default=0.0
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2022-03-24 00:59:23 +08:00
|
|
|
max_features : int, float, {"auto", "sqrt", "log2"} or None, default="sqrt"
|
2017-07-12 00:42:10 +08:00
|
|
|
The number of features to consider when looking for the best split:
|
|
|
|
|
|
|
|
|
|
- If int, then consider `max_features` features at each split.
|
2018-02-18 07:46:05 +08:00
|
|
|
- If float, then `max_features` is a fraction and
|
2017-07-12 00:42:10 +08:00
|
|
|
`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`.
|
|
|
|
|
|
2022-03-24 00:59:23 +08:00
|
|
|
.. versionchanged:: 1.1
|
|
|
|
|
The default of `max_features` changed from `"auto"` to `"sqrt"`.
|
|
|
|
|
|
|
|
|
|
.. deprecated:: 1.1
|
|
|
|
|
The `"auto"` option was deprecated in 1.1 and will be removed
|
|
|
|
|
in 1.3.
|
|
|
|
|
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2020-08-31 19:58:23 +08:00
|
|
|
random_state : int, RandomState instance or None, default=None
|
2020-01-08 23:11:24 +08:00
|
|
|
Used to pick randomly the `max_features` used at each split.
|
|
|
|
|
See :term:`Glossary <random_state>` for details.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_leaf_nodes : int, default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_impurity_decrease : float, default=0.0
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.19
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
class_weight : dict, list of dict or "balanced", default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
Weights associated with classes in the form ``{class_label: weight}``.
|
2019-12-14 06:10:17 +08:00
|
|
|
If None, all classes are supposed to have weight one. For
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
ccp_alpha : non-negative float, default=0.0
|
2019-08-20 21:02:45 +08:00
|
|
|
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
|
|
|
|
|
:ref:`minimal_cost_complexity_pruning` for details.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.22
|
|
|
|
|
|
2019-07-14 05:27:40 +08:00
|
|
|
Attributes
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
classes_ : ndarray of shape (n_classes,) or list of ndarray
|
2019-07-14 05:27:40 +08:00
|
|
|
The classes labels (single output problem),
|
|
|
|
|
or a list of arrays of class labels (multi-output problem).
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_features_ : int
|
2019-07-14 05:27:40 +08:00
|
|
|
The inferred value of max_features.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
n_classes_ : int or list of int
|
2019-07-14 05:27:40 +08:00
|
|
|
The number of classes (for single output problems),
|
|
|
|
|
or a list containing the number of classes for each
|
|
|
|
|
output (for multi-output problems).
|
|
|
|
|
|
2019-10-03 08:54:32 +08:00
|
|
|
feature_importances_ : ndarray of shape (n_features,)
|
2020-02-01 20:18:11 +08:00
|
|
|
The impurity-based feature importances.
|
|
|
|
|
The higher, the more important the feature.
|
|
|
|
|
The importance of a feature is computed as the (normalized)
|
|
|
|
|
total reduction of the criterion brought by that feature. It is also
|
|
|
|
|
known as the Gini importance.
|
2019-08-26 23:13:58 +08:00
|
|
|
|
2020-02-05 22:20:20 +08:00
|
|
|
Warning: impurity-based feature importances can be misleading for
|
|
|
|
|
high cardinality features (many unique values). See
|
|
|
|
|
:func:`sklearn.inspection.permutation_importance` as an alternative.
|
|
|
|
|
|
2019-07-14 05:27:40 +08:00
|
|
|
n_features_ : int
|
|
|
|
|
The number of features when ``fit`` is performed.
|
|
|
|
|
|
2021-06-16 02:36:13 +08:00
|
|
|
.. deprecated:: 1.0
|
|
|
|
|
`n_features_` is deprecated in 1.0 and will be removed in
|
|
|
|
|
1.2. Use `n_features_in_` instead.
|
|
|
|
|
|
2021-06-09 22:58:03 +08:00
|
|
|
n_features_in_ : int
|
|
|
|
|
Number of features seen during :term:`fit`.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.24
|
|
|
|
|
|
2021-08-26 19:44:45 +08:00
|
|
|
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
|
|
|
|
Names of features seen during :term:`fit`. Defined only when `X`
|
|
|
|
|
has feature names that are all strings.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 1.0
|
|
|
|
|
|
2019-07-14 05:27:40 +08:00
|
|
|
n_outputs_ : int
|
|
|
|
|
The number of outputs when ``fit`` is performed.
|
|
|
|
|
|
2020-08-31 19:58:23 +08:00
|
|
|
tree_ : Tree instance
|
2019-07-14 05:27:40 +08:00
|
|
|
The underlying Tree object. Please refer to
|
|
|
|
|
``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and
|
|
|
|
|
:ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`
|
|
|
|
|
for basic usage of these attributes.
|
|
|
|
|
|
2019-11-06 06:36:57 +08:00
|
|
|
See Also
|
2011-11-13 17:05:21 +08:00
|
|
|
--------
|
2019-12-14 06:10:17 +08:00
|
|
|
ExtraTreeRegressor : An extremely randomized tree regressor.
|
|
|
|
|
sklearn.ensemble.ExtraTreesClassifier : An extra-trees classifier.
|
|
|
|
|
sklearn.ensemble.ExtraTreesRegressor : An extra-trees regressor.
|
2021-07-27 15:09:57 +08:00
|
|
|
sklearn.ensemble.RandomForestClassifier : A random forest classifier.
|
|
|
|
|
sklearn.ensemble.RandomForestRegressor : A random forest regressor.
|
|
|
|
|
sklearn.ensemble.RandomTreesEmbedding : An ensemble of
|
|
|
|
|
totally random trees.
|
2011-11-13 17:05:21 +08:00
|
|
|
|
2017-04-09 23:16:19 +08:00
|
|
|
Notes
|
|
|
|
|
-----
|
|
|
|
|
The default values for the parameters controlling the size of the trees
|
2018-09-08 22:43:21 +08:00
|
|
|
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
|
2017-04-09 23:16:19 +08:00
|
|
|
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.
|
|
|
|
|
|
2012-03-04 04:15:56 +08:00
|
|
|
References
|
|
|
|
|
----------
|
2011-12-22 02:29:01 +08:00
|
|
|
|
2011-11-12 18:29:38 +08:00
|
|
|
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
|
|
|
|
|
Machine Learning, 63(1), 3-42, 2006.
|
2020-03-12 03:07:12 +08:00
|
|
|
|
|
|
|
|
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...
|
2011-11-12 18:29:38 +08:00
|
|
|
"""
|
2021-06-18 02:21:09 +08:00
|
|
|
|
2020-04-22 21:20:57 +08:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
2012-11-26 21:57:51 +08:00
|
|
|
criterion="gini",
|
2013-07-04 23:19:45 +08:00
|
|
|
splitter="random",
|
2012-11-26 21:57:51 +08:00
|
|
|
max_depth=None,
|
2013-01-07 03:05:50 +08:00
|
|
|
min_samples_split=2,
|
2018-09-08 22:43:21 +08:00
|
|
|
min_samples_leaf=1,
|
|
|
|
|
min_weight_fraction_leaf=0.0,
|
2022-03-24 00:59:23 +08:00
|
|
|
max_features="sqrt",
|
2013-07-11 15:25:45 +08:00
|
|
|
random_state=None,
|
2014-12-23 08:50:58 +08:00
|
|
|
max_leaf_nodes=None,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease=0.0,
|
2019-08-20 21:02:45 +08:00
|
|
|
class_weight=None,
|
|
|
|
|
ccp_alpha=0.0,
|
|
|
|
|
):
|
2019-01-11 05:27:06 +08:00
|
|
|
super().__init__(
|
2014-01-16 20:44:43 +08:00
|
|
|
criterion=criterion,
|
|
|
|
|
splitter=splitter,
|
|
|
|
|
max_depth=max_depth,
|
|
|
|
|
min_samples_split=min_samples_split,
|
|
|
|
|
min_samples_leaf=min_samples_leaf,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf=min_weight_fraction_leaf,
|
2014-01-16 20:44:43 +08:00
|
|
|
max_features=max_features,
|
|
|
|
|
max_leaf_nodes=max_leaf_nodes,
|
2014-12-23 08:50:58 +08:00
|
|
|
class_weight=class_weight,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease=min_impurity_decrease,
|
2019-08-20 21:02:45 +08:00
|
|
|
random_state=random_state,
|
|
|
|
|
ccp_alpha=ccp_alpha,
|
|
|
|
|
)
|
2014-01-16 20:44:43 +08:00
|
|
|
|
2011-11-12 23:20:43 +08:00
|
|
|
|
2011-11-12 18:29:38 +08:00
|
|
|
class ExtraTreeRegressor(DecisionTreeRegressor):
|
|
|
|
|
"""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.
|
|
|
|
|
|
2011-11-13 17:05:21 +08:00
|
|
|
Warning: Extra-trees should only be used within ensemble methods.
|
|
|
|
|
|
2015-06-03 12:24:04 +08:00
|
|
|
Read more in the :ref:`User Guide <tree>`.
|
|
|
|
|
|
2017-07-12 00:42:10 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2021-10-15 00:07:10 +08:00
|
|
|
criterion : {"squared_error", "friedman_mse"}, default="squared_error"
|
2017-07-12 00:42:10 +08:00
|
|
|
The function to measure the quality of a split. Supported criteria
|
2021-03-19 22:21:34 +08:00
|
|
|
are "squared_error" for the mean squared error, which is equal to
|
|
|
|
|
variance reduction as feature selection criterion and "mae" for the
|
|
|
|
|
mean absolute error.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
|
|
|
|
.. versionadded:: 0.18
|
|
|
|
|
Mean Absolute Error (MAE) criterion.
|
|
|
|
|
|
2020-11-02 23:32:29 +08:00
|
|
|
.. versionadded:: 0.24
|
|
|
|
|
Poisson deviance criterion.
|
|
|
|
|
|
2021-03-19 22:21:34 +08:00
|
|
|
.. deprecated:: 1.0
|
|
|
|
|
Criterion "mse" was deprecated in v1.0 and will be removed in
|
|
|
|
|
version 1.2. Use `criterion="squared_error"` which is equivalent.
|
|
|
|
|
|
2021-05-11 04:10:21 +08:00
|
|
|
.. deprecated:: 1.0
|
|
|
|
|
Criterion "mae" was deprecated in v1.0 and will be removed in
|
|
|
|
|
version 1.2. Use `criterion="absolute_error"` which is equivalent.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
splitter : {"random", "best"}, default="random"
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_depth : int, default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_samples_split : int or float, default=2
|
2017-07-12 00:42:10 +08:00
|
|
|
The minimum number of samples required to split an internal node:
|
|
|
|
|
|
2018-09-08 22:43:21 +08:00
|
|
|
- If int, then consider `min_samples_split` as the minimum number.
|
|
|
|
|
- If float, then `min_samples_split` is a fraction and
|
2017-07-12 00:42:10 +08:00
|
|
|
`ceil(min_samples_split * n_samples)` are the minimum
|
|
|
|
|
number of samples for each split.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 0.18
|
2018-02-18 07:46:05 +08:00
|
|
|
Added float values for fractions.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_samples_leaf : int or float, default=1
|
2018-09-08 22:43:21 +08:00
|
|
|
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
|
2017-07-12 00:42:10 +08:00
|
|
|
`ceil(min_samples_leaf * n_samples)` are the minimum
|
|
|
|
|
number of samples for each node.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 0.18
|
2018-02-18 07:46:05 +08:00
|
|
|
Added float values for fractions.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_weight_fraction_leaf : float, default=0.0
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2022-03-24 00:59:23 +08:00
|
|
|
max_features : int, float, {"auto", "sqrt", "log2"} or None, default=1.0
|
2017-07-12 00:42:10 +08:00
|
|
|
The number of features to consider when looking for the best split:
|
|
|
|
|
|
|
|
|
|
- If int, then consider `max_features` features at each split.
|
2018-02-18 07:46:05 +08:00
|
|
|
- If float, then `max_features` is a fraction and
|
2017-07-12 00:42:10 +08:00
|
|
|
`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`.
|
|
|
|
|
|
2022-03-24 00:59:23 +08:00
|
|
|
.. versionchanged:: 1.1
|
|
|
|
|
The default of `max_features` changed from `"auto"` to `1.0`.
|
|
|
|
|
|
|
|
|
|
.. deprecated:: 1.1
|
|
|
|
|
The `"auto"` option was deprecated in 1.1 and will be removed
|
|
|
|
|
in 1.3.
|
|
|
|
|
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2020-08-31 19:58:23 +08:00
|
|
|
random_state : int, RandomState instance or None, default=None
|
2020-01-08 23:11:24 +08:00
|
|
|
Used to pick randomly the `max_features` used at each split.
|
|
|
|
|
See :term:`Glossary <random_state>` for details.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
min_impurity_decrease : float, default=0.0
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.19
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
max_leaf_nodes : int, default=None
|
2017-07-12 00:42:10 +08:00
|
|
|
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.
|
|
|
|
|
|
2019-12-14 06:10:17 +08:00
|
|
|
ccp_alpha : non-negative float, default=0.0
|
2019-08-20 21:02:45 +08:00
|
|
|
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
|
|
|
|
|
:ref:`minimal_cost_complexity_pruning` for details.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.22
|
|
|
|
|
|
2019-07-14 05:27:40 +08:00
|
|
|
Attributes
|
|
|
|
|
----------
|
2019-12-14 06:10:17 +08:00
|
|
|
max_features_ : int
|
2019-07-14 05:27:40 +08:00
|
|
|
The inferred value of max_features.
|
|
|
|
|
|
|
|
|
|
n_features_ : int
|
|
|
|
|
The number of features when ``fit`` is performed.
|
|
|
|
|
|
2021-06-16 02:36:13 +08:00
|
|
|
.. deprecated:: 1.0
|
|
|
|
|
`n_features_` is deprecated in 1.0 and will be removed in
|
|
|
|
|
1.2. Use `n_features_in_` instead.
|
|
|
|
|
|
2021-06-09 22:58:03 +08:00
|
|
|
n_features_in_ : int
|
|
|
|
|
Number of features seen during :term:`fit`.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 0.24
|
|
|
|
|
|
2021-08-26 19:44:45 +08:00
|
|
|
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
|
|
|
|
Names of features seen during :term:`fit`. Defined only when `X`
|
|
|
|
|
has feature names that are all strings.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 1.0
|
|
|
|
|
|
2020-01-26 19:33:07 +08:00
|
|
|
feature_importances_ : ndarray of shape (n_features,)
|
2020-02-05 22:20:20 +08:00
|
|
|
Return impurity-based feature importances (the higher, the more
|
|
|
|
|
important the feature).
|
|
|
|
|
|
|
|
|
|
Warning: impurity-based feature importances can be misleading for
|
|
|
|
|
high cardinality features (many unique values). See
|
|
|
|
|
:func:`sklearn.inspection.permutation_importance` as an alternative.
|
2020-01-26 19:33:07 +08:00
|
|
|
|
2019-07-14 05:27:40 +08:00
|
|
|
n_outputs_ : int
|
|
|
|
|
The number of outputs when ``fit`` is performed.
|
|
|
|
|
|
2020-08-31 19:58:23 +08:00
|
|
|
tree_ : Tree instance
|
2019-07-14 05:27:40 +08:00
|
|
|
The underlying Tree object. Please refer to
|
|
|
|
|
``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and
|
|
|
|
|
:ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`
|
|
|
|
|
for basic usage of these attributes.
|
2017-07-12 00:42:10 +08:00
|
|
|
|
2019-11-06 06:36:57 +08:00
|
|
|
See Also
|
2011-11-13 17:05:21 +08:00
|
|
|
--------
|
2019-12-14 06:10:17 +08:00
|
|
|
ExtraTreeClassifier : An extremely randomized tree classifier.
|
|
|
|
|
sklearn.ensemble.ExtraTreesClassifier : An extra-trees classifier.
|
|
|
|
|
sklearn.ensemble.ExtraTreesRegressor : An extra-trees regressor.
|
2011-11-13 17:05:21 +08:00
|
|
|
|
2017-04-09 23:16:19 +08:00
|
|
|
Notes
|
|
|
|
|
-----
|
|
|
|
|
The default values for the parameters controlling the size of the trees
|
2018-09-08 22:43:21 +08:00
|
|
|
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
|
2017-04-09 23:16:19 +08:00
|
|
|
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.
|
|
|
|
|
|
2012-03-04 04:15:56 +08:00
|
|
|
References
|
|
|
|
|
----------
|
2011-12-22 02:29:01 +08:00
|
|
|
|
2011-11-12 18:29:38 +08:00
|
|
|
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
|
|
|
|
|
Machine Learning, 63(1), 3-42, 2006.
|
2019-11-19 12:24:09 +08:00
|
|
|
|
|
|
|
|
Examples
|
|
|
|
|
--------
|
2020-04-14 16:42:15 +08:00
|
|
|
>>> from sklearn.datasets import load_diabetes
|
2019-11-19 12:24:09 +08:00
|
|
|
>>> from sklearn.model_selection import train_test_split
|
|
|
|
|
>>> from sklearn.ensemble import BaggingRegressor
|
|
|
|
|
>>> from sklearn.tree import ExtraTreeRegressor
|
2020-04-14 16:42:15 +08:00
|
|
|
>>> X, y = load_diabetes(return_X_y=True)
|
2019-11-19 12:24:09 +08:00
|
|
|
>>> 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)
|
2020-04-14 16:42:15 +08:00
|
|
|
0.33...
|
2011-11-12 18:29:38 +08:00
|
|
|
"""
|
2021-06-18 02:21:09 +08:00
|
|
|
|
2020-04-22 21:20:57 +08:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
2021-03-19 22:21:34 +08:00
|
|
|
criterion="squared_error",
|
2013-07-04 23:19:45 +08:00
|
|
|
splitter="random",
|
2012-11-26 21:57:51 +08:00
|
|
|
max_depth=None,
|
2013-01-07 03:05:50 +08:00
|
|
|
min_samples_split=2,
|
2018-09-08 22:43:21 +08:00
|
|
|
min_samples_leaf=1,
|
|
|
|
|
min_weight_fraction_leaf=0.0,
|
2022-03-24 00:59:23 +08:00
|
|
|
max_features=1.0,
|
2013-07-11 15:25:45 +08:00
|
|
|
random_state=None,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease=0.0,
|
2019-08-20 21:02:45 +08:00
|
|
|
max_leaf_nodes=None,
|
|
|
|
|
ccp_alpha=0.0,
|
|
|
|
|
):
|
2019-01-11 05:27:06 +08:00
|
|
|
super().__init__(
|
2014-01-16 20:44:43 +08:00
|
|
|
criterion=criterion,
|
|
|
|
|
splitter=splitter,
|
|
|
|
|
max_depth=max_depth,
|
|
|
|
|
min_samples_split=min_samples_split,
|
|
|
|
|
min_samples_leaf=min_samples_leaf,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf=min_weight_fraction_leaf,
|
2014-01-16 20:44:43 +08:00
|
|
|
max_features=max_features,
|
|
|
|
|
max_leaf_nodes=max_leaf_nodes,
|
2017-04-04 00:38:53 +08:00
|
|
|
min_impurity_decrease=min_impurity_decrease,
|
2019-08-20 21:02:45 +08:00
|
|
|
random_state=random_state,
|
|
|
|
|
ccp_alpha=ccp_alpha,
|
|
|
|
|
)
|