KEMBAR78
1.10. Decision Trees - Scikit-Learn 0.24.1 Documentation | PDF | Machine Learning | Algorithms
0% found this document useful (0 votes)
83 views10 pages

1.10. Decision Trees - Scikit-Learn 0.24.1 Documentation

Decision Trees (DTs) are a non-parametric supervised learning method used for classification and regression, creating models that predict target variable values through decision rules derived from data features. They offer advantages such as interpretability and minimal data preparation but can suffer from overfitting and instability. The document also discusses the implementation of DecisionTreeClassifier and DecisionTreeRegressor in scikit-learn, along with practical tips and various decision tree algorithms.

Uploaded by

Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views10 pages

1.10. Decision Trees - Scikit-Learn 0.24.1 Documentation

Decision Trees (DTs) are a non-parametric supervised learning method used for classification and regression, creating models that predict target variable values through decision rules derived from data features. They offer advantages such as interpretability and minimal data preparation but can suffer from overfitting and instability. The document also discusses the implementation of DecisionTreeClassifier and DecisionTreeRegressor in scikit-learn, along with practical tips and various decision tree algorithms.

Uploaded by

Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1.10.

Decision Trees
Decision Trees (DTs) are a non-parametric supervised learning method used for classification and regression. The goal is to create a
model that predicts the value of a target variable by learning simple decision rules inferred from the data features. A tree can be seen as
a piecewise constant approximation.

For instance, in the example below, decision trees learn from data to approximate a sine curve with a set of if-then-else decision rules.
The deeper the tree, the more complex the decision rules and the fitter the model.

Some advantages of decision trees are:

Simple to understand and to interpret. Trees can be visualised.


Requires little data preparation. Other techniques often require data normalisation, dummy variables need to be created and blank
values to be removed. Note however that this module does not support missing values.
The cost of using the tree (i.e., predicting data) is logarithmic in the number of data points used to train the tree.
Able to handle both numerical and categorical data. However scikit-learn implementation does not support categorical variables for
now. Other techniques are usually specialised in analysing datasets that have only one type of variable. See algorithms for more infor-
mation.
Able to handle multi-output problems.
Uses a white box model. If a given situation is observable in a model, the explanation for the condition is easily explained by boolean
logic. By contrast, in a black box model (e.g., in an artificial neural network), results may be more difficult to interpret.
Possible to validate a model using statistical tests. That makes it possible to account for the reliability of the model.
Performs well even if its assumptions are somewhat violated by the true model from which the data were generated.

The disadvantages of decision trees include:

Toggle Menu
Decision-tree learners can create over-complex trees that do not generalise the data well. This is called overfitting. Mechanisms such
as pruning, setting the minimum number of samples required at a leaf node or setting the maximum depth of the tree are necessary
to avoid this problem.
Decision trees can be unstable because small variations in the data might result in a completely different tree being generated. This
problem is mitigated by using decision trees within an ensemble.
Predictions of decision trees are neither smooth nor continuous, but piecewise constant approximations as seen in the above figure.
Therefore, they are not good at extrapolation.
The problem of learning an optimal decision tree is known to be NP-complete under several aspects of optimality and even for sim-
ple concepts. Consequently, practical decision-tree learning algorithms are based on heuristic algorithms such as the greedy algo-
rithm where locally optimal decisions are made at each node. Such algorithms cannot guarantee to return the globally optimal deci-
sion tree. This can be mitigated by training multiple trees in an ensemble learner, where the features and samples are randomly sam-
pled with replacement.
There are concepts that are hard to learn because decision trees do not express them easily, such as XOR, parity or multiplexer prob-
lems.
Decision tree learners create biased trees if some classes dominate. It is therefore recommended to balance the dataset prior to fit-
ting with the decision tree.

1.10.1. Classification
DecisionTreeClassifier is a class capable of performing multi-class classification on a dataset.

As with other classifiers, DecisionTreeClassifier takes as input two arrays: an array X, sparse or dense, of shape (n_samples, n_fea-
tures) holding the training samples, and an array Y of integer values, shape (n_samples,) , holding the class labels for the training sam-
ples:

>>> from sklearn import tree >>>


>>> X = [[0, 0], [1, 1]]
>>> Y = [0, 1]
>>> clf = tree.DecisionTreeClassifier()
>>> clf = clf.fit(X, Y)

After being fitted, the model can then be used to predict the class of samples:

>>> clf.predict([[2., 2.]]) >>>


array([1])

In case that there are multiple classes with the same and highest probability, the classifier will predict the class with the lowest index
amongst those classes.

As an alternative to outputting a specific class, the probability of each class can be predicted, which is the fraction of training samples of
the class in a leaf:

>>> clf.predict_proba([[2., 2.]]) >>>


array([[0., 1.]])

DecisionTreeClassifier is capable of both binary (where the labels are [-1, 1]) classification and multiclass (where the labels are [0, …,
K-1]) classification.

Using the Iris dataset, we can construct a tree as follows:

>>> from sklearn.datasets import load_iris >>>


>>> from sklearn import tree
>>> X, y = load_iris(return_X_y=True)
>>> clf = tree.DecisionTreeClassifier()
>>> clf = clf.fit(X, y)

Once trained, you can plot the tree with the plot_tree function:

plot_tree(clf) >>>
Toggle Menu
We can also export the tree in Graphviz format using the export_graphviz exporter. If you use the conda package manager, the graphviz
binaries and the python package can be installed with conda install python-graphviz .

Alternatively binaries for graphviz can be downloaded from the graphviz project homepage, and the Python wrapper installed from pypi
with pip install graphviz .

Below is an example graphviz export of the above tree trained on the entire iris dataset; the results are saved in an output file iris.pdf :

>>> import graphviz >>>


>>> dot_data = tree.export_graphviz(clf, out_file=None)
>>> graph = graphviz.Source(dot_data)
>>> graph.render("iris")

The export_graphviz exporter also supports a variety of aesthetic options, including coloring nodes by their class (or value for regression)
and using explicit variable and class names if desired. Jupyter notebooks also render these plots inline automatically:

>>> dot_data = tree.export_graphviz(clf, out_file=None, >>>


... feature_names=iris.feature_names,
... class_names=iris.target_names,
... filled=True, rounded=True,
... special_characters=True)
>>> graph = graphviz.Source(dot_data)
>>> graph

Toggle Menu
Alternatively, the tree can also be exported in textual format with the function export_text. This method doesn’t require the installation
of external libraries and is more compact:

>>>

Toggle Menu
>>> from sklearn.datasets import load_iris
>>> from sklearn.tree import DecisionTreeClassifier
>>> from sklearn.tree import export_text
>>> iris = load_iris()
>>> decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
>>> decision_tree = decision_tree.fit(iris.data, iris.target)
>>> r = export_text(decision_tree, feature_names=iris['feature_names'])
>>> print(r)
|--- petal width (cm) <= 0.80
| |--- class: 0
|--- petal width (cm) > 0.80
| |--- petal width (cm) <= 1.75
| | |--- class: 1
| |--- petal width (cm) > 1.75
| | |--- class: 2

Examples:
Plot the decision surface of a decision tree on the iris dataset
Understanding the decision tree structure

1.10.2. Regression

Decision trees can also be applied to regression problems, using the DecisionTreeRegressor class.

As in the classification setting, the fit method will take as argument arrays X and y, only that in this case y is expected to have floating
point values instead of integer values:

>>> from sklearn import tree >>>


>>> X = [[0, 0], [2, 2]]
>>> y = [0.5, 2.5]
>>> clf = tree.DecisionTreeRegressor()
>>> clf = clf.fit(X, y)
>>> clf.predict([[1, 1]])
array([0.5])

Examples:
Decision Tree Regression

1.10.3. Multi-output problems


A multi-output problem is a supervised learning problem with several outputs to predict, that is when Y is a 2d array of shape (n_sam-
Toggle n_outputs)
Menu .
When there is no correlation between the outputs, a very simple way to solve this kind of problem is to build n independent models, i.e.
one for each output, and then to use those models to independently predict each one of the n outputs. However, because it is likely that
the output values related to the same input are themselves correlated, an often better way is to build a single model capable of predict-
ing simultaneously all n outputs. First, it requires lower training time since only a single estimator is built. Second, the generalization ac-
curacy of the resulting estimator may often be increased.

With regard to decision trees, this strategy can readily be used to support multi-output problems. This requires the following changes:

Store n output values in leaves, instead of 1;


Use splitting criteria that compute the average reduction across all n outputs.

This module offers support for multi-output problems by implementing this strategy in both DecisionTreeClassifier and
DecisionTreeRegressor. If a decision tree is fit on an output array Y of shape (n_samples, n_outputs) then the resulting estimator will:

Output n_output values upon predict ;


Output a list of n_output arrays of class probabilities upon predict_proba .

The use of multi-output trees for regression is demonstrated in Multi-output Decision Tree Regression. In this example, the input X is a
single real value and the outputs Y are the sine and cosine of X.

The use of multi-output trees for classification is demonstrated in Face completion with a multi-output estimators. In this example, the in-
puts X are the pixels of the upper half of faces and the outputs Y are the pixels of the lower half of those faces.

Toggle Menu
Examples:
Multi-output Decision Tree Regression
Face completion with a multi-output estimators

References:
M. Dumont et al, Fast multi-class image annotation with random subwindows and multiple output randomized trees, International
Conference on Computer Vision Theory and Applications 2009

1.10.4. Complexity
In general, the run time cost to construct a balanced binary tree is and query time .
Although the tree construction algorithm attempts to generate balanced trees, they will not always be balanced. Assuming that the sub-
trees remain approximately balanced, the cost at each node consists of searching through to find the feature that offers the
largest reduction in entropy. This has a cost of at each node, leading to a total cost over the entire
trees (by summing the cost at each node) of .

Toggle Menu
1.10.5. Tips on practical use
Decision trees tend to overfit on data with a large number of features. Getting the right ratio of samples to number of features is
important, since a tree with few samples in high dimensional space is very likely to overfit.

Consider performing dimensionality reduction (PCA, ICA, or Feature selection) beforehand to give your tree a better chance of find-
ing features that are discriminative.

Understanding the decision tree structure will help in gaining more insights about how the decision tree makes predictions, which
is important for understanding the important features in the data.

Visualise your tree as you are training by using the export function. Use max_depth=3 as an initial tree depth to get a feel for how
the tree is fitting to your data, and then increase the depth.

Remember that the number of samples required to populate the tree doubles for each additional level the tree grows to. Use
max_depth to control the size of the tree to prevent overfitting.

Use min_samples_split or min_samples_leaf to ensure that multiple samples inform every decision in the tree, by controlling
which splits will be considered. A very small number will usually mean the tree will overfit, whereas a large number will prevent the
tree from learning the data. Try min_samples_leaf=5 as an initial value. If the sample size varies greatly, a float number can be used
as percentage in these two parameters. While min_samples_split can create arbitrarily small leaves, min_samples_leaf guarantees
that each leaf has a minimum size, avoiding low-variance, over-fit leaf nodes in regression problems. For classification with few
classes, min_samples_leaf=1 is often the best choice.

Note that min_samples_split considers samples directly and independent of sample_weight , if provided (e.g. a node with m
weighted samples is still treated as having exactly m samples). Consider min_weight_fraction_leaf or min_impurity_decrease if ac-
counting for sample weights is required at splits.

Balance your dataset before training to prevent the tree from being biased toward the classes that are dominant. Class balancing
can be done by sampling an equal number of samples from each class, or preferably by normalizing the sum of the sample weights
( sample_weight ) for each class to the same value. Also note that weight-based pre-pruning criteria, such as min_weight_frac-
tion_leaf , will then be less biased toward dominant classes than criteria that are not aware of the sample weights, like min_sam-
ples_leaf .

If the samples are weighted, it will be easier to optimize the tree structure using weight-based pre-pruning criterion such as
min_weight_fraction_leaf , which ensure that leaf nodes contain at least a fraction of the overall sum of the sample weights.

All decision trees use np.float32 arrays internally. If training data is not in this format, a copy of the dataset will be made.

If the input matrix X is very sparse, it is recommended to convert to sparse csc_matrix before calling fit and sparse csr_matrix be-
fore calling predict. Training time can be orders of magnitude faster for a sparse matrix input compared to a dense matrix when
features have zero values in most of the samples.

1.10.6. Tree algorithms: ID3, C4.5, C5.0 and CART


What are all the various decision tree algorithms and how do they differ from each other? Which one is implemented in scikit-learn?

ID3 (Iterative Dichotomiser 3) was developed in 1986 by Ross Quinlan. The algorithm creates a multiway tree, finding for each node (i.e. in
a greedy manner) the categorical feature that will yield the largest information gain for categorical targets. Trees are grown to their maxi-
mum size and then a pruning step is usually applied to improve the ability of the tree to generalise to unseen data.

C4.5 is the successor to ID3 and removed the restriction that features must be categorical by dynamically defining a discrete attribute
(based on numerical variables) that partitions the continuous attribute value into a discrete set of intervals. C4.5 converts the trained trees
(i.e. the output of the ID3 algorithm) into sets of if-then rules. These accuracy of each rule is then evaluated to determine the order in
which they should be applied. Pruning is done by removing a rule’s precondition if the accuracy of the rule improves without it.

C5.0 is Quinlan’s latest version release under a proprietary license. It uses less memory and builds smaller rulesets than C4.5 while being
Toggle Menu
more accurate.
CART (Classification and Regression Trees) is very similar to C4.5, but it differs in that it supports numerical target variables (regression)
and does not compute rule sets. CART constructs binary trees using the feature and threshold that yield the largest information gain at
each node.

scikit-learn uses an optimised version of the CART algorithm; however, scikit-learn implementation does not support categorical variables
for now.

1.10.7. Mathematical formulation


Given training vectors , i=1,…, l and a label vector , a decision tree recursively partitions the feature space such that the
samples with the same labels or similar target values are grouped together.

Let the data at node be represented by with samples. For each candidate split consisting of a feature and
threshold , partition the data into and subsets

The quality of a candidate split of node is then computed using an impurity function or loss function , the choice of which de-
pends on the task being solved (classification or regression)

Select the parameters that minimises the impurity

Recurse for subsets and until the maximum allowable depth is reached, or .

1.10.7.1. Classification criteria


If a target is a classification outcome taking on values 0,1,…,K-1, for node , let

be the proportion of class k observations in node . If is a terminal node, predict_proba for this region is set to . Common mea-
sures of impurity are the following.

Gini:

Entropy:

Misclassification:

1.10.7.2. Regression criteria


If the target is a continuous value, then for node , common criteria to minimize as for determining locations for future splits are Mean
Squared Error (MSE or L2 error), Poisson deviance as well as Mean Absolute Error (MAE or L1 error). MSE and Poisson deviance both set
the predicted value of terminal nodes to the learned mean value of the node whereas the MAE sets the predicted value of terminal
nodes to the median .

Mean Squared
Toggle Menu Error:
Half Poisson deviance:

Setting criterion="poisson" might be a good choice if your target is a count or a frequency (count per some unit). In any case,
is a necessary condition to use this criterion. Note that it fits much slower than the MSE criterion.

Mean Absolute Error:

Note that it fits much slower than the MSE criterion.

1.10.8. Minimal Cost-Complexity Pruning


Minimal cost-complexity pruning is an algorithm used to prune a tree to avoid over-fitting, described in Chapter 3 of [BRE]. This algo-
rithm is parameterized by known as the complexity parameter. The complexity parameter is used to define the cost-complexity
measure, of a given tree :

where is the number of terminal nodes in and is traditionally defined as the total misclassification rate of the terminal nodes.
Alternatively, scikit-learn uses the total sample weighted impurity of the terminal nodes for . As shown above, the impurity of a
node depends on the criterion. Minimal cost-complexity pruning finds the subtree of that minimizes .

The cost complexity measure of a single node is . The branch, , is defined to be a tree where node is its root. In
general, the impurity of a node is greater than the sum of impurities of its terminal nodes, . However, the cost complexity
measure of a node, , and its branch, , can be equal depending on . We define the effective of a node to be the value where they
are equal, or . A non-terminal node with the smallest value of is the weakest link and will be
pruned. This process stops when the pruned tree’s minimal is greater than the ccp_alpha parameter.

Examples:
Post pruning decision trees with cost complexity pruning

References:
[BRE] L. Breiman, J. Friedman, R. Olshen, and C. Stone. Classification and Regression Trees. Wadsworth, Belmont, CA, 1984.

https://en.wikipedia.org/wiki/Decision_tree_learning
https://en.wikipedia.org/wiki/Predictive_analytics
J.R. Quinlan. C4. 5: programs for machine learning. Morgan Kaufmann, 1993.
T. Hastie, R. Tibshirani and J. Friedman. Elements of Statistical Learning, Springer, 2009.

© 2007 - 2020, scikit-learn developers (BSD License). Show this page source

Toggle Menu

You might also like