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>
|
|
|
|
|
#
|
2013-07-04 23:19:45 +08:00
|
|
|
# Licence: BSD 3 clause
|
2011-02-12 20:58:01 +08:00
|
|
|
|
|
|
|
|
from __future__ import division
|
2013-02-05 23:19:32 +08:00
|
|
|
|
2014-04-04 04:28:08 +08:00
|
|
|
|
2013-02-26 15:26:35 +08:00
|
|
|
import numbers
|
2015-09-11 16:39:21 +08:00
|
|
|
from abc import ABCMeta
|
|
|
|
|
from abc import abstractmethod
|
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
|
|
|
|
|
from ..base import RegressorMixin
|
2013-01-17 01:16:21 +08:00
|
|
|
from ..externals import six
|
2013-05-06 18:36:16 +08:00
|
|
|
from ..feature_selection.from_model import _LearntSelectorMixin
|
2015-10-18 06:54:58 +08:00
|
|
|
from ..utils import check_array, check_X_y
|
2015-09-11 16:39:21 +08:00
|
|
|
from ..utils import check_random_state
|
|
|
|
|
from ..utils import compute_sample_weight
|
2015-08-04 20:57:58 +08:00
|
|
|
from ..utils.multiclass import check_classification_targets
|
2015-06-06 02:45:45 +08:00
|
|
|
from ..exceptions import NotFittedError
|
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
|
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
|
|
|
|
2015-09-09 03:07:30 +08:00
|
|
|
CRITERIA_CLF = {"gini": _criterion.Gini, "entropy": _criterion.Entropy}
|
|
|
|
|
CRITERIA_REG = {"mse": _criterion.MSE, "friedman_mse": _criterion.FriedmanMSE}
|
2011-09-04 16:54:21 +08:00
|
|
|
|
2015-09-09 03:07:30 +08:00
|
|
|
DENSE_SPLITTERS = {"best": _splitter.BestSplitter,
|
|
|
|
|
"random": _splitter.RandomSplitter}
|
2014-04-04 04:28:08 +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
|
|
|
|
2013-05-02 21:46:25 +08:00
|
|
|
class BaseDecisionTree(six.with_metaclass(ABCMeta, BaseEstimator,
|
2013-05-06 18:36:16 +08:00
|
|
|
_LearntSelectorMixin)):
|
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
|
2012-11-26 21:57:51 +08:00
|
|
|
def __init__(self,
|
|
|
|
|
criterion,
|
2013-07-04 23:19:45 +08:00
|
|
|
splitter,
|
2012-11-26 21:57:51 +08:00
|
|
|
max_depth,
|
|
|
|
|
min_samples_split,
|
|
|
|
|
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,
|
2015-09-11 16:39:21 +08:00
|
|
|
class_weight=None,
|
|
|
|
|
presort=False):
|
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
|
|
|
|
|
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
|
2012-08-27 21:39:57 +08:00
|
|
|
self.random_state = random_state
|
2013-11-03 15:40:24 +08:00
|
|
|
self.max_leaf_nodes = max_leaf_nodes
|
2014-12-23 08:50:58 +08:00
|
|
|
self.class_weight = class_weight
|
2015-09-11 16:39:21 +08:00
|
|
|
self.presort = presort
|
2011-09-26 00:57:49 +08:00
|
|
|
|
2011-11-22 03:06:25 +08:00
|
|
|
self.n_features_ = None
|
2012-06-28 16:09:21 +08:00
|
|
|
self.n_outputs_ = None
|
2011-11-22 03:06:25 +08:00
|
|
|
self.classes_ = None
|
|
|
|
|
self.n_classes_ = None
|
2011-02-12 20:58:01 +08:00
|
|
|
|
2011-11-22 03:06:25 +08:00
|
|
|
self.tree_ = None
|
2013-09-12 19:57:47 +08:00
|
|
|
self.max_features_ = None
|
2011-11-02 22:13:01 +08:00
|
|
|
|
2015-10-20 19:15:24 +08:00
|
|
|
def fit(self, X, y, sample_weight=None, check_input=True,
|
2015-09-11 16:39:21 +08:00
|
|
|
X_idx_sorted=None):
|
2011-09-26 19:25:39 +08:00
|
|
|
"""Build a decision tree from the training set (X, y).
|
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
|
|
|
|
|
----------
|
2014-04-04 04:28:08 +08:00
|
|
|
X : array-like or sparse matrix, 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``.
|
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
|
|
|
y : array-like, shape = [n_samples] or [n_samples, n_outputs]
|
2014-03-21 17:54:20 +08:00
|
|
|
The target values (class labels in classification, real numbers in
|
|
|
|
|
regression). In the regression case, use ``dtype=np.float64`` and
|
|
|
|
|
``order='C'`` for maximum efficiency.
|
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-12-23 22:31:22 +08:00
|
|
|
sample_weight : array-like, shape = [n_samples] or None
|
2013-01-07 15:10:11 +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. In the case of
|
|
|
|
|
classification, splits are also ignored if they would result in any
|
|
|
|
|
single class carrying a negative weight in either child node.
|
2012-12-23 20:13:21 +08:00
|
|
|
|
2013-01-17 19:50:48 +08:00
|
|
|
check_input : boolean, (default=True)
|
2012-11-22 18:05:08 +08:00
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
|
|
|
|
|
2015-09-11 16:39:21 +08:00
|
|
|
X_idx_sorted : array-like, shape = [n_samples, n_features], optional
|
|
|
|
|
The indexes of the sorted training input samples. If many tree
|
|
|
|
|
are grown on the same dataset, this allows the ordering to be
|
|
|
|
|
cached between trees. If None, the data will be sorted here.
|
|
|
|
|
Don't use this parameter unless you know what to do.
|
|
|
|
|
|
2011-12-20 20:47:16 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
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
|
|
|
self : object
|
|
|
|
|
Returns self.
|
2011-08-09 20:29:39 +08:00
|
|
|
"""
|
2015-09-11 16:39:21 +08:00
|
|
|
|
2013-07-19 15:53:29 +08:00
|
|
|
random_state = check_random_state(self.random_state)
|
2012-11-02 00:23:07 +08:00
|
|
|
if check_input:
|
2015-10-19 04:17:15 +08:00
|
|
|
X = check_array(X, dtype=DTYPE, accept_sparse="csc")
|
2015-10-19 06:39:19 +08:00
|
|
|
y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)
|
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
|
|
|
|
2013-07-19 15:53:29 +08:00
|
|
|
# Determine output settings
|
2011-11-22 03:06:25 +08:00
|
|
|
n_samples, self.n_features_ = X.shape
|
2011-11-04 15:20:10 +08:00
|
|
|
is_classification = isinstance(self, ClassifierMixin)
|
|
|
|
|
|
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
|
|
|
|
2015-06-24 23:22:01 +08:00
|
|
|
y_store_unique_indices = np.zeros(y.shape, dtype=np.int)
|
2014-04-04 04:28:08 +08:00
|
|
|
for k in range(self.n_outputs_):
|
2015-06-24 23:22:01 +08:00
|
|
|
classes_k, y_store_unique_indices[:, 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])
|
2015-06-24 23:22:01 +08:00
|
|
|
y = y_store_unique_indices
|
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
|
|
|
|
2011-11-01 21:22:31 +08:00
|
|
|
else:
|
2012-06-28 16:09:21 +08:00
|
|
|
self.classes_ = [None] * self.n_outputs_
|
|
|
|
|
self.n_classes_ = [1] * self.n_outputs_
|
2011-09-01 21:05:15 +08:00
|
|
|
|
2013-07-07 16:13:09 +08:00
|
|
|
self.n_classes_ = np.array(self.n_classes_, dtype=np.intp)
|
|
|
|
|
|
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
|
2014-02-01 22:19:58 +08:00
|
|
|
max_depth = ((2 ** 31) - 1 if self.max_depth is None
|
|
|
|
|
else self.max_depth)
|
|
|
|
|
max_leaf_nodes = (-1 if self.max_leaf_nodes is None
|
|
|
|
|
else self.max_leaf_nodes)
|
2012-01-03 17:11:52 +08:00
|
|
|
|
2013-01-17 01:16:21 +08:00
|
|
|
if isinstance(self.max_features, six.string_types):
|
2012-01-03 17:11:52 +08:00
|
|
|
if self.max_features == "auto":
|
|
|
|
|
if is_classification:
|
|
|
|
|
max_features = max(1, int(np.sqrt(self.n_features_)))
|
|
|
|
|
else:
|
|
|
|
|
max_features = self.n_features_
|
|
|
|
|
elif self.max_features == "sqrt":
|
|
|
|
|
max_features = max(1, int(np.sqrt(self.n_features_)))
|
|
|
|
|
elif self.max_features == "log2":
|
|
|
|
|
max_features = max(1, int(np.log2(self.n_features_)))
|
|
|
|
|
else:
|
2012-01-04 07:30:28 +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:
|
|
|
|
|
max_features = self.n_features_
|
2013-02-26 15:34:11 +08:00
|
|
|
elif isinstance(self.max_features, (numbers.Integral, np.integer)):
|
2012-01-03 17:11:52 +08:00
|
|
|
max_features = self.max_features
|
2013-03-05 04:57:52 +08:00
|
|
|
else: # float
|
2014-05-28 23:03:48 +08:00
|
|
|
if self.max_features > 0.0:
|
|
|
|
|
max_features = max(1, int(self.max_features * self.n_features_))
|
|
|
|
|
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
|
|
|
|
|
|
2011-11-02 19:32:48 +08:00
|
|
|
if len(y) != n_samples:
|
|
|
|
|
raise ValueError("Number of labels=%d does not match "
|
2012-01-03 17:21:18 +08:00
|
|
|
"number of samples=%d" % (len(y), n_samples))
|
2012-02-16 06:38:11 +08:00
|
|
|
if self.min_samples_split <= 0:
|
|
|
|
|
raise ValueError("min_samples_split must be greater than zero.")
|
|
|
|
|
if self.min_samples_leaf <= 0:
|
|
|
|
|
raise ValueError("min_samples_leaf must be greater than zero.")
|
2014-05-27 18:39:54 +08:00
|
|
|
if not 0 <= self.min_weight_fraction_leaf <= 0.5:
|
|
|
|
|
raise ValueError("min_weight_fraction_leaf must in [0, 0.5]")
|
2011-11-16 23:24:31 +08:00
|
|
|
if max_depth <= 0:
|
2011-11-02 19:32:48 +08:00
|
|
|
raise ValueError("max_depth must be greater than zero. ")
|
2012-01-03 17:11:52 +08:00
|
|
|
if not (0 < max_features <= self.n_features_):
|
2011-11-03 04:04:25 +08:00
|
|
|
raise ValueError("max_features must be in (0, n_features]")
|
2013-12-01 01:34:13 +08:00
|
|
|
if not isinstance(max_leaf_nodes, (numbers.Integral, np.integer)):
|
2014-01-08 19:25:56 +08:00
|
|
|
raise ValueError("max_leaf_nodes must be integral number but was "
|
|
|
|
|
"%r" % max_leaf_nodes)
|
|
|
|
|
if -1 < max_leaf_nodes < 2:
|
2014-01-16 20:44:43 +08:00
|
|
|
raise ValueError(("max_leaf_nodes {0} must be either smaller than "
|
|
|
|
|
"0 or larger than 1").format(max_leaf_nodes))
|
2013-01-06 07:24:22 +08:00
|
|
|
|
|
|
|
|
if sample_weight is not None:
|
|
|
|
|
if (getattr(sample_weight, "dtype", None) != DOUBLE or
|
|
|
|
|
not sample_weight.flags.contiguous):
|
|
|
|
|
sample_weight = np.ascontiguousarray(
|
|
|
|
|
sample_weight, dtype=DOUBLE)
|
|
|
|
|
if len(sample_weight.shape) > 1:
|
|
|
|
|
raise ValueError("Sample weights array has more "
|
|
|
|
|
"than one dimension: %d" %
|
|
|
|
|
len(sample_weight.shape))
|
|
|
|
|
if len(sample_weight) != n_samples:
|
|
|
|
|
raise ValueError("Number of weights=%d does not match "
|
|
|
|
|
"number of samples=%d" %
|
|
|
|
|
(len(sample_weight), n_samples))
|
|
|
|
|
|
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
|
|
|
|
|
if self.min_weight_fraction_leaf != 0. and sample_weight is not None:
|
|
|
|
|
min_weight_leaf = (self.min_weight_fraction_leaf *
|
|
|
|
|
np.sum(sample_weight))
|
|
|
|
|
else:
|
|
|
|
|
min_weight_leaf = 0.
|
|
|
|
|
|
2012-12-23 20:13:21 +08:00
|
|
|
# Set min_samples_split sensibly
|
2013-01-07 02:53:59 +08:00
|
|
|
min_samples_split = max(self.min_samples_split,
|
|
|
|
|
2 * self.min_samples_leaf)
|
2012-12-23 20:13:21 +08:00
|
|
|
|
2015-09-11 16:39:21 +08:00
|
|
|
|
|
|
|
|
presort = self.presort
|
|
|
|
|
# Allow presort to be 'auto', which means True if the dataset is dense,
|
|
|
|
|
# otherwise it will be False.
|
|
|
|
|
if self.presort == 'auto' and issparse(X):
|
|
|
|
|
presort = False
|
|
|
|
|
elif self.presort == 'auto':
|
|
|
|
|
presort = True
|
2015-10-20 19:15:24 +08:00
|
|
|
|
2015-09-11 16:39:21 +08:00
|
|
|
if presort == True and issparse(X):
|
|
|
|
|
raise ValueError("Presorting is not supported for sparse matrices.")
|
|
|
|
|
|
|
|
|
|
# If multiple trees are built on the same dataset, we only want to
|
2015-10-20 19:15:24 +08:00
|
|
|
# presort once. Splitters now can accept presorted indices if desired,
|
2015-09-11 16:39:21 +08:00
|
|
|
# but do not handle any presorting themselves. Ensemble algorithms which
|
|
|
|
|
# desire presorting must do presorting themselves and pass that matrix
|
|
|
|
|
# into each tree.
|
|
|
|
|
if X_idx_sorted is None and presort:
|
|
|
|
|
X_idx_sorted = np.asfortranarray(np.argsort(X, axis=0),
|
|
|
|
|
dtype=np.int32)
|
|
|
|
|
|
|
|
|
|
if presort and X_idx_sorted.shape != X.shape:
|
|
|
|
|
raise ValueError("The shape of X (X.shape = {}) doesn't match "
|
|
|
|
|
"the shape of X_idx_sorted (X_idx_sorted"
|
2015-10-20 19:15:24 +08:00
|
|
|
".shape = {})".format(X.shape,
|
2015-09-11 16:39:21 +08:00
|
|
|
X_idx_sorted.shape))
|
|
|
|
|
|
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:
|
|
|
|
|
criterion = CRITERIA_REG[self.criterion](self.n_outputs_)
|
|
|
|
|
|
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_,
|
2013-07-08 20:50:48 +08:00
|
|
|
self.min_samples_leaf,
|
2014-06-28 15:26:46 +08:00
|
|
|
min_weight_leaf,
|
2015-09-11 16:39:21 +08:00
|
|
|
random_state,
|
|
|
|
|
self.presort)
|
2013-07-08 20:47:47 +08:00
|
|
|
|
2014-03-18 04:48:41 +08:00
|
|
|
self.tree_ = Tree(self.n_features_, self.n_classes_, 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-05-27 18:39:54 +08:00
|
|
|
self.min_samples_leaf,
|
2014-06-28 15:26:46 +08:00
|
|
|
min_weight_leaf,
|
2014-05-27 18:39:54 +08:00
|
|
|
max_depth)
|
2013-11-21 04:10:16 +08:00
|
|
|
else:
|
2014-03-18 04:45:27 +08:00
|
|
|
builder = BestFirstTreeBuilder(splitter, min_samples_split,
|
2014-05-27 18:39:54 +08:00
|
|
|
self.min_samples_leaf,
|
2014-06-28 15:26:46 +08:00
|
|
|
min_weight_leaf,
|
2014-05-27 18:39:54 +08:00
|
|
|
max_depth,
|
2014-03-18 04:45:27 +08:00
|
|
|
max_leaf_nodes)
|
2013-12-01 01:34:13 +08:00
|
|
|
|
2015-09-11 16:39:21 +08:00
|
|
|
builder.build(self.tree_, X, y, sample_weight, X_idx_sorted)
|
2011-09-26 00:41:50 +08:00
|
|
|
|
2012-12-04 21:25:14 +08:00
|
|
|
if self.n_outputs_ == 1:
|
|
|
|
|
self.n_classes_ = self.n_classes_[0]
|
|
|
|
|
self.classes_ = self.classes_[0]
|
|
|
|
|
|
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):
|
2015-04-16 19:51:54 +08:00
|
|
|
"""Validate X whenever one tries to predict, apply, predict_proba"""
|
2015-04-16 16:34:33 +08:00
|
|
|
if self.tree_ is None:
|
2015-04-16 21:12:49 +08:00
|
|
|
raise NotFittedError("Estimator not fitted, "
|
|
|
|
|
"call `fit` before exploiting the model.")
|
2015-04-16 16:34:33 +08:00
|
|
|
|
|
|
|
|
if check_input:
|
|
|
|
|
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
|
|
|
|
|
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")
|
|
|
|
|
|
|
|
|
|
n_features = X.shape[1]
|
|
|
|
|
if self.n_features_ != n_features:
|
|
|
|
|
raise ValueError("Number of features of the model must "
|
|
|
|
|
" match the input. Model n_features is %s and "
|
|
|
|
|
" input n_features is %s "
|
|
|
|
|
% (self.n_features_, n_features))
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
----------
|
2014-04-04 04:28:08 +08:00
|
|
|
X : array-like or sparse matrix of shape = [n_samples, n_features]
|
|
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
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-14 07:30:02 +08:00
|
|
|
check_input : boolean, (default=True)
|
|
|
|
|
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
|
|
|
|
|
-------
|
2012-07-02 17:51:50 +08:00
|
|
|
y : array 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
|
|
|
"""
|
2015-09-11 16:39:21 +08:00
|
|
|
|
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
|
2011-11-01 21:22:31 +08:00
|
|
|
if isinstance(self, ClassifierMixin):
|
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:
|
2012-12-05 05:10:09 +08:00
|
|
|
predictions = np.zeros((n_samples, self.n_outputs_))
|
2012-06-28 16:09:21 +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
|
|
|
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):
|
2015-01-08 10:55:23 +08:00
|
|
|
"""
|
2015-04-02 17:51:00 +08:00
|
|
|
Returns the index of the leaf that each sample is predicted as.
|
2015-01-08 02:30:57 +08:00
|
|
|
|
2015-01-08 10:55:23 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2015-01-10 12:36:15 +08:00
|
|
|
X : array_like or sparse matrix, shape = [n_samples, n_features]
|
|
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
2015-01-08 02:30:57 +08:00
|
|
|
|
2015-04-16 16:19:57 +08:00
|
|
|
check_input : boolean, (default=True)
|
|
|
|
|
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
|
|
|
|
|
-------
|
2015-01-10 12:36:15 +08:00
|
|
|
X_leaves : array_like, 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
|
|
|
"""
|
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):
|
2015-10-20 19:15:24 +08:00
|
|
|
"""Return the decision path in the tree
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
X : array_like or sparse matrix, shape = [n_samples, n_features]
|
|
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
|
|
|
|
|
|
|
|
|
check_input : boolean, (default=True)
|
|
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
indicator : sparse csr array, shape = [n_samples, n_nodes]
|
|
|
|
|
Return a node indicator 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
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
feature_importances_ : array, shape = [n_features]
|
|
|
|
|
"""
|
|
|
|
|
if self.tree_ is None:
|
|
|
|
|
raise NotFittedError("Estimator not fitted, call `fit` before"
|
|
|
|
|
" `feature_importances_`.")
|
|
|
|
|
|
|
|
|
|
return self.tree_.compute_feature_importances()
|
|
|
|
|
|
2011-04-02 05:28:20 +08:00
|
|
|
|
2013-07-04 23:19:45 +08:00
|
|
|
# =============================================================================
|
|
|
|
|
# Public estimators
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
2012-12-23 20:35:30 +08:00
|
|
|
class DecisionTreeClassifier(BaseDecisionTree, ClassifierMixin):
|
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
|
|
|
|
|
----------
|
2011-09-26 20:09:03 +08:00
|
|
|
criterion : string, optional (default="gini")
|
|
|
|
|
The function to measure the quality of a split. Supported criteria are
|
|
|
|
|
"gini" for the Gini impurity and "entropy" for the information gain.
|
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
|
|
|
|
2013-08-23 07:24:07 +08:00
|
|
|
splitter : string, optional (default="best")
|
|
|
|
|
The strategy used to choose the split at each node. Supported
|
|
|
|
|
strategies are "best" to choose the best split and "random" to choose
|
|
|
|
|
the best random split.
|
|
|
|
|
|
2013-02-25 21:41:43 +08:00
|
|
|
max_features : int, float, string or None, optional (default=None)
|
2012-12-24 01:36:30 +08:00
|
|
|
The number of features to consider when looking for the best split:
|
2013-02-25 21:41:43 +08:00
|
|
|
- If int, then consider `max_features` features at each split.
|
2013-02-25 22:00:31 +08:00
|
|
|
- If float, then `max_features` is a percentage and
|
|
|
|
|
`int(max_features * n_features)` features are considered at each
|
|
|
|
|
split.
|
2013-02-25 21:41:43 +08:00
|
|
|
- If "auto", then `max_features=sqrt(n_features)`.
|
2012-12-24 01:36:30 +08:00
|
|
|
- If "sqrt", then `max_features=sqrt(n_features)`.
|
|
|
|
|
- If "log2", then `max_features=log2(n_features)`.
|
|
|
|
|
- If None, then `max_features=n_features`.
|
2012-12-23 20:13:21 +08:00
|
|
|
|
2014-03-18 21:19:40 +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-12-03 03:13:57 +08:00
|
|
|
max_depth : int or None, optional (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.
|
2014-12-29 15:42:23 +08:00
|
|
|
Ignored if ``max_leaf_nodes`` is not None.
|
2011-08-09 20:29:39 +08:00
|
|
|
|
2013-12-01 01:34:13 +08:00
|
|
|
min_samples_split : int, optional (default=2)
|
2011-11-02 18:40:54 +08:00
|
|
|
The minimum number of samples required to split an internal node.
|
2011-08-09 20:29:39 +08:00
|
|
|
|
2013-12-01 01:34:13 +08:00
|
|
|
min_samples_leaf : int, optional (default=1)
|
2012-02-14 18:09:40 +08:00
|
|
|
The minimum number of samples required to be at a leaf node.
|
|
|
|
|
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf : float, optional (default=0.)
|
|
|
|
|
The minimum weighted fraction of the input samples required to be at a
|
|
|
|
|
leaf node.
|
|
|
|
|
|
2013-12-01 01:34:13 +08:00
|
|
|
max_leaf_nodes : int or None, optional (default=None)
|
2013-11-03 15:40:24 +08:00
|
|
|
Grow a tree with ``max_leaf_nodes`` in best-first fashion.
|
2013-12-01 01:34:13 +08:00
|
|
|
Best nodes are defined as relative reduction in impurity.
|
|
|
|
|
If None then unlimited number of leaf nodes.
|
2013-12-03 03:13:57 +08:00
|
|
|
If not None then ``max_depth`` will be ignored.
|
2013-11-02 07:04:23 +08:00
|
|
|
|
2015-05-13 03:41:22 +08:00
|
|
|
class_weight : dict, list of dicts, "balanced" or None, optional
|
|
|
|
|
(default=None)
|
2014-12-23 08:50:58 +08:00
|
|
|
Weights associated with classes in the form ``{class_label: weight}``.
|
|
|
|
|
If not given, all classes are supposed to have weight one. For
|
|
|
|
|
multi-output problems, a list of dicts can be provided in the same
|
|
|
|
|
order as the columns of y.
|
|
|
|
|
|
2015-05-13 03:41:22 +08:00
|
|
|
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))``
|
2014-12-23 08:50:58 +08:00
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
2011-11-01 21:22:31 +08:00
|
|
|
random_state : int, RandomState instance or None, optional (default=None)
|
|
|
|
|
If int, random_state is the seed used by the random number generator;
|
|
|
|
|
If RandomState instance, random_state is the random number generator;
|
|
|
|
|
If None, the random number generator is the RandomState instance used
|
|
|
|
|
by `np.random`.
|
|
|
|
|
|
2015-09-11 16:39:21 +08:00
|
|
|
presort : bool, optional (default=False)
|
|
|
|
|
Whether to presort the data to speed up the finding of best splits in
|
|
|
|
|
fitting. For the default settings of a decision tree on large
|
|
|
|
|
datasets, setting this to true may slow down the training process.
|
|
|
|
|
When using either a smaller dataset or a restricted depth, this may
|
|
|
|
|
speed up the training.
|
|
|
|
|
|
2011-12-28 00:44:04 +08:00
|
|
|
Attributes
|
|
|
|
|
----------
|
2014-07-28 17:04:59 +08:00
|
|
|
classes_ : array of shape = [n_classes] or a list of such arrays
|
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
|
|
|
|
2014-07-28 17:04:59 +08:00
|
|
|
feature_importances_ : array of shape = [n_features]
|
2013-03-12 05:51:22 +08:00
|
|
|
The 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 [4]_.
|
2011-12-28 00:44:04 +08:00
|
|
|
|
2015-05-12 21:00:27 +08:00
|
|
|
max_features_ : int,
|
|
|
|
|
The inferred value of max_features.
|
|
|
|
|
|
|
|
|
|
n_classes_ : int or list
|
|
|
|
|
The number of classes (for single output problems),
|
|
|
|
|
or a list containing the number of classes for each
|
|
|
|
|
output (for multi-output problems).
|
|
|
|
|
|
|
|
|
|
n_features_ : int
|
|
|
|
|
The number of features when ``fit`` is performed.
|
|
|
|
|
|
|
|
|
|
n_outputs_ : int
|
|
|
|
|
The number of outputs when ``fit`` is performed.
|
|
|
|
|
|
|
|
|
|
tree_ : Tree object
|
|
|
|
|
The underlying Tree object.
|
|
|
|
|
|
2011-12-22 01:05:22 +08:00
|
|
|
See also
|
|
|
|
|
--------
|
|
|
|
|
DecisionTreeRegressor
|
|
|
|
|
|
2012-03-04 04:15:56 +08:00
|
|
|
References
|
|
|
|
|
----------
|
2011-12-22 02:29:01 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
.. [1] http://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",
|
|
|
|
|
http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
|
|
|
|
|
|
2011-09-26 19:25:39 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
2011-09-04 02:54:12 +08:00
|
|
|
>>> from sklearn.datasets import load_iris
|
2011-09-22 21:48:56 +08:00
|
|
|
>>> from sklearn.cross_validation 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
|
|
|
"""
|
2012-11-26 21:57:51 +08:00
|
|
|
def __init__(self,
|
|
|
|
|
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,
|
2012-11-26 21:57:51 +08:00
|
|
|
min_samples_leaf=1,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf=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,
|
2015-09-11 16:39:21 +08:00
|
|
|
class_weight=None,
|
|
|
|
|
presort=False):
|
2014-01-16 20:44:43 +08:00
|
|
|
super(DecisionTreeClassifier, self).__init__(
|
|
|
|
|
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,
|
|
|
|
|
presort=presort)
|
2014-01-16 20:44:43 +08:00
|
|
|
|
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.
|
|
|
|
|
|
2015-04-14 07:30:02 +08:00
|
|
|
check_input : boolean, (default=True)
|
|
|
|
|
Allow to bypass several input checking.
|
|
|
|
|
Don't use this parameter unless you know what you do.
|
|
|
|
|
|
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
|
|
|
|
|
----------
|
2014-04-04 04:28:08 +08:00
|
|
|
X : array-like or sparse matrix of shape = [n_samples, n_features]
|
|
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
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
|
|
|
|
|
-------
|
2012-07-02 18:11:27 +08:00
|
|
|
p : array of shape = [n_samples, n_classes], or a 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
|
|
|
|
|
classes corresponds to that in the attribute `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
|
|
|
"""
|
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
|
|
|
|
|
----------
|
2014-04-04 04:28:08 +08:00
|
|
|
X : array-like or sparse matrix of shape = [n_samples, n_features]
|
|
|
|
|
The input samples. Internally, it will be converted to
|
|
|
|
|
``dtype=np.float32`` and if a sparse matrix is provided
|
|
|
|
|
to a sparse ``csr_matrix``.
|
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
|
|
|
|
|
-------
|
2012-07-02 18:11:27 +08:00
|
|
|
p : array of shape = [n_samples, n_classes], or a 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
|
|
|
|
|
classes corresponds to that in the attribute `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
|
|
|
|
|
|
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-12-23 20:35:30 +08:00
|
|
|
class DecisionTreeRegressor(BaseDecisionTree, RegressorMixin):
|
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
|
|
|
|
|
----------
|
2011-09-26 20:09:03 +08:00
|
|
|
criterion : string, optional (default="mse")
|
|
|
|
|
The function to measure the quality of a split. The only supported
|
2015-07-12 04:03:20 +08:00
|
|
|
criterion is "mse" for the mean squared error, which is equal to
|
|
|
|
|
variance reduction as feature selection criterion.
|
2011-07-29 20:57:39 +08:00
|
|
|
|
2013-08-23 07:24:07 +08:00
|
|
|
splitter : string, optional (default="best")
|
|
|
|
|
The strategy used to choose the split at each node. Supported
|
|
|
|
|
strategies are "best" to choose the best split and "random" to choose
|
|
|
|
|
the best random split.
|
|
|
|
|
|
2013-02-25 21:41:43 +08:00
|
|
|
max_features : int, float, string or None, optional (default=None)
|
2012-12-24 01:36:30 +08:00
|
|
|
The number of features to consider when looking for the best split:
|
2013-02-25 21:41:43 +08:00
|
|
|
- If int, then consider `max_features` features at each split.
|
2013-02-25 22:00:31 +08:00
|
|
|
- If float, then `max_features` is a percentage and
|
|
|
|
|
`int(max_features * n_features)` features are considered at each
|
|
|
|
|
split.
|
2013-02-25 21:41:43 +08:00
|
|
|
- If "auto", then `max_features=n_features`.
|
2012-12-24 01:36:30 +08:00
|
|
|
- If "sqrt", then `max_features=sqrt(n_features)`.
|
|
|
|
|
- If "log2", then `max_features=log2(n_features)`.
|
|
|
|
|
- If None, then `max_features=n_features`.
|
2012-12-23 20:13:21 +08:00
|
|
|
|
2014-03-18 21:19:40 +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-12-01 01:34:13 +08:00
|
|
|
max_depth : int or None, optional (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.
|
2014-12-29 15:42:23 +08:00
|
|
|
Ignored if ``max_leaf_nodes`` is not None.
|
2011-08-09 20:29:39 +08:00
|
|
|
|
2013-12-01 01:34:13 +08:00
|
|
|
min_samples_split : int, optional (default=2)
|
2011-09-26 20:09:03 +08:00
|
|
|
The minimum number of samples required to split an internal node.
|
2011-08-09 20:29:39 +08:00
|
|
|
|
2013-12-01 01:34:13 +08:00
|
|
|
min_samples_leaf : int, optional (default=1)
|
2012-02-14 18:09:40 +08:00
|
|
|
The minimum number of samples required to be at a leaf node.
|
|
|
|
|
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf : float, optional (default=0.)
|
|
|
|
|
The minimum weighted fraction of the input samples required to be at a
|
|
|
|
|
leaf node.
|
|
|
|
|
|
2013-12-01 01:34:13 +08:00
|
|
|
max_leaf_nodes : int or None, optional (default=None)
|
2013-11-03 15:40:24 +08:00
|
|
|
Grow a tree with ``max_leaf_nodes`` in best-first fashion.
|
2013-12-01 01:34:13 +08:00
|
|
|
Best nodes are defined as relative reduction in impurity.
|
|
|
|
|
If None then unlimited number of leaf nodes.
|
2013-12-03 03:13:57 +08:00
|
|
|
If not None then ``max_depth`` will be ignored.
|
2013-11-02 07:04:23 +08:00
|
|
|
|
2011-11-01 21:22:31 +08:00
|
|
|
random_state : int, RandomState instance or None, optional (default=None)
|
|
|
|
|
If int, random_state is the seed used by the random number generator;
|
|
|
|
|
If RandomState instance, random_state is the random number generator;
|
|
|
|
|
If None, the random number generator is the RandomState instance used
|
|
|
|
|
by `np.random`.
|
|
|
|
|
|
2015-09-11 16:39:21 +08:00
|
|
|
presort : bool, optional (default=False)
|
|
|
|
|
Whether to presort the data to speed up the finding of best splits in
|
|
|
|
|
fitting. For the default settings of a decision tree on large
|
|
|
|
|
datasets, setting this to true may slow down the training process.
|
|
|
|
|
When using either a smaller dataset or a restricted depth, this may
|
|
|
|
|
speed up the training.
|
|
|
|
|
|
2011-12-28 00:44:04 +08:00
|
|
|
Attributes
|
|
|
|
|
----------
|
2014-07-28 17:04:59 +08:00
|
|
|
feature_importances_ : array 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
|
|
|
|
2015-05-12 21:00:27 +08:00
|
|
|
max_features_ : int,
|
|
|
|
|
The inferred value of max_features.
|
|
|
|
|
|
|
|
|
|
n_features_ : int
|
|
|
|
|
The number of features when ``fit`` is performed.
|
|
|
|
|
|
|
|
|
|
n_outputs_ : int
|
|
|
|
|
The number of outputs when ``fit`` is performed.
|
|
|
|
|
|
|
|
|
|
tree_ : Tree object
|
|
|
|
|
The underlying Tree object.
|
|
|
|
|
|
2012-01-09 16:12:13 +08:00
|
|
|
See also
|
|
|
|
|
--------
|
|
|
|
|
DecisionTreeClassifier
|
|
|
|
|
|
2012-03-04 04:15:56 +08:00
|
|
|
References
|
|
|
|
|
----------
|
2011-12-22 02:29:01 +08:00
|
|
|
|
2011-09-26 20:09:03 +08:00
|
|
|
.. [1] http://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",
|
|
|
|
|
http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
|
|
|
|
|
|
2011-09-26 19:25:39 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
2011-09-04 02:54:12 +08:00
|
|
|
>>> from sklearn.datasets import load_boston
|
2011-09-22 21:48:56 +08:00
|
|
|
>>> from sklearn.cross_validation import cross_val_score
|
2011-11-24 05:31:17 +08:00
|
|
|
>>> from sklearn.tree import DecisionTreeRegressor
|
2011-09-04 21:45:15 +08:00
|
|
|
>>> boston = load_boston()
|
|
|
|
|
>>> regressor = DecisionTreeRegressor(random_state=0)
|
|
|
|
|
>>> cross_val_score(regressor, boston.data, boston.target, cv=10)
|
2011-09-25 23:37:03 +08:00
|
|
|
... # doctest: +SKIP
|
2011-08-11 19:49:38 +08:00
|
|
|
...
|
2011-09-22 03:06:32 +08:00
|
|
|
array([ 0.61..., 0.57..., -0.34..., 0.41..., 0.75...,
|
2011-09-22 22:08:17 +08:00
|
|
|
0.07..., 0.29..., 0.33..., -1.42..., -1.77...])
|
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-11-26 21:57:51 +08:00
|
|
|
def __init__(self,
|
|
|
|
|
criterion="mse",
|
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,
|
2012-11-26 21:57:51 +08:00
|
|
|
min_samples_leaf=1,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf=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,
|
|
|
|
|
presort=False):
|
2014-01-16 20:44:43 +08:00
|
|
|
super(DecisionTreeRegressor, self).__init__(
|
|
|
|
|
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,
|
|
|
|
|
presort=presort)
|
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 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>`.
|
|
|
|
|
|
2011-11-13 17:05:21 +08:00
|
|
|
See also
|
|
|
|
|
--------
|
|
|
|
|
ExtraTreeRegressor, ExtraTreesClassifier, ExtraTreesRegressor
|
|
|
|
|
|
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.
|
|
|
|
|
"""
|
2012-11-26 21:57:51 +08:00
|
|
|
def __init__(self,
|
|
|
|
|
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,
|
2012-11-26 21:57:51 +08:00
|
|
|
min_samples_leaf=1,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf=0.,
|
2012-11-26 21:57:51 +08:00
|
|
|
max_features="auto",
|
2013-07-11 15:25:45 +08:00
|
|
|
random_state=None,
|
2014-12-23 08:50:58 +08:00
|
|
|
max_leaf_nodes=None,
|
|
|
|
|
class_weight=None):
|
2014-01-16 20:44:43 +08:00
|
|
|
super(ExtraTreeClassifier, self).__init__(
|
|
|
|
|
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,
|
2014-01-16 20:44:43 +08:00
|
|
|
random_state=random_state)
|
|
|
|
|
|
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>`.
|
|
|
|
|
|
2011-11-13 17:05:21 +08:00
|
|
|
See also
|
|
|
|
|
--------
|
2013-07-11 15:30:19 +08:00
|
|
|
ExtraTreeClassifier, ExtraTreesClassifier, ExtraTreesRegressor
|
2011-11-13 17:05:21 +08:00
|
|
|
|
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.
|
|
|
|
|
"""
|
2012-11-26 21:57:51 +08:00
|
|
|
def __init__(self,
|
|
|
|
|
criterion="mse",
|
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,
|
2012-11-26 21:57:51 +08:00
|
|
|
min_samples_leaf=1,
|
2014-05-27 18:39:54 +08:00
|
|
|
min_weight_fraction_leaf=0.,
|
2012-11-26 21:57:51 +08:00
|
|
|
max_features="auto",
|
2013-07-11 15:25:45 +08:00
|
|
|
random_state=None,
|
2013-12-01 01:34:13 +08:00
|
|
|
max_leaf_nodes=None):
|
2014-01-16 20:44:43 +08:00
|
|
|
super(ExtraTreeRegressor, self).__init__(
|
|
|
|
|
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,
|
|
|
|
|
random_state=random_state)
|