1.10. Decision Trees

Decision Trees (DTs) are a non-parametric supervised learning method usedfor classification and regression. The goal is to create a model that predicts the value of atarget variable by learning simple decision rules inferred from the datafeatures.

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

../_images/sphx_glr_plot_tree_regression_0011.png

Some advantages of decision trees are:

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

  • Requires little data preparation. Other techniques often require datanormalisation, dummy variables need to be created and blank values tobe removed. Note however that this module does not support missingvalues.

  • The cost of using the tree (i.e., predicting data) is logarithmic in thenumber of data points used to train the tree.

  • Able to handle both numerical and categorical data. Other techniquesare usually specialised in analysing datasets that have only one typeof variable. See algorithms for moreinformation.

  • 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 neuralnetwork), results may be more difficult to interpret.

  • Possible to validate a model using statistical tests. That makes itpossible to account for the reliability of the model.

  • Performs well even if its assumptions are somewhat violated bythe true model from which the data were generated.

The disadvantages of decision trees include:

  • Decision-tree learners can create over-complex trees that do notgeneralise the data well. This is called overfitting. Mechanismssuch as pruning (not currently supported), setting the minimumnumber of samples required at a leaf node or setting the maximumdepth of the tree are necessary to avoid this problem.

  • Decision trees can be unstable because small variations in thedata might result in a completely different tree being generated.This problem is mitigated by using decision trees within anensemble.

  • The problem of learning an optimal decision tree is known to beNP-complete under several aspects of optimality and even for simpleconcepts. Consequently, practical decision-tree learning algorithmsare based on heuristic algorithms such as the greedy algorithm wherelocally optimal decisions are made at each node. Such algorithmscannot guarantee to return the globally optimal decision tree. Thiscan be mitigated by training multiple trees in an ensemble learner,where the features and samples are randomly sampled with replacement.

  • There are concepts that are hard to learn because decision treesdo not express them easily, such as XOR, parity or multiplexer problems.

  • Decision tree learners create biased trees if some classes dominate.It is therefore recommended to balance the dataset prior to fittingwith the decision tree.

1.10.1. Classification

DecisionTreeClassifier is a class capable of performing multi-classclassification on a dataset.

As with other classifiers, DecisionTreeClassifier takes as input two arrays:an array X, sparse or dense, of size [n_samples, n_features] holding thetraining samples, and an array Y of integer values, size [n_samples],holding the class labels for the training samples:

>>>

  1. >>> from sklearn import tree
  2. >>> X = [[0, 0], [1, 1]]
  3. >>> Y = [0, 1]
  4. >>> clf = tree.DecisionTreeClassifier()
  5. >>> clf = clf.fit(X, Y)

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

>>>

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

Alternatively, the probability of each class can be predicted, which is thefraction of training samples of the same class in a leaf:

>>>

  1. >>> clf.predict_proba([[2., 2.]])
  2. array([[0., 1.]])

DecisionTreeClassifier is capable of both binary (where thelabels 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:

>>>

  1. >>> from sklearn.datasets import load_iris
  2. >>> from sklearn import tree
  3. >>> X, y = load_iris(return_X_y=True)
  4. >>> clf = tree.DecisionTreeClassifier()
  5. >>> clf = clf.fit(X, y)

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

>>>

  1. >>> tree.plot_tree(clf.fit(iris.data, iris.target))

../_images/sphx_glr_plot_iris_dtc_0021.png

We can also export the tree in Graphviz format using the export_graphvizexporter. 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 entireiris dataset; the results are saved in an output file iris.pdf:

>>>

  1. >>> import graphviz
  2. >>> dot_data = tree.export_graphviz(clf, out_file=None)
  3. >>> graph = graphviz.Source(dot_data)
  4. >>> graph.render("iris")

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

>>>

  1. >>> dot_data = tree.export_graphviz(clf, out_file=None,
  2. ... feature_names=iris.feature_names,
  3. ... class_names=iris.target_names,
  4. ... filled=True, rounded=True,
  5. ... special_characters=True)
  6. >>> graph = graphviz.Source(dot_data)
  7. >>> graph

../_images/iris.png

../_images/sphx_glr_plot_iris_dtc_0011.png

Alternatively, the tree can also be exported in textual format with thefunction export_text. This method doesn’t require the installationof external libraries and is more compact:

>>>

  1. >>> from sklearn.datasets import load_iris
  2. >>> from sklearn.tree import DecisionTreeClassifier
  3. >>> from sklearn.tree.export import export_text
  4. >>> iris = load_iris()
  5. >>> decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
  6. >>> decision_tree = decision_tree.fit(iris.data, iris.target)
  7. >>> r = export_text(decision_tree, feature_names=iris['feature_names'])
  8. >>> print(r)
  9. |--- petal width (cm) <= 0.80
  10. | |--- class: 0
  11. |--- petal width (cm) > 0.80
  12. | |--- petal width (cm) <= 1.75
  13. | | |--- class: 1
  14. | |--- petal width (cm) > 1.75
  15. | | |--- class: 2
  16. <BLANKLINE>

Examples:

1.10.2. Regression

../_images/sphx_glr_plot_tree_regression_0011.png

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

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

>>>

  1. >>> from sklearn import tree
  2. >>> X = [[0, 0], [2, 2]]
  3. >>> y = [0.5, 2.5]
  4. >>> clf = tree.DecisionTreeRegressor()
  5. >>> clf = clf.fit(X, y)
  6. >>> clf.predict([[1, 1]])
  7. array([0.5])

Examples:

1.10.3. Multi-output problems

A multi-output problem is a supervised learning problem with several outputsto predict, that is when Y is a 2d array of size [n_samples, n_outputs].

When there is no correlation between the outputs, a very simple way to solvethis kind of problem is to build n independent models, i.e. one for eachoutput, and then to use those models to independently predict each one of the noutputs. However, because it is likely that the output values related to thesame input are themselves correlated, an often better way is to build a singlemodel capable of predicting simultaneously all n outputs. First, it requireslower training time since only a single estimator is built. Second, thegeneralization accuracy of the resulting estimator may often be increased.

With regard to decision trees, this strategy can readily be used to supportmulti-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 alln outputs.

This module offers support for multi-output problems by implementing thisstrategy in both DecisionTreeClassifier andDecisionTreeRegressor. If a decision tree is fit on an output array Yof size [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 uponpredict_proba.

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

../_images/sphx_glr_plot_tree_regression_multioutput_0011.png

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

../_images/sphx_glr_plot_multioutput_face_completion_0011.png

Examples:

References:

1.10.4. Complexity

In general, the run time cost to construct a balanced binary tree is

1.10. Decision Trees - 图8 and query time1.10. Decision Trees - 图9. Although the tree construction algorithm attemptsto generate balanced trees, they will not always be balanced. Assuming that thesubtrees remain approximately balanced, the cost at each node consists ofsearching through1.10. Decision Trees - 图10 to find the feature that offers thelargest reduction in entropy. This has a cost of1.10. Decision Trees - 图11 at each node, leading to atotal cost over the entire trees (by summing the cost at each node) of1.10. Decision Trees - 图12.

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, sincea tree with few samples in high dimensional space is very likely to overfit.

  • Consider performing dimensionality reduction (PCA,ICA, or Feature selection) beforehand togive your tree a better chance of finding features that are discriminative.

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

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

  • Remember that the number of samples required to populate the tree doublesfor each additional level the tree grows to. Use max_depth to controlthe size of the tree to prevent overfitting.

  • Use min_samples_split or min_samples_leaf to ensure that multiplesamples inform every decision in the tree, by controlling which splits willbe considered. A very small number will usually mean the tree will overfit,whereas a large number will prevent the tree from learning the data. Trymin_samples_leaf=5 as an initial value. If the sample size variesgreatly, 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, avoidinglow-variance, over-fit leaf nodes in regression problems. Forclassification with few classes, min_samples_leaf=1 is often the bestchoice.

  • Balance your dataset before training to prevent the tree from being biasedtoward the classes that are dominant. Class balancing can be done bysampling an equal number of samples from each class, or preferably bynormalizing the sum of the sample weights (sample_weight) for eachclass to the same value. Also note that weight-based pre-pruning criteria,such as min_weight_fraction_leaf, will then be less biased towarddominant classes than criteria that are not aware of the sample weights,like min_samples_leaf.

  • If the samples are weighted, it will be easier to optimize the treestructure using weight-based pre-pruning criterion such asmin_weight_fraction_leaf, which ensure that leaf nodes contain at leasta 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 sparsecsc_matrix before calling fit and sparse csr_matrix before callingpredict. Training time can be orders of magnitude faster for a sparsematrix input compared to a dense matrix when features have zero values inmost 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 differfrom 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. ina greedy manner) the categorical feature that will yield the largestinformation gain for categorical targets. Trees are grown to theirmaximum size and then a pruning step is usually applied to improve theability of the tree to generalise to unseen data.

C4.5 is the successor to ID3 and removed the restriction that featuresmust be categorical by dynamically defining a discrete attribute (basedon numerical variables) that partitions the continuous attribute valueinto 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 orderin which they should be applied. Pruning is done by removing a rule’sprecondition 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 beingmore accurate.

CART (Classification and Regression Trees) is very similar to C4.5, butit differs in that it supports numerical target variables (regression) anddoes not compute rule sets. CART constructs binary trees using the featureand threshold that yield the largest information gain at each node.

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

1.10.7. Mathematical formulation

Given training vectors

1.10. Decision Trees - 图13, i=1,…, l and a label vector1.10. Decision Trees - 图14, a decision tree recursively partitions the space suchthat the samples with the same labels are grouped together.

Let the data at node

1.10. Decision Trees - 图15 be represented by1.10. Decision Trees - 图16. Foreach candidate split1.10. Decision Trees - 图17 consisting of afeature1.10. Decision Trees - 图18 and threshold1.10. Decision Trees - 图19, partition the data into1.10. Decision Trees - 图20 and1.10. Decision Trees - 图21 subsets

1.10. Decision Trees - 图22

The impurity at

1.10. Decision Trees - 图23 is computed using an impurity function1.10. Decision Trees - 图24, the choice of which depends on the task being solved(classification or regression)

1.10. Decision Trees - 图25

Select the parameters that minimises the impurity

1.10. Decision Trees - 图26

Recurse for subsets

1.10. Decision Trees - 图27 and1.10. Decision Trees - 图28 until the maximum allowable depth is reached,1.10. Decision Trees - 图29 or1.10. Decision Trees - 图30.

1.10.7.1. Classification criteria

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

1.10. Decision Trees - 图31, representing a region1.10. Decision Trees - 图32 with1.10. Decision Trees - 图33observations, let

1.10. Decision Trees - 图34

be the proportion of class k observations in node

1.10. Decision Trees - 图35

Common measures of impurity are Gini

1.10. Decision Trees - 图36

Entropy

1.10. Decision Trees - 图37

and Misclassification

1.10. Decision Trees - 图38

where

1.10. Decision Trees - 图39 is the training data in node1.10. Decision Trees - 图40

1.10.7.2. Regression criteria

If the target is a continuous value, then for node

1.10. Decision Trees - 图41,representing a region1.10. Decision Trees - 图42 with1.10. Decision Trees - 图43 observations, commoncriteria to minimise as for determining locations for futuresplits are Mean Squared Error, which minimizes the L2 errorusing mean values at terminal nodes, and Mean Absolute Error, whichminimizes the L1 error using median values at terminal nodes.

Mean Squared Error:

1.10. Decision Trees - 图44

Mean Absolute Error:

1.10. Decision Trees - 图45

where

1.10. Decision Trees - 图46 is the training data in node1.10. Decision Trees - 图47

1.10.8. Minimal Cost-Complexity Pruning

Minimal cost-complexity pruning is an algorithm used to prune a tree to avoidover-fitting, described in Chapter 3 of [BRE]. This algorithm is parameterizedby

1.10. Decision Trees - 图48 known as the complexity parameter. The complexityparameter is used to define the cost-complexity measure,1.10. Decision Trees - 图49 ofa given tree1.10. Decision Trees - 图50:

1.10. Decision Trees - 图51

where

1.10. Decision Trees - 图52 is the number of terminal nodes in1.10. Decision Trees - 图53 and1.10. Decision Trees - 图54is traditionally defined as the total misclassification rate of the terminalnodes. Alternatively, scikit-learn uses the total sample weighted impurity ofthe terminal nodes for1.10. Decision Trees - 图55. As shown above, the impurity of a nodedepends on the criterion. Minimal cost-complexity pruning finds the subtree of1.10. Decision Trees - 图56 that minimizes1.10. Decision Trees - 图57.

The cost complexity measure of a single node is

1.10. Decision Trees - 图58. The branch,1.10. Decision Trees - 图59, is defined to be atree where node1.10. Decision Trees - 图60 is its root. In general, the impurity of a nodeis greater than the sum of impurities of its terminal nodes,1.10. Decision Trees - 图61. However, the cost complexity measure of a node,1.10. Decision Trees - 图62, and its branch,1.10. Decision Trees - 图63, can be equal depending on1.10. Decision Trees - 图64. We define the effective1.10. Decision Trees - 图65 of a node to be thevalue where they are equal,1.10. Decision Trees - 图66 or1.10. Decision Trees - 图67. A non-terminal nodewith the smallest value of1.10. Decision Trees - 图68 is the weakest link and willbe pruned. This process stops when the pruned tree’s minimal1.10. Decision Trees - 图69 is greater than the ccp_alpha parameter.

Examples:

References:

  • BRE
  • L. Breiman, J. Friedman, R. Olshen, and C. Stone. Classificationand Regression Trees. Wadsworth, Belmont, CA, 1984.