diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html
index f172e5af7..3b30bddfe 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -170,26 +182,26 @@ The main idea of decision trees
is to find those descriptive features which contain the most
information regarding the target feature and then split the dataset
along the values of these features such that the target feature values
-for the resulting sub datasets are as pure as possible.
+for the resulting underlying datasets are as pure as possible.
-The descriptive feature which leaves the target feature most purely is said
-to be the most informative one. This process of finding the most
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the most
informative feature is done until we accomplish a stopping criteria
where we then finally end up in so called leaf nodes.
+
+A decision tree is typically divided into a root node, the interior nodes,
+and the final leaf nodes or just leaves. These entities are then connected by so-called branches.
+
The leaf nodes
contain the predictions we will make for new query instances presented
-to our trained model. This is possible since the model has kind of
+to our trained model. This is possible since the model has
learned the underlying structure of the training data and hence can,
given some assumptions, make predictions about the target feature value
(class) of unseen query instances.
-
-A decision tree mainly contains of a root node, interior nodes,
-and leaf nodes which are then connected by branches.
-
@@ -207,7 +219,7 @@ and leaf nodes which are then connected by branches.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html
index d8d12de75..cabb06ae8 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
A typical Decision Tree with its pertinent Jargon, Classification Problem
-Decision trees classify instances by sorting top down.
-
-
-
A leaf provides the classification of the instance.
-
A node specifies a test of some attribute of the instance.
-
A branch corresponds to a possible values an attribute.
-
An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
-
-
-This processis then repeated for the subtree rooted at the new
-node.
+In the figure here we present a decision tree obtained from a classification problem
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html
index 55172e31d..730fc99c9 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
A typical Decision Tree with its pertinent Jargon, Regeression Problem
-In simplified terms, the process of training a decision tree and
-predicting the target features of query instances is as follows:
-
-
-
Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
-
Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
-
Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
-
Show query instances to the tree and run down the tree until we arrive at leaf nodes
-
-
-Then we are essentially done!
+In the figure we present a decision tree obtained from a simple regression problem
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html
index 1f1af5517..05d7cc3c5 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
A leaf provides the classification of a given instance.
+
A node specifies a test of some attribute of the instance.
+
A branch corresponds to a possible values of an attribute.
+
An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html
index b08d98b67..43bf8f88d 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-There are mainly two steps
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
-
We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
-
For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
+
Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
+
Show query instances to the tree and run down the tree until we arrive at leaf nodes
-How do we construct the regions \( R_1,\dots,R_J \)?
-In theory, the regions could have any shape. However, we
-choose to divide the predictor space into high-dimensional rectangles,
-or boxes, for simplicity and for ease of interpretation of the
-resulting predictive model. The goal is to find boxes \( R_1,\dots,R_J \)
-that minimize the MSE, given by
-$$
-\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
-$$
-
-where \( \overline{y}_{R_j} \) is the mean response for the training observations
-within box \( j \).
+Then we are essentially done!
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html
index 18420e466..d02772a03 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-Unfortunately, it is computationally infeasible to consider every
-possible partition of the feature space into \( J \) boxes.
-The common strategy is to take a top-down approach
-
-The approach is top-down because it begins at the top of the tree (all
-observations belong to a single region) and then successively splits
-the predictor space; each split is indicated via two new branches
-further down on the tree. It is greedy because at each step of the
-tree-building process, the best split is made at that particular step,
-rather than looking ahead and picking a split that will lead to a
-better tree in some future step.
+
+
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html
index dbf71764d..b4f46b182 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-In order to implement the recursive binary splitting we start by selecting
-the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
-$$
-\left\{X\vert x_j < s\right\},
-$$
+There are mainly two steps
-and
-$$
-\left\{X\vert x_j \geq s\right\},
-$$
+
+
We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
+
For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
+
-so that we obtain the lowest MSE, that is
-$$
-\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
-$$
+How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
+regions could have any shape. However, we choose to divide the
+predictor space into high-dimensional rectangles, or boxes, for
+simplicity and for ease of interpretation of the resulting predictive
+model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
+MSE, given by
-which we want to minimize by considering all predictors \( x_1,x_2,\dots,x_p \).
-We consider also all possible values of \( s \) for each predictor. These values could be determined by randomly assigned numbers or by starting at the midpoint and then proceed till we find an optimal value.
+$$
+\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
+$$
-For any \( j \) and \( s \), we define the pair of
-half-planes where \( \overline{y}_{R_1} \) is the mean response for the training
-observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean response for the
-training observations in \( R_2(j,s) \).
-
-
-Finding the values of j and s that
-minimize the above equation can be done quite quickly, especially when the number
-of features \( p \) is not too large.
-
-
-Next, we repeat the process, looking
-for the best predictor and best cutpoint in order to split the data
-further so as to minimize the MSE within each of the resulting
-regions. However, this time, instead of splitting the entire predictor
-space, we split one of the two previously identified regions. We now
-have three regions. Again, we look to split one of these three regions
-further, so as to minimize the MSE. The process continues until a
-stopping criterion is reached; for instance, we may continue until no
-region contains more than five observations.
+where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within box \( j \).
@@ -226,7 +219,7 @@ region contains more than five observations.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html
index 2c4cf64af..5726c850b 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-The above procedure is rather straightforward, but leads often to
-overfitting and unnecessarily large and complicated trees. The basic
-idea is to grow a large tree \( T_0 \) and then prune it back in order to
-obtain a subtree. A smaller tree with fewer splits (fewer regions) can
-lead to smaller variance and better interpretation at the cost of a
-little more bias.
+Unfortunately, it is computationally infeasible to consider every
+possible partition of the feature space into \( J \) boxes. The common
+strategy is to take a top-down approach
-The so-called Cost complexity pruning algorithm gives us a
-way to do just this. Rather than considering every possible subtree,
-we consider a sequence of trees indexed by a nonnegative tuning
-parameter \( \alpha \).
+The approach is top-down because it begins at the top of the tree (all
+observations belong to a single region) and then successively splits
+the predictor space; each split is indicated via two new branches
+further down on the tree. It is greedy because at each step of the
+tree-building process, the best split is made at that particular step,
+rather than looking ahead and picking a split that will lead to a
+better tree in some future step.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html
index c39e03d2d..7c6e70eda 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
-$$
-\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
-$$
-
-is as small as possible. Here \( \overline{T} \) is
-the number of terminal nodes of the tree \( T \) , \( R_m \) is the
-rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node.
+
Making a tree
-The tuning parameter \( \alpha \) controls a trade-off between the subtree’s
-com- plexity and its fit to the training data. When \( \alpha = 0 \), then the
-subtree \( T \) will simply equal \( T_0 \),
-because then the above equation just measures the
-training error.
-However, as \( \alpha \) increases, there is a price to pay for
-having a tree with many terminal nodes. The above equation will
-tend to be minimized for a smaller subtree.
+In order to implement the recursive binary splitting we start by selecting
+the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
+$$
+\left\{X\vert x_j < s\right\},
+$$
+
+and
+$$
+\left\{X\vert x_j \geq s\right\},
+$$
+
+so that we obtain the lowest MSE, that is
+$$
+\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
+$$
-It turns out that as we increase \( \alpha \) from zero
-branches get pruned from the tree in a nested and predictable fashion,
-so obtaining the whole sequence of subtrees as a function of \( \alpha \) is
-easy. We can select a value of \( \alpha \) using a validation set or using
-cross-validation. We then return to the full data set and obtain the
-subtree corresponding to \( \alpha \).
+which we want to minimize by considering all predictors
+\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
+each predictor. These values could be determined by randomly assigned
+numbers or by starting at the midpoint and then proceed till we find
+an optimal value.
+
+
+For any \( j \) and \( s \), we define the pair of half-planes where
+\( \overline{y}_{R_1} \) is the mean response for the training
+observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
+response for the training observations in \( R_2(j,s) \).
+
+
+Finding the values of \( j \) and \( s \) that minimize the above equation can be
+done quite quickly, especially when the number of features \( p \) is not
+too large.
+
+
+Next, we repeat the process, looking
+for the best predictor and best cutpoint in order to split the data
+further so as to minimize the MSE within each of the resulting
+regions. However, this time, instead of splitting the entire predictor
+space, we split one of the two previously identified regions. We now
+have three regions. Again, we look to split one of these three regions
+further, so as to minimize the MSE. The process continues until a
+stopping criterion is reached; for instance, we may continue until no
+region contains more than five observations.
@@ -212,7 +244,7 @@ subtree corresponding to \( \alpha \).
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html
index c1b487279..2831c11d5 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
-
Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
-
Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
-
-
-
repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
-
Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
-
Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
-
-
-
Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
-
-
-
+The above procedure is rather straightforward, but leads often to
+overfitting and unnecessarily large and complicated trees. The basic
+idea is to grow a large tree \( T_0 \) and then prune it back in order to
+obtain a subtree. A smaller tree with fewer splits (fewer regions) can
+lead to smaller variance and better interpretation at the cost of a
+little more bias.
+
+The so-called Cost complexity pruning algorithm gives us a
+way to do just this. Rather than considering every possible subtree,
+we consider a sequence of trees indexed by a nonnegative tuning
+parameter \( \alpha \).
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html
index ed8a2a46c..c14cd1bd9 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
+$$
+\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
+$$
+
+is as small as possible. Here \( \overline{T} \) is
+the number of terminal nodes of the tree \( T \) , \( R_m \) is the
+rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node.
-A classification tree is very similar to a regression tree, except
-that it is used to predict a qualitative response rather than a
-quantitative one. Recall that for a regression tree, the predicted
-response for an observation is given by the mean response of the
-training observations that belong to the same terminal node. In
-contrast, for a classification tree, we predict that each observation
-belongs to the most commonly occurring class of training observations
-in the region to which it belongs. In interpreting the results of a
-classification tree, we are often interested not only in the class
-prediction corresponding to a particular terminal node region, but
-also in the class proportions among the training observations that
-fall into that region.
+The tuning parameter \( \alpha \) controls a trade-off between the subtree’s
+com- plexity and its fit to the training data. When \( \alpha = 0 \), then the
+subtree \( T \) will simply equal \( T_0 \),
+because then the above equation just measures the
+training error.
+However, as \( \alpha \) increases, there is a price to pay for
+having a tree with many terminal nodes. The above equation will
+tend to be minimized for a smaller subtree.
+
+
+It turns out that as we increase \( \alpha \) from zero
+branches get pruned from the tree in a nested and predictable fashion,
+so obtaining the whole sequence of subtrees as a function of \( \alpha \) is
+easy. We can select a value of \( \alpha \) using a validation set or using
+cross-validation. We then return to the full data set and obtain the
+subtree corresponding to \( \alpha \).
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html
index e2a5685c5..672b5a2fc 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-The task of growing a
-classification tree is quite similar to the task of growing a
-regression tree. Just as in the regression setting, we use recursive
-binary splitting to grow a classification tree. However, in the
-classification setting, the MSE cannot be used as a criterion for making
-the binary splits. A natural alternative to MSE is the classification
-error rate. Since we plan to assign an observation in a given region
-to the most commonly occurring error rate class of training
-observations in that region, the classification error rate is simply
-the fraction of the training observations in that region that do not
-belong to the most common class.
+
+
+
+
+
+
Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
+
Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
+
Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
+
+
+
repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
+
Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
+
Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
+
+
+
Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
+
+
+
-
-When building a classification tree, either the Gini index or the
-entropy are typically used to evaluate the quality of a particular
-split, since these two approaches are more sensitive to node purity
-than is the classification error rate.
@@ -206,7 +221,7 @@ than is the classification error rate.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html
index 6e3252297..8be931c10 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-If our targets are the outcome of a classification process that takes for example
-\( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node.
-
-
-We define a PDF \( p_{mk} \) that represents the number of observations of a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent this likelihood function in terms of the proportion \( I(y_i=k) \) of observations of this class in the region \( R_m \) as
-$$
-p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
-$$
-
-
-We let \( p_{mk} \) represent the majority class of observations in region \( m \). The three most common ways of splitting a node are given by
-
-
-
-$$
-s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
-$$
+A classification tree is very similar to a regression tree, except
+that it is used to predict a qualitative response rather than a
+quantitative one. Recall that for a regression tree, the predicted
+response for an observation is given by the mean response of the
+training observations that belong to the same terminal node. In
+contrast, for a classification tree, we predict that each observation
+belongs to the most commonly occurring class of training observations
+in the region to which it belongs. In interpreting the results of a
+classification tree, we are often interested not only in the class
+prediction corresponding to a particular terminal node region, but
+also in the class proportions among the training observations that
+fall into that region.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html
index 32319f7d4..0c50d4fb1 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-ID3, learns decision trees by constructing
-them topdown, beginning with the question which attribute should be tested at the root of the tree?
-
-
-
Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
-
The best attribute is selected and used as the test at the root node of the tree.
-
A descendant of the root node is then created for each possible value of this attribute.
-
Training examples are sorted to the appropriate descendant node.
-
The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
-
This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
-
-
-The ID3 algorithm selects, which attribute to test at each node in the
-tree.
+The task of growing a
+classification tree is quite similar to the task of growing a
+regression tree. Just as in the regression setting, we use recursive
+binary splitting to grow a classification tree. However, in the
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+error rate. Since we plan to assign an observation in a given region
+to the most commonly occurring error rate class of training
+observations in that region, the classification error rate is simply
+the fraction of the training observations in that region that do not
+belong to the most common class.
-We would like to select the attribute that is most useful for classifying
-examples.
-
-
-What is a good quantitative measure of the worth of an attribute?
-
-
-Information gain measures how well a given attribute separates the
-training examples according to their target classification.
-
-
-The ID3 algorithm uses this information gain measure to select among the candidate
-attributes at each step while growing the tree.
+When building a classification tree, either the Gini index or the
+entropy are typically used to evaluate the quality of a particular
+split, since these two approaches are more sensitive to node purity
+than is the classification error rate.
@@ -218,7 +218,7 @@ attributes at each step while growing the tree.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html
index 6fbdf006c..1bd9c6979 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-more text to come here, material presented during lecture Friday Oct 25.
+If our targets are the outcome of a classification process that takes
+for example \( k=1,2,\dots,K \) values, the only thing we need to think of
+is to set up the splitting criteria for each node.
+
+
+We define a PDF \( p_{mk} \) that represents the number of observations of
+a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
+this likelihood function in terms of the proportion \( I(y_i=k) \) of
+observations of this class in the region \( R_m \) as
+
+$$
+p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
+$$
+
+
+We let \( p_{mk} \) represent the majority class of observations in region
+\( m \). The three most common ways of splitting a node are given by
+
+
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html
index d2872aa0e..b2914688d 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
+
The best attribute is selected and used as the test at the root node of the tree.
+
A descendant of the root node is then created for each possible value of this attribute.
+
Training examples are sorted to the appropriate descendant node.
+
The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
+
This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
+
-# Load the data
-cancer = load_breast_cancer()
+The ID3 algorithm selects, which attribute to test at each node in the
+tree.
+
+
+We would like to select the attribute that is most useful for classifying
+examples.
+
+
+What is a good quantitative measure of the worth of an attribute?
+
+
+Information gain measures how well a given attribute separates the
+training examples according to their target classification.
+
+
+The ID3 algorithm uses this information gain measure to select among the candidate
+attributes at each step while growing the tree.
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-print(X_train.shape)
-print(X_test.shape)
-# Logistic Regression
-logreg = LogisticRegression(solver='lbfgs')
-logreg.fit(X_train, y_train)
-print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
-# Support vector machine
-svm = SVC(gamma='auto', C=100)
-svm.fit(X_train, y_train)
-print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
-# Decision Trees
-deep_tree_clf = DecisionTreeClassifier(max_depth=None)
-deep_tree_clf.fit(X_train, y_train)
-print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
-#now scale the data
-fromsklearn.preprocessingimport StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-# Logistic Regression
-logreg.fit(X_train_scaled, y_train)
-print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
-# Support Vector Machine
-svm.fit(X_train_scaled, y_train)
-print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
-# Decision Trees
-deep_tree_clf.fit(X_train_scaled, y_train)
-print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
-
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html
index b3376b407..a762e5c1b 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html
index 3f1a352e8..8a5f891fe 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html
index 1abf03cbe..021d0b636 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html
index 261df3269..39d29c531 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html
index ebac943c4..077ed8885 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
-
Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
-
No feature normalization needed
-
Tree models can handle both continuous and categorical data (Classification and Regression Trees)
-
Can model nonlinear relationships
-
Can model interactions between the different descriptive features
-
Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
-
+
+
# Quadratic training set + noise
+np.random.seed(42)
+m =200
+X = np.random.rand(m, 1)
+y =4* (X -0.5) **2
+y = y + np.random.randn(m, 1) /10
+
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html
index c3e65aa61..d692c2d6e 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
-
If continuous features are used the tree may become quite large and hence less interpretable
-
Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
-
Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
-
Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
-
If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
-
Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
-
+
+
fromsklearn.treeimport DecisionTreeRegressor
-However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+defplot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html
index ed701c94f..fdd169e96 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-The plain decision trees suffer from high
-variance. This means that if we split the training data into two parts
-at random, and fit a decision tree to both halves, the results that we
-get could be quite different. In contrast, a procedure with low
-variance will yield similar results if applied repeatedly to distinct
-data sets; linear regression tends to have low variance, if the ratio
-of \( n \) to \( p \) is moderately large.
+
+
White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+
Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+
No feature normalization needed
+
Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+
Can model nonlinear relationships
+
Can model interactions between the different descriptive features
+
Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+
-
-Bootstrap aggregation, or just bagging, is a
-general-purpose procedure for reducing the variance of a statistical
-learning method.
-
-
-Bagging typically results in improved accuracy
-over prediction using a single tree. Unfortunately, however, it can be
-difficult to interpret the resulting model. Recall that one of the
-advantages of decision trees is the attractive and easily interpreted
-diagram that results.
-
-
-However, when we bag a large number of trees, it is no longer
-possible to represent the resulting statistical learning procedure
-using a single tree, and it is no longer clear which variables are
-most important to the procedure. Thus, bagging improves prediction
-accuracy at the expense of interpretability. Although the collection
-of bagged trees is much more difficult to interpret than a single
-tree, one can obtain an overall summary of the importance of each
-predictor using the MSE (for bagging regression trees) or the Gini
-index (for bagging classification trees). In the case of bagging
-regression trees, we can record the total amount that the MSE is
-decreased due to splits over a given predictor, averaged over all \( B \) possible
-trees. A large value indicates an important predictor. Similarly, in
-the context of bagging classification trees, we can add up the total
-amount that the Gini index is decreased by splits over a given
-predictor, averaged over all \( B \) trees.
-
-
@@ -222,6 +205,8 @@ predictor, averaged over all \( B \) trees.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html
index 094e5e5c5..86deef56b 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+
If continuous features are used the tree may become quite large and hence less interpretable
+
Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+
Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+
Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+
If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+
Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+
+
+However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
-
-
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html
index a41f45ab6..497d3fe62 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
-Random forests provide an improvement over bagged trees by way of a
-small tweak that decorrelates the trees.
+The plain decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of \( n \) to \( p \) is moderately large.
-As in bagging, we build a
-number of decision trees on bootstrapped training samples. But when
-building these decision trees, each time a split in a tree is
-considered, a random sample of \( m \) predictors is chosen as split
-candidates from the full set of \( p \) predictors. The split is allowed to
-use only one of those \( m \) predictors.
+Bootstrap aggregation, or just bagging, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
-A fresh sample of \( m \) predictors is
-taken at each split, and typically we choose
-$$
-m\approx \sqrt{p}.
-$$
-
-In building a random forest, at
-each split in the tree, the algorithm is not even allowed to consider
-a majority of the available predictors.
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
-The reason for this is rather clever. Suppose that there is one very
-strong predictor in the data set, along with a number of other
-moderately strong predictors. Then in the collection of bagged
-variable importance random forest trees, most or all of the trees will
-use this strong predictor in the top split. Consequently, all of the
-bagged trees will look quite similar to each other. Hence the
-predictions from the bagged trees will be highly correlated.
-Unfortunately, averaging many highly correlated quantities does not lead
-to as large of a reduction in variance as averaging many uncorrelated
-quanti- ties. In particular, this means that bagging will not lead to
-a substantial reduction in variance over a single tree in this
-setting.
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all \( B \) possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all \( B \) trees.
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html
index 2371b947f..1a7a4d4ff 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
fromsklearn.ensembleimport RandomForestClassifier
-fromsklearn.preprocessingimport LabelEncoder
-fromsklearn.model_selectionimport cross_validate
-# Data set not specificied
-X = dataset.XXX
-Y = dataset.YYY
-#Instantiate the model with 100 trees and entropy as splitting criteria
-Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
-#Cross validation
-accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
+
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html
index 7fd7f2ec4..409250a3e 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of \( m \) predictors is chosen as split
+candidates from the full set of \( p \) predictors. The split is allowed to
+use only one of those \( m \) predictors.
-
-
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
-
-
fromsklearn.metricsimport accuracy_score
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html
index 935838dd3..d009c481c 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
fromsklearn.ensembleimport RandomForestClassifier
+fromsklearn.preprocessingimport LabelEncoder
+fromsklearn.model_selectionimport cross_validate
+# Data set not specificied
+X = dataset.XXX
+Y = dataset.YYY
+#Instantiate the model with 100 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html
index 861de541c..f5146b5a8 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html
index 99821f748..5c6a146f2 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html
index a61857c62..9b4825d3c 100644
--- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html
+++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html
@@ -6,9 +6,10 @@ Automatically generated HTML file from DocOnce source
-
+
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -41,42 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-bs.html b/doc/pub/DecisionTrees/html/DecisionTrees-bs.html
index 60b829003..ceb0e0248 100644
--- a/doc/pub/DecisionTrees/html/DecisionTrees-bs.html
+++ b/doc/pub/DecisionTrees/html/DecisionTrees-bs.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -42,41 +42,51 @@ Automatically generated HTML file from DocOnce source
@@ -106,7 +116,7 @@ MathJax.Hub.Config({
- Data Analysis and Machine Learning: Trees, forests and all that
+ Data Analysis and Machine Learning: From Decision Trees to Forests and all that
diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html b/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html
index 7cf28ce07..cf3dc3ebb 100644
--- a/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html
+++ b/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html
@@ -3,9 +3,9 @@
-
+
-Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -132,7 +132,7 @@ MathJax.Hub.Config({
-
Data Analysis and Machine Learning: Trees, forests and all that
+
Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -148,7 +148,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Oct 25, 2019
+
Oct 26, 2019
@@ -170,49 +170,65 @@ The main idea of decision trees
is to find those descriptive features which contain the most
information regarding the target feature and then split the dataset
along the values of these features such that the target feature values
-for the resulting sub datasets are as pure as possible.
+for the resulting underlying datasets are as pure as possible.
-The descriptive feature which leaves the target feature most purely is said
-to be the most informative one. This process of finding the most
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the most
informative feature is done until we accomplish a stopping criteria
where we then finally end up in so called leaf nodes.
+
+A decision tree is typically divided into a root node, the interior nodes,
+and the final leaf nodes or just leaves. These entities are then connected by so-called branches.
+
The leaf nodes
contain the predictions we will make for new query instances presented
-to our trained model. This is possible since the model has kind of
+to our trained model. This is possible since the model has
learned the underlying structure of the training data and hence can,
given some assumptions, make predictions about the target feature value
(class) of unseen query instances.
-
-
-A decision tree mainly contains of a root node, interior nodes,
-and leaf nodes which are then connected by branches.
-
General Features
+
A typical Decision Tree with its pertinent Jargon, Classification Problem
-Decision trees classify instances by sorting top down.
+In the figure here we present a decision tree obtained from a classification problem
+
+
+
+
+
A typical Decision Tree with its pertinent Jargon, Regeression Problem
+
+
+In the figure we present a decision tree obtained from a simple regression problem
+
+
+
+
+
General Features
+
+
+The overarching approach to decision trees is a top-down approach.
-
A leaf provides the classification of the instance.
+
A leaf provides the classification of a given instance.
A node specifies a test of some attribute of the instance.
-
A branch corresponds to a possible values an attribute.
+
A branch corresponds to a possible values of an attribute.
An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
-This processis then repeated for the subtree rooted at the new
+This process is then repeated for the subtree rooted at the new
node.
-
How do we set it up?
+
How do we set it up?
In simplified terms, the process of training a decision tree and
@@ -231,7 +247,7 @@ Then we are essentially done!
-
Decision trees and Regression
+
Decision trees and Regression
@@ -328,7 +344,7 @@ plt.show()
-
Building a tree, regression
+
Building a tree, regression
There are mainly two steps
@@ -340,30 +356,32 @@ There are mainly two steps
-How do we construct the regions \( R_1,\dots,R_J \)?
-In theory, the regions could have any shape. However, we
-choose to divide the predictor space into high-dimensional rectangles,
-or boxes, for simplicity and for ease of interpretation of the
-resulting predictive model. The goal is to find boxes \( R_1,\dots,R_J \)
-that minimize the MSE, given by
+How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
+regions could have any shape. However, we choose to divide the
+predictor space into high-dimensional rectangles, or boxes, for
+simplicity and for ease of interpretation of the resulting predictive
+model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
+MSE, given by
+
where \( \overline{y}_{R_j} \) is the mean response for the training observations
within box \( j \).
-
A top-down approach, recursive binary splitting
+
A top-down approach, recursive binary splitting
Unfortunately, it is computationally infeasible to consider every
-possible partition of the feature space into \( J \) boxes.
-The common strategy is to take a top-down approach
+possible partition of the feature space into \( J \) boxes. The common
+strategy is to take a top-down approach
The approach is top-down because it begins at the top of the tree (all
@@ -377,7 +395,7 @@ better tree in some future step.
-
Making a tree
+
Making a tree
In order to implement the recursive binary splitting we start by selecting
@@ -402,19 +420,23 @@ $$
$$
-which we want to minimize by considering all predictors \( x_1,x_2,\dots,x_p \).
-We consider also all possible values of \( s \) for each predictor. These values could be determined by randomly assigned numbers or by starting at the midpoint and then proceed till we find an optimal value.
+
+which we want to minimize by considering all predictors
+\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
+each predictor. These values could be determined by randomly assigned
+numbers or by starting at the midpoint and then proceed till we find
+an optimal value.
-For any \( j \) and \( s \), we define the pair of
-half-planes where \( \overline{y}_{R_1} \) is the mean response for the training
-observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean response for the
-training observations in \( R_2(j,s) \).
+For any \( j \) and \( s \), we define the pair of half-planes where
+\( \overline{y}_{R_1} \) is the mean response for the training
+observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
+response for the training observations in \( R_2(j,s) \).
-Finding the values of j and s that
-minimize the above equation can be done quite quickly, especially when the number
-of features \( p \) is not too large.
+Finding the values of \( j \) and \( s \) that minimize the above equation can be
+done quite quickly, especially when the number of features \( p \) is not
+too large.
Next, we repeat the process, looking
@@ -430,7 +452,7 @@ region contains more than five observations.
-
Pruning the tree
+
Pruning the tree
The above procedure is rather straightforward, but leads often to
@@ -449,7 +471,7 @@ parameter \( \alpha \).
-
Cost complexity pruning
+
Cost complexity pruning
For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
A classification tree is very similar to a regression tree, except
@@ -526,7 +548,7 @@ fall into that region.
-
Growing a classification tree
+
Growing a classification tree
The task of growing a
@@ -550,14 +572,19 @@ than is the classification error rate.
-
Classification tree, how to split nodes
+
Classification tree, how to split nodes
-If our targets are the outcome of a classification process that takes for example
-\( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node.
+If our targets are the outcome of a classification process that takes
+for example \( k=1,2,\dots,K \) values, the only thing we need to think of
+is to set up the splitting criteria for each node.
-We define a PDF \( p_{mk} \) that represents the number of observations of a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent this likelihood function in terms of the proportion \( I(y_i=k) \) of observations of this class in the region \( R_m \) as
+We define a PDF \( p_{mk} \) that represents the number of observations of
+a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
+this likelihood function in terms of the proportion \( I(y_i=k) \) of
+observations of this class in the region \( R_m \) as
+
-We let \( p_{mk} \) represent the majority class of observations in region \( m \). The three most common ways of splitting a node are given by
+We let \( p_{mk} \) represent the majority class of observations in region
+\( m \). The three most common ways of splitting a node are given by
Misclassification error
@@ -599,7 +627,7 @@ $$
-
Entropy and the ID3 algorithm
+
Entropy and the ID3 algorithm
ID3, learns decision trees by constructing
@@ -636,7 +664,7 @@ attributes at each step while growing the tree.
-
Implementing the ID3 Algorithm
+
Implementing the ID3 Algorithm
more text to come here, material presented during lecture Friday Oct 25.
@@ -644,7 +672,7 @@ attributes at each step while growing the tree.
-
White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
@@ -913,7 +941,7 @@ plt.show()
-
Disadvantages
+
Disadvantages
Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
@@ -931,7 +959,7 @@ However, by aggregating many decision trees, using methods like bagging, random
-
Bagging
+
Bagging
The plain decision trees suffer from high
@@ -974,7 +1002,7 @@ predictor, averaged over all \( B \) trees.
-
Simple example, head or tail
+
Simple example, head or tail
@@ -995,7 +1023,7 @@ plt.show()
-
Random forests
+
Random forests
Random forests provide an improvement over bagged trees by way of a
@@ -1011,13 +1039,15 @@ use only one of those \( m \) predictors.
A fresh sample of \( m \) predictors is
-taken at each split, and typically we choose
+taken at each split, and typically we choose
+
$$
m\approx \sqrt{p}.
$$
+
In building a random forest, at
each split in the tree, the algorithm is not even allowed to consider
a majority of the available predictors.
@@ -1029,17 +1059,17 @@ moderately strong predictors. Then in the collection of bagged
variable importance random forest trees, most or all of the trees will
use this strong predictor in the top split. Consequently, all of the
bagged trees will look quite similar to each other. Hence the
-predictions from the bagged trees will be highly correlated.
-Unfortunately, averaging many highly correlated quantities does not lead
-to as large of a reduction in variance as averaging many uncorrelated
-quanti- ties. In particular, this means that bagging will not lead to
-a substantial reduction in variance over a single tree in this
-setting.
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
-
A simple scikit-learn example
+
A simple scikit-learn example
@@ -1058,7 +1088,7 @@ accuracy = cross_validate(Random_Forest_model,X,Y,cv=Please, not the moons again!
+
More material to come here.
diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html b/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html
index 1d7217057..f6b84cb41 100644
--- a/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html
+++ b/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-
Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -62,41 +62,51 @@ div { text-align: justify; text-justify: inter-word; }
@@ -122,7 +132,7 @@ MathJax.Hub.Config({
-
Data Analysis and Machine Learning: Trees, forests and all that
+
Data Analysis and Machine Learning: From Decision Trees to Forests and all that
@@ -138,7 +148,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Oct 25, 2019
+
Oct 26, 2019
@@ -154,48 +164,64 @@ The main idea of decision trees
is to find those descriptive features which contain the most
information regarding the target feature and then split the dataset
along the values of these features such that the target feature values
-for the resulting sub datasets are as pure as possible.
+for the resulting underlying datasets are as pure as possible.
-The descriptive feature which leaves the target feature most purely is said
-to be the most informative one. This process of finding the most
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the most
informative feature is done until we accomplish a stopping criteria
where we then finally end up in so called leaf nodes.
+
+A decision tree is typically divided into a root node, the interior nodes,
+and the final leaf nodes or just leaves. These entities are then connected by so-called branches.
+
The leaf nodes
contain the predictions we will make for new query instances presented
-to our trained model. This is possible since the model has kind of
+to our trained model. This is possible since the model has
learned the underlying structure of the training data and hence can,
given some assumptions, make predictions about the target feature value
(class) of unseen query instances.
-A decision tree mainly contains of a root node, interior nodes,
-and leaf nodes which are then connected by branches.
+
+
+
A typical Decision Tree with its pertinent Jargon, Classification Problem
+
+
+In the figure here we present a decision tree obtained from a classification problem
-
General Features
+
A typical Decision Tree with its pertinent Jargon, Regeression Problem
-Decision trees classify instances by sorting top down.
+In the figure we present a decision tree obtained from a simple regression problem
+
+
+
+
+
General Features
+
+
+The overarching approach to decision trees is a top-down approach.
-
A leaf provides the classification of the instance.
+
A leaf provides the classification of a given instance.
A node specifies a test of some attribute of the instance.
-
A branch corresponds to a possible values an attribute.
+
A branch corresponds to a possible values of an attribute.
An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
-This processis then repeated for the subtree rooted at the new
+This process is then repeated for the subtree rooted at the new
node.
-
How do we set it up?
+
How do we set it up?
In simplified terms, the process of training a decision tree and
@@ -213,7 +239,7 @@ Then we are essentially done!
-
Decision trees and Regression
+
Decision trees and Regression
@@ -309,7 +335,7 @@ plt.show()
-
Building a tree, regression
+
Building a tree, regression
There are mainly two steps
@@ -319,28 +345,30 @@ There are mainly two steps
For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
-How do we construct the regions \( R_1,\dots,R_J \)?
-In theory, the regions could have any shape. However, we
-choose to divide the predictor space into high-dimensional rectangles,
-or boxes, for simplicity and for ease of interpretation of the
-resulting predictive model. The goal is to find boxes \( R_1,\dots,R_J \)
-that minimize the MSE, given by
+How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
+regions could have any shape. However, we choose to divide the
+predictor space into high-dimensional rectangles, or boxes, for
+simplicity and for ease of interpretation of the resulting predictive
+model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
+MSE, given by
+
$$
\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
$$
+
where \( \overline{y}_{R_j} \) is the mean response for the training observations
within box \( j \).
-
A top-down approach, recursive binary splitting
+
A top-down approach, recursive binary splitting
Unfortunately, it is computationally infeasible to consider every
-possible partition of the feature space into \( J \) boxes.
-The common strategy is to take a top-down approach
+possible partition of the feature space into \( J \) boxes. The common
+strategy is to take a top-down approach
The approach is top-down because it begins at the top of the tree (all
@@ -354,7 +382,7 @@ better tree in some future step.
-
Making a tree
+
Making a tree
In order to implement the recursive binary splitting we start by selecting
@@ -373,19 +401,23 @@ $$
\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
$$
-which we want to minimize by considering all predictors \( x_1,x_2,\dots,x_p \).
-We consider also all possible values of \( s \) for each predictor. These values could be determined by randomly assigned numbers or by starting at the midpoint and then proceed till we find an optimal value.
+
+which we want to minimize by considering all predictors
+\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
+each predictor. These values could be determined by randomly assigned
+numbers or by starting at the midpoint and then proceed till we find
+an optimal value.
-For any \( j \) and \( s \), we define the pair of
-half-planes where \( \overline{y}_{R_1} \) is the mean response for the training
-observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean response for the
-training observations in \( R_2(j,s) \).
+For any \( j \) and \( s \), we define the pair of half-planes where
+\( \overline{y}_{R_1} \) is the mean response for the training
+observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
+response for the training observations in \( R_2(j,s) \).
-Finding the values of j and s that
-minimize the above equation can be done quite quickly, especially when the number
-of features \( p \) is not too large.
+Finding the values of \( j \) and \( s \) that minimize the above equation can be
+done quite quickly, especially when the number of features \( p \) is not
+too large.
Next, we repeat the process, looking
@@ -401,7 +433,7 @@ region contains more than five observations.
-
Pruning the tree
+
Pruning the tree
The above procedure is rather straightforward, but leads often to
@@ -420,7 +452,7 @@ parameter \( \alpha \).
-
Cost complexity pruning
+
Cost complexity pruning
For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
$$
\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
@@ -451,7 +483,7 @@ subtree corresponding to \( \alpha \).
-
Schematic Regression Procedure
+
Schematic Regression Procedure
@@ -477,7 +509,7 @@ subtree corresponding to \( \alpha \).
-
A Classification Tree
+
A Classification Tree
A classification tree is very similar to a regression tree, except
@@ -496,7 +528,7 @@ fall into that region.
-
Growing a classification tree
+
Growing a classification tree
The task of growing a
@@ -520,20 +552,26 @@ than is the classification error rate.
-
Classification tree, how to split nodes
+
Classification tree, how to split nodes
-If our targets are the outcome of a classification process that takes for example
-\( k=1,2,\dots,K \) values, the only thing we need to think of is to set up the splitting criteria for each node.
+If our targets are the outcome of a classification process that takes
+for example \( k=1,2,\dots,K \) values, the only thing we need to think of
+is to set up the splitting criteria for each node.
-We define a PDF \( p_{mk} \) that represents the number of observations of a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent this likelihood function in terms of the proportion \( I(y_i=k) \) of observations of this class in the region \( R_m \) as
+We define a PDF \( p_{mk} \) that represents the number of observations of
+a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
+this likelihood function in terms of the proportion \( I(y_i=k) \) of
+observations of this class in the region \( R_m \) as
+
$$
p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
$$
-We let \( p_{mk} \) represent the majority class of observations in region \( m \). The three most common ways of splitting a node are given by
+We let \( p_{mk} \) represent the majority class of observations in region
+\( m \). The three most common ways of splitting a node are given by
Misclassification error
@@ -564,7 +602,7 @@ $$
-
Entropy and the ID3 algorithm
+
Entropy and the ID3 algorithm
ID3, learns decision trees by constructing
@@ -600,7 +638,7 @@ attributes at each step while growing the tree.
-
Implementing the ID3 Algorithm
+
Implementing the ID3 Algorithm
more text to come here, material presented during lecture Friday Oct 25.
@@ -608,7 +646,7 @@ attributes at each step while growing the tree.
White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
@@ -871,7 +909,7 @@ plt.show()
-
Disadvantages
+
Disadvantages
Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
@@ -888,7 +926,7 @@ However, by aggregating many decision trees, using methods like bagging, random
-
Bagging
+
Bagging
The plain decision trees suffer from high
@@ -931,7 +969,7 @@ predictor, averaged over all \( B \) trees.
-
Simple example, head or tail
+
Simple example, head or tail
@@ -951,7 +989,7 @@ plt.show()
-
Random forests
+
Random forests
Random forests provide an improvement over bagged trees by way of a
@@ -968,10 +1006,12 @@ use only one of those \( m \) predictors.
A fresh sample of \( m \) predictors is
taken at each split, and typically we choose
+
$$
m\approx \sqrt{p}.
$$
+
In building a random forest, at
each split in the tree, the algorithm is not even allowed to consider
a majority of the available predictors.
@@ -983,17 +1023,17 @@ moderately strong predictors. Then in the collection of bagged
variable importance random forest trees, most or all of the trees will
use this strong predictor in the top split. Consequently, all of the
bagged trees will look quite similar to each other. Hence the
-predictions from the bagged trees will be highly correlated.
-Unfortunately, averaging many highly correlated quantities does not lead
-to as large of a reduction in variance as averaging many uncorrelated
-quanti- ties. In particular, this means that bagging will not lead to
-a substantial reduction in variance over a single tree in this
-setting.
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
-
A simple scikit-learn example
+
A simple scikit-learn example
@@ -1011,7 +1051,7 @@ accuracy = cross_validate(Random_Forest_model,X,Y,cv=Please, not the moons again!
+
diff --git a/doc/pub/DecisionTrees/html/DecisionTrees.html b/doc/pub/DecisionTrees/html/DecisionTrees.html
index 99778a107..1472b9062 100644
--- a/doc/pub/DecisionTrees/html/DecisionTrees.html
+++ b/doc/pub/DecisionTrees/html/DecisionTrees.html
@@ -7,9 +7,9 @@ Automatically generated HTML file from DocOnce source
-
+
-
Data Analysis and Machine Learning: Trees, forests and all that
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/src/DecisionTrees/DecisionTrees-minted.pdf b/doc/src/DecisionTrees/DecisionTrees-minted.pdf
new file mode 100644
index 000000000..9f633fb4e
Binary files /dev/null and b/doc/src/DecisionTrees/DecisionTrees-minted.pdf differ
diff --git a/doc/src/DecisionTrees/DecisionTrees-plain-minted.tex b/doc/src/DecisionTrees/DecisionTrees-plain-minted.tex
new file mode 100644
index 000000000..f125241e4
--- /dev/null
+++ b/doc/src/DecisionTrees/DecisionTrees-plain-minted.tex
@@ -0,0 +1,1130 @@
+%%
+%% Automatically generated file from DocOnce source
+%% (https://github.com/hplgit/doconce/)
+%%
+%%
+
+
+%-------------------- begin preamble ----------------------
+
+\documentclass[%
+oneside, % oneside: electronic viewing, twoside: printing
+final, % draft: marks overfull hboxes, figures with paths
+10pt]{article}
+
+\listfiles % print all files needed to compile this document
+
+\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}
+\usepackage[table]{xcolor}
+\usepackage{bm,ltablex,microtype}
+
+\usepackage[pdftex]{graphicx}
+
+\usepackage{fancyvrb} % packages needed for verbatim environments
+\usepackage{minted}
+\usemintedstyle{default}
+
+\usepackage[T1]{fontenc}
+%\usepackage[latin1]{inputenc}
+\usepackage{ucs}
+\usepackage[utf8x]{inputenc}
+
+\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern
+
+% Hyperlinks in PDF:
+\definecolor{linkcolor}{rgb}{0,0,0.4}
+\usepackage{hyperref}
+\hypersetup{
+ breaklinks=true,
+ colorlinks=true,
+ linkcolor=linkcolor,
+ urlcolor=linkcolor,
+ citecolor=black,
+ filecolor=black,
+ %filecolor=blue,
+ pdfmenubar=true,
+ pdftoolbar=true,
+ bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC
+ }
+%\hyperbaseurl{} % hyperlinks are relative to this root
+
+\setcounter{tocdepth}{2} % levels in table of contents
+
+% --- fancyhdr package for fancy headers ---
+\usepackage{fancyhdr}
+\fancyhf{} % sets both header and footer to nothing
+\renewcommand{\headrulewidth}{0pt}
+\fancyfoot[LE,RO]{\thepage}
+% Ensure copyright on titlepage (article style) and chapter pages (book style)
+\fancypagestyle{plain}{
+ \fancyhf{}
+ \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}}
+% \renewcommand{\footrulewidth}{0mm}
+ \renewcommand{\headrulewidth}{0mm}
+}
+% Ensure copyright on titlepages with \thispagestyle{empty}
+\fancypagestyle{empty}{
+ \fancyhf{}
+ \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}}
+ \renewcommand{\footrulewidth}{0mm}
+ \renewcommand{\headrulewidth}{0mm}
+}
+
+\pagestyle{fancy}
+
+
+\usepackage[framemethod=TikZ]{mdframed}
+
+% --- begin definitions of admonition environments ---
+
+% --- end of definitions of admonition environments ---
+
+% prevent orhpans and widows
+\clubpenalty = 10000
+\widowpenalty = 10000
+
+% --- end of standard preamble for documents ---
+
+
+% insert custom LaTeX commands...
+
+\raggedbottom
+\makeindex
+\usepackage[totoc]{idxlayout} % for index in the toc
+\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc
+
+%-------------------- end preamble ----------------------
+
+\begin{document}
+
+% matching end for #ifdef PREAMBLE
+
+\newcommand{\exercisesection}[1]{\subsection*{#1}}
+
+
+% ------------------- main content ----------------------
+
+
+
+% ----------------- title -------------------------
+
+\thispagestyle{empty}
+
+\begin{center}
+{\LARGE\bf
+\begin{spacing}{1.25}
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+\end{spacing}
+}
+\end{center}
+
+% ----------------- author(s) -------------------------
+
+\begin{center}
+{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm]
+\end{center}
+
+\begin{center}
+% List of all institutions:
+\centerline{{\small ${}^1$Department of Physics, University of Oslo}}
+\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}}
+\end{center}
+
+% ----------------- end author(s) -------------------------
+
+% --- begin date ---
+\begin{center}
+Oct 26, 2019
+\end{center}
+% --- end date ---
+
+\vspace{1cm}
+
+
+% !split
+\subsection*{Decision trees, overarching aims}
+
+
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+\textbf{information} regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the \textbf{most
+informative} feature is done until we accomplish a stopping criteria
+where we then finally end up in so called \textbf{leaf nodes}.
+
+A decision tree is typically divided into a \textbf{root node}, the \textbf{interior nodes},
+and the final \textbf{leaf nodes} or just \textbf{leaves}. These entities are then connected by so-called \textbf{branches}.
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+% !split
+\subsection*{A typical Decision Tree with its pertinent Jargon, Classification Problem}
+
+In the figure here we present a decision tree obtained from a classification problem
+
+
+% !split
+\subsection*{A typical Decision Tree with its pertinent Jargon, Regeression Problem}
+
+In the figure we present a decision tree obtained from a simple regression problem
+
+
+% !split
+\subsection*{General Features}
+
+The overarching approach to decision trees is a top-down approach.
+
+\begin{itemize}
+\item A leaf provides the classification of a given instance.
+
+\item A node specifies a test of some attribute of the instance.
+
+\item A branch corresponds to a possible values of an attribute.
+
+\item An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+\end{itemize}
+
+\noindent
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+% !split
+\subsection*{How do we set it up?}
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+\begin{enumerate}
+\item Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
+\item Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
+\item Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the \emph{predictions} we want to make for new query instances
+
+\item Show query instances to the tree and run down the tree until we arrive at leaf nodes
+\end{enumerate}
+
+\noindent
+Then we are essentially done!
+
+
+
+
+
+% !split
+\subsection*{Decision trees and Regression}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x 0).astype(np.float32) * 2
+
+angle = np.pi / 4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+\end{minted}
+
+% !split
+\subsection*{Regression trees}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+\end{minted}
+
+% !split
+\subsection*{Final regressor code}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+\end{minted}
+
+
+
+% !split
+\subsection*{Pros and cons of trees, pros}
+
+\begin{itemize}
+\item White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+
+\item Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+
+\item No feature normalization needed
+
+\item Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+
+\item Can model nonlinear relationships
+
+\item Can model interactions between the different descriptive features
+
+\item Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+\end{itemize}
+
+\noindent
+% !split
+\subsection*{Disadvantages}
+
+\begin{itemize}
+\item Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+
+\item If continuous features are used the tree may become quite large and hence less interpretable
+
+\item Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+
+\item Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+
+\item Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+
+\item If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+
+\item Features with many levels may be preferred over features with less levels since for them it is \emph{more easy} to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+\end{itemize}
+
+\noindent
+However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
+
+% !split
+\subsection*{Bagging}
+
+The \textbf{plain} decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of $n$ to $p$ is moderately large.
+
+\textbf{Bootstrap aggregation}, or just \textbf{bagging}, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all $B$ possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all $B$ trees.
+
+% !split
+\subsection*{Simple example, head or tail}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+plt.show()
+
+\end{minted}
+
+
+% !split
+\subsection*{Random forests}
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of $m$ predictors is chosen as split
+candidates from the full set of $p$ predictors. The split is allowed to
+use only one of those $m$ predictors.
+
+A fresh sample of $m$ predictors is
+taken at each split, and typically we choose
+
+\[
+m\approx \sqrt{p}.
+\]
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+% !split
+\subsection*{A simple scikit-learn example}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+X = dataset.XXX
+Y = dataset.YYY
+#Instantiate the model with 100 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
+\end{minted}
+
+% !split
+\subsection*{Please, not the moons again!}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+voting_clf.fit(X_train, y_train)
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+\end{minted}
+
+% !split
+\subsection*{Bagging examples}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(random_state=42), n_estimators=500,
+ max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+\end{minted}
+
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if contour:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+ plt.axis(axes)
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+plt.show()
+\end{minted}
+
+% !split
+\subsection*{Then random forests}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+ n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+\end{minted}
+
+
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred)
+\end{minted}
+
+
+% !split
+\subsection*{Boosting and more}
+More material to come here.
+
+
+
+% ------------------- end of main content ---------------
+
+\end{document}
+
diff --git a/doc/src/DecisionTrees/DecisionTrees-reveal.html b/doc/src/DecisionTrees/DecisionTrees-reveal.html
new file mode 100644
index 000000000..cf3dc3ebb
--- /dev/null
+++ b/doc/src/DecisionTrees/DecisionTrees-reveal.html
@@ -0,0 +1,1383 @@
+
+
+
+
+
+
+
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+
+
+
+
+
+Morten Hjorth-Jensen [1, 2]
+
+
+
+
+
+
[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+information regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the most
+informative feature is done until we accomplish a stopping criteria
+where we then finally end up in so called leaf nodes.
+
+
+A decision tree is typically divided into a root node, the interior nodes,
+and the final leaf nodes or just leaves. These entities are then connected by so-called branches.
+
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+
+
+
+
A typical Decision Tree with its pertinent Jargon, Classification Problem
+
+
+In the figure here we present a decision tree obtained from a classification problem
+
+
+
+
+
A typical Decision Tree with its pertinent Jargon, Regeression Problem
+
+
+In the figure we present a decision tree obtained from a simple regression problem
+
+
+
+
+
General Features
+
+
+The overarching approach to decision trees is a top-down approach.
+
+
+
A leaf provides the classification of a given instance.
+
A node specifies a test of some attribute of the instance.
+
A branch corresponds to a possible values of an attribute.
+
An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+
+
+
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+
+
+
How do we set it up?
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+
+
Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
+
Show query instances to the tree and run down the tree until we arrive at leaf nodes
We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
+
+
For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
+
+
+
+How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
+regions could have any shape. However, we choose to divide the
+predictor space into high-dimensional rectangles, or boxes, for
+simplicity and for ease of interpretation of the resulting predictive
+model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
+MSE, given by
+
+
+where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within box \( j \).
+
+
+
+
+
A top-down approach, recursive binary splitting
+
+
+Unfortunately, it is computationally infeasible to consider every
+possible partition of the feature space into \( J \) boxes. The common
+strategy is to take a top-down approach
+
+
+The approach is top-down because it begins at the top of the tree (all
+observations belong to a single region) and then successively splits
+the predictor space; each split is indicated via two new branches
+further down on the tree. It is greedy because at each step of the
+tree-building process, the best split is made at that particular step,
+rather than looking ahead and picking a split that will lead to a
+better tree in some future step.
+
+
+
+
+
Making a tree
+
+
+In order to implement the recursive binary splitting we start by selecting
+the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
+
+which we want to minimize by considering all predictors
+\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
+each predictor. These values could be determined by randomly assigned
+numbers or by starting at the midpoint and then proceed till we find
+an optimal value.
+
+
+For any \( j \) and \( s \), we define the pair of half-planes where
+\( \overline{y}_{R_1} \) is the mean response for the training
+observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
+response for the training observations in \( R_2(j,s) \).
+
+
+Finding the values of \( j \) and \( s \) that minimize the above equation can be
+done quite quickly, especially when the number of features \( p \) is not
+too large.
+
+
+Next, we repeat the process, looking
+for the best predictor and best cutpoint in order to split the data
+further so as to minimize the MSE within each of the resulting
+regions. However, this time, instead of splitting the entire predictor
+space, we split one of the two previously identified regions. We now
+have three regions. Again, we look to split one of these three regions
+further, so as to minimize the MSE. The process continues until a
+stopping criterion is reached; for instance, we may continue until no
+region contains more than five observations.
+
+
+
+
+
Pruning the tree
+
+
+The above procedure is rather straightforward, but leads often to
+overfitting and unnecessarily large and complicated trees. The basic
+idea is to grow a large tree \( T_0 \) and then prune it back in order to
+obtain a subtree. A smaller tree with fewer splits (fewer regions) can
+lead to smaller variance and better interpretation at the cost of a
+little more bias.
+
+
+The so-called Cost complexity pruning algorithm gives us a
+way to do just this. Rather than considering every possible subtree,
+we consider a sequence of trees indexed by a nonnegative tuning
+parameter \( \alpha \).
+
+
+
+
+
Cost complexity pruning
+For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
+
+
+is as small as possible. Here \( \overline{T} \) is
+the number of terminal nodes of the tree \( T \) , \( R_m \) is the
+rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node.
+
+
+The tuning parameter \( \alpha \) controls a trade-off between the subtree’s
+com- plexity and its fit to the training data. When \( \alpha = 0 \), then the
+subtree \( T \) will simply equal \( T_0 \),
+because then the above equation just measures the
+training error.
+However, as \( \alpha \) increases, there is a price to pay for
+having a tree with many terminal nodes. The above equation will
+tend to be minimized for a smaller subtree.
+
+
+It turns out that as we increase \( \alpha \) from zero
+branches get pruned from the tree in a nested and predictable fashion,
+so obtaining the whole sequence of subtrees as a function of \( \alpha \) is
+easy. We can select a value of \( \alpha \) using a validation set or using
+cross-validation. We then return to the full data set and obtain the
+subtree corresponding to \( \alpha \).
+
+
+
+
+
Schematic Regression Procedure
+
+
+
+Building a Regression Tree.
+
+
Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
+
Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
+
Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
+
+
+
+
repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
+
+
Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
+
+
Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
+
+
Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
+
+
+
+
+
+
+
A Classification Tree
+
+
+A classification tree is very similar to a regression tree, except
+that it is used to predict a qualitative response rather than a
+quantitative one. Recall that for a regression tree, the predicted
+response for an observation is given by the mean response of the
+training observations that belong to the same terminal node. In
+contrast, for a classification tree, we predict that each observation
+belongs to the most commonly occurring class of training observations
+in the region to which it belongs. In interpreting the results of a
+classification tree, we are often interested not only in the class
+prediction corresponding to a particular terminal node region, but
+also in the class proportions among the training observations that
+fall into that region.
+
+
+
+
+
Growing a classification tree
+
+
+The task of growing a
+classification tree is quite similar to the task of growing a
+regression tree. Just as in the regression setting, we use recursive
+binary splitting to grow a classification tree. However, in the
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+error rate. Since we plan to assign an observation in a given region
+to the most commonly occurring error rate class of training
+observations in that region, the classification error rate is simply
+the fraction of the training observations in that region that do not
+belong to the most common class.
+
+
+When building a classification tree, either the Gini index or the
+entropy are typically used to evaluate the quality of a particular
+split, since these two approaches are more sensitive to node purity
+than is the classification error rate.
+
+
+
+
+
Classification tree, how to split nodes
+
+
+If our targets are the outcome of a classification process that takes
+for example \( k=1,2,\dots,K \) values, the only thing we need to think of
+is to set up the splitting criteria for each node.
+
+
+We define a PDF \( p_{mk} \) that represents the number of observations of
+a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
+this likelihood function in terms of the proportion \( I(y_i=k) \) of
+observations of this class in the region \( R_m \) as
+
+
+ID3, learns decision trees by constructing
+them topdown, beginning with the question which attribute should be tested at the root of the tree?
+
+
+
Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
+
The best attribute is selected and used as the test at the root node of the tree.
+
A descendant of the root node is then created for each possible value of this attribute.
+
Training examples are sorted to the appropriate descendant node.
+
The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
+
This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
+
+
+
+The ID3 algorithm selects, which attribute to test at each node in the
+tree.
+
+
+We would like to select the attribute that is most useful for classifying
+examples.
+
+
+What is a good quantitative measure of the worth of an attribute?
+
+
+Information gain measures how well a given attribute separates the
+training examples according to their target classification.
+
+
+The ID3 algorithm uses this information gain measure to select among the candidate
+attributes at each step while growing the tree.
+
+
+
+
+
Implementing the ID3 Algorithm
+
+
+more text to come here, material presented during lecture Friday Oct 25.
+
+
+
+
+
Cancer Data again now with Decision Trees
+
+
+
+
importmatplotlib.pyplotasplt
+importnumpyasnp
+fromsklearn.model_selectionimport train_test_split
+fromsklearn.datasetsimport load_breast_cancer
+fromsklearn.svmimport SVC
+fromsklearn.linear_modelimport LogisticRegression
+fromsklearn.treeimport DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+fromsklearn.preprocessingimport StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+
Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+
No feature normalization needed
+
Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+
Can model nonlinear relationships
+
Can model interactions between the different descriptive features
+
Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+
+
+
+
+
+
Disadvantages
+
+
+
Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+
If continuous features are used the tree may become quite large and hence less interpretable
+
Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+
Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+
Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+
If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+
Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+
+
+
+However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
+
+
+
+
+
Bagging
+
+
+The plain decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of \( n \) to \( p \) is moderately large.
+
+
+Bootstrap aggregation, or just bagging, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all \( B \) possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all \( B \) trees.
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of \( m \) predictors is chosen as split
+candidates from the full set of \( p \) predictors. The split is allowed to
+use only one of those \( m \) predictors.
+
+
+A fresh sample of \( m \) predictors is
+taken at each split, and typically we choose
+
+
+$$
+m\approx \sqrt{p}.
+$$
+
+
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+
+
+
+
A simple scikit-learn example
+
+
+
+
fromsklearn.ensembleimport RandomForestClassifier
+fromsklearn.preprocessingimport LabelEncoder
+fromsklearn.model_selectionimport cross_validate
+# Data set not specificied
+X = dataset.XXX
+Y = dataset.YYY
+#Instantiate the model with 100 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/src/DecisionTrees/DecisionTrees-solarized.html b/doc/src/DecisionTrees/DecisionTrees-solarized.html
new file mode 100644
index 000000000..f6b84cb41
--- /dev/null
+++ b/doc/src/DecisionTrees/DecisionTrees-solarized.html
@@ -0,0 +1,1211 @@
+
+
+
+
+
+
+
+
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+
+
+
+
+
+Morten Hjorth-Jensen [1, 2]
+
+
+
+
+
+
[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+
+
Oct 26, 2019
+
+
+
+
+
Decision trees, overarching aims
+
+
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+information regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the most
+informative feature is done until we accomplish a stopping criteria
+where we then finally end up in so called leaf nodes.
+
+
+A decision tree is typically divided into a root node, the interior nodes,
+and the final leaf nodes or just leaves. These entities are then connected by so-called branches.
+
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+
+
+
+
A typical Decision Tree with its pertinent Jargon, Classification Problem
+
+
+In the figure here we present a decision tree obtained from a classification problem
+
+
+
+
+
A typical Decision Tree with its pertinent Jargon, Regeression Problem
+
+
+In the figure we present a decision tree obtained from a simple regression problem
+
+
+
+
+
General Features
+
+
+The overarching approach to decision trees is a top-down approach.
+
+
+
A leaf provides the classification of a given instance.
+
A node specifies a test of some attribute of the instance.
+
A branch corresponds to a possible values of an attribute.
+
An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+
+
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+
+
+
How do we set it up?
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+
+
Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
+
Show query instances to the tree and run down the tree until we arrive at leaf nodes
We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
+
For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
+
+
+How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
+regions could have any shape. However, we choose to divide the
+predictor space into high-dimensional rectangles, or boxes, for
+simplicity and for ease of interpretation of the resulting predictive
+model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
+MSE, given by
+
+$$
+\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
+$$
+
+
+where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within box \( j \).
+
+
+
+
+
A top-down approach, recursive binary splitting
+
+
+Unfortunately, it is computationally infeasible to consider every
+possible partition of the feature space into \( J \) boxes. The common
+strategy is to take a top-down approach
+
+
+The approach is top-down because it begins at the top of the tree (all
+observations belong to a single region) and then successively splits
+the predictor space; each split is indicated via two new branches
+further down on the tree. It is greedy because at each step of the
+tree-building process, the best split is made at that particular step,
+rather than looking ahead and picking a split that will lead to a
+better tree in some future step.
+
+
+
+
+
Making a tree
+
+
+In order to implement the recursive binary splitting we start by selecting
+the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
+$$
+\left\{X\vert x_j < s\right\},
+$$
+
+and
+$$
+\left\{X\vert x_j \geq s\right\},
+$$
+
+so that we obtain the lowest MSE, that is
+$$
+\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
+$$
+
+
+which we want to minimize by considering all predictors
+\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
+each predictor. These values could be determined by randomly assigned
+numbers or by starting at the midpoint and then proceed till we find
+an optimal value.
+
+
+For any \( j \) and \( s \), we define the pair of half-planes where
+\( \overline{y}_{R_1} \) is the mean response for the training
+observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
+response for the training observations in \( R_2(j,s) \).
+
+
+Finding the values of \( j \) and \( s \) that minimize the above equation can be
+done quite quickly, especially when the number of features \( p \) is not
+too large.
+
+
+Next, we repeat the process, looking
+for the best predictor and best cutpoint in order to split the data
+further so as to minimize the MSE within each of the resulting
+regions. However, this time, instead of splitting the entire predictor
+space, we split one of the two previously identified regions. We now
+have three regions. Again, we look to split one of these three regions
+further, so as to minimize the MSE. The process continues until a
+stopping criterion is reached; for instance, we may continue until no
+region contains more than five observations.
+
+
+
+
+
Pruning the tree
+
+
+The above procedure is rather straightforward, but leads often to
+overfitting and unnecessarily large and complicated trees. The basic
+idea is to grow a large tree \( T_0 \) and then prune it back in order to
+obtain a subtree. A smaller tree with fewer splits (fewer regions) can
+lead to smaller variance and better interpretation at the cost of a
+little more bias.
+
+
+The so-called Cost complexity pruning algorithm gives us a
+way to do just this. Rather than considering every possible subtree,
+we consider a sequence of trees indexed by a nonnegative tuning
+parameter \( \alpha \).
+
+
+
+
+
Cost complexity pruning
+For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
+$$
+\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
+$$
+
+is as small as possible. Here \( \overline{T} \) is
+the number of terminal nodes of the tree \( T \) , \( R_m \) is the
+rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node.
+
+
+The tuning parameter \( \alpha \) controls a trade-off between the subtree’s
+com- plexity and its fit to the training data. When \( \alpha = 0 \), then the
+subtree \( T \) will simply equal \( T_0 \),
+because then the above equation just measures the
+training error.
+However, as \( \alpha \) increases, there is a price to pay for
+having a tree with many terminal nodes. The above equation will
+tend to be minimized for a smaller subtree.
+
+
+It turns out that as we increase \( \alpha \) from zero
+branches get pruned from the tree in a nested and predictable fashion,
+so obtaining the whole sequence of subtrees as a function of \( \alpha \) is
+easy. We can select a value of \( \alpha \) using a validation set or using
+cross-validation. We then return to the full data set and obtain the
+subtree corresponding to \( \alpha \).
+
+
+
+
+
Schematic Regression Procedure
+
+
+
+Building a Regression Tree.
+
+
+
+
Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
+
Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
+
Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
+
+
+
repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
+
Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
+
Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
+
+
+
Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
+
+
+
+
+
+
+
+
A Classification Tree
+
+
+A classification tree is very similar to a regression tree, except
+that it is used to predict a qualitative response rather than a
+quantitative one. Recall that for a regression tree, the predicted
+response for an observation is given by the mean response of the
+training observations that belong to the same terminal node. In
+contrast, for a classification tree, we predict that each observation
+belongs to the most commonly occurring class of training observations
+in the region to which it belongs. In interpreting the results of a
+classification tree, we are often interested not only in the class
+prediction corresponding to a particular terminal node region, but
+also in the class proportions among the training observations that
+fall into that region.
+
+
+
+
+
Growing a classification tree
+
+
+The task of growing a
+classification tree is quite similar to the task of growing a
+regression tree. Just as in the regression setting, we use recursive
+binary splitting to grow a classification tree. However, in the
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+error rate. Since we plan to assign an observation in a given region
+to the most commonly occurring error rate class of training
+observations in that region, the classification error rate is simply
+the fraction of the training observations in that region that do not
+belong to the most common class.
+
+
+When building a classification tree, either the Gini index or the
+entropy are typically used to evaluate the quality of a particular
+split, since these two approaches are more sensitive to node purity
+than is the classification error rate.
+
+
+
+
+
Classification tree, how to split nodes
+
+
+If our targets are the outcome of a classification process that takes
+for example \( k=1,2,\dots,K \) values, the only thing we need to think of
+is to set up the splitting criteria for each node.
+
+
+We define a PDF \( p_{mk} \) that represents the number of observations of
+a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
+this likelihood function in terms of the proportion \( I(y_i=k) \) of
+observations of this class in the region \( R_m \) as
+
+$$
+p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
+$$
+
+
+We let \( p_{mk} \) represent the majority class of observations in region
+\( m \). The three most common ways of splitting a node are given by
+
+
+ID3, learns decision trees by constructing
+them topdown, beginning with the question which attribute should be tested at the root of the tree?
+
+
+
Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
+
The best attribute is selected and used as the test at the root node of the tree.
+
A descendant of the root node is then created for each possible value of this attribute.
+
Training examples are sorted to the appropriate descendant node.
+
The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
+
This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
+
+
+The ID3 algorithm selects, which attribute to test at each node in the
+tree.
+
+
+We would like to select the attribute that is most useful for classifying
+examples.
+
+
+What is a good quantitative measure of the worth of an attribute?
+
+
+Information gain measures how well a given attribute separates the
+training examples according to their target classification.
+
+
+The ID3 algorithm uses this information gain measure to select among the candidate
+attributes at each step while growing the tree.
+
+
+
+
+
Implementing the ID3 Algorithm
+
+
+more text to come here, material presented during lecture Friday Oct 25.
+
+
+
+
+
Cancer Data again now with Decision Trees
+
+
+
+
importmatplotlib.pyplotasplt
+importnumpyasnp
+fromsklearn.model_selectionimport train_test_split
+fromsklearn.datasetsimport load_breast_cancer
+fromsklearn.svmimport SVC
+fromsklearn.linear_modelimport LogisticRegression
+fromsklearn.treeimport DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+fromsklearn.preprocessingimport StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+
Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+
No feature normalization needed
+
Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+
Can model nonlinear relationships
+
Can model interactions between the different descriptive features
+
Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+
+
+
+
+
Disadvantages
+
+
+
Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+
If continuous features are used the tree may become quite large and hence less interpretable
+
Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+
Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+
Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+
If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+
Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+
+
+However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
+
+
+
+
+
Bagging
+
+
+The plain decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of \( n \) to \( p \) is moderately large.
+
+
+Bootstrap aggregation, or just bagging, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all \( B \) possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all \( B \) trees.
+
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of \( m \) predictors is chosen as split
+candidates from the full set of \( p \) predictors. The split is allowed to
+use only one of those \( m \) predictors.
+
+
+A fresh sample of \( m \) predictors is
+taken at each split, and typically we choose
+
+$$
+m\approx \sqrt{p}.
+$$
+
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+
+
+
+
A simple scikit-learn example
+
+
+
+
fromsklearn.ensembleimport RandomForestClassifier
+fromsklearn.preprocessingimport LabelEncoder
+fromsklearn.model_selectionimport cross_validate
+# Data set not specificied
+X = dataset.XXX
+Y = dataset.YYY
+#Instantiate the model with 100 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
+
+
+
+
+
+
+
diff --git a/doc/src/DecisionTrees/DecisionTrees.do.txt b/doc/src/DecisionTrees/DecisionTrees.do.txt
index a5dc32152..e0bbfb497 100644
--- a/doc/src/DecisionTrees/DecisionTrees.do.txt
+++ b/doc/src/DecisionTrees/DecisionTrees.do.txt
@@ -1,4 +1,4 @@
-TITLE: Data Analysis and Machine Learning: Trees, forests and all that
+TITLE: Data Analysis and Machine Learning: From Decision Trees to Forests and all that
AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
DATE: today
@@ -15,37 +15,47 @@ The main idea of decision trees
is to find those descriptive features which contain the most
_information_ regarding the target feature and then split the dataset
along the values of these features such that the target feature values
-for the resulting sub datasets are as pure as possible.
+for the resulting underlying datasets are as pure as possible.
-The descriptive feature which leaves the target feature most purely is said
-to be the most informative one. This process of finding the _most
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the _most
informative_ feature is done until we accomplish a stopping criteria
where we then finally end up in so called _leaf nodes_.
+A decision tree is typically divided into a _root node_, the _interior nodes_,
+and the final _leaf nodes_ or just _leaves_. These entities are then connected by so-called _branches_.
+
The leaf nodes
contain the predictions we will make for new query instances presented
-to our trained model. This is possible since the model has kind of
+to our trained model. This is possible since the model has
learned the underlying structure of the training data and hence can,
given some assumptions, make predictions about the target feature value
(class) of unseen query instances.
+!split
+===== A typical Decision Tree with its pertinent Jargon, Classification Problem =====
-A decision tree mainly contains of a _root node_, _interior nodes_,
-and _leaf nodes_ which are then connected by _branches_.
+In the figure here we present a decision tree obtained from a classification problem
+
+
+!split
+===== A typical Decision Tree with its pertinent Jargon, Regeression Problem =====
+
+In the figure we present a decision tree obtained from a simple regression problem
!split
===== General Features =====
-Decision trees classify instances by sorting top down.
+The overarching approach to decision trees is a top-down approach.
-* A leaf provides the classification of the instance.
+* A leaf provides the classification of a given instance.
* A node specifies a test of some attribute of the instance.
-* A branch corresponds to a possible values an attribute.
+* A branch corresponds to a possible values of an attribute.
* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
-This processis then repeated for the subtree rooted at the new
+This process is then repeated for the subtree rooted at the new
node.
@@ -173,17 +183,19 @@ There are mainly two steps
o We split the predictor space (the set of possible values $x_1,x_2,\dots, x_p$) into $J$ distinct and non-non-overlapping regions, $R_1,R_2,\dots,R_J$.
o For every observation that falls into the region $R_j$ , we make the same prediction, which is simply the mean of the response values for the training observations in $R_j$.
-How do we construct the regions $R_1,\dots,R_J$?
-In theory, the regions could have any shape. However, we
-choose to divide the predictor space into high-dimensional rectangles,
-or boxes, for simplicity and for ease of interpretation of the
-resulting predictive model. The goal is to find boxes $R_1,\dots,R_J$
-that minimize the MSE, given by
+How do we construct the regions $R_1,\dots,R_J$? In theory, the
+regions could have any shape. However, we choose to divide the
+predictor space into high-dimensional rectangles, or boxes, for
+simplicity and for ease of interpretation of the resulting predictive
+model. The goal is to find boxes $R_1,\dots,R_J$ that minimize the
+MSE, given by
+
!bt
\[
\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
\]
!et
+
where $\overline{y}_{R_j}$ is the mean response for the training observations
within box $j$.
@@ -191,8 +203,8 @@ within box $j$.
===== A top-down approach, recursive binary splitting =====
Unfortunately, it is computationally infeasible to consider every
-possible partition of the feature space into $J$ boxes.
-The common strategy is to take a top-down approach
+possible partition of the feature space into $J$ boxes. The common
+strategy is to take a top-down approach
The approach is top-down because it begins at the top of the tree (all
observations belong to a single region) and then successively splits
@@ -224,17 +236,21 @@ so that we obtain the lowest MSE, that is
\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
\]
!et
-which we want to minimize by considering all predictors $x_1,x_2,\dots,x_p$.
-We consider also all possible values of $s$ for each predictor. These values could be determined by randomly assigned numbers or by starting at the midpoint and then proceed till we find an optimal value.
-For any $j$ and $s$, we define the pair of
-half-planes where $\overline{y}_{R_1}$ is the mean response for the training
-observations in $R_1(j,s)$, and $\overline{y}_{R_2}$ is the mean response for the
-training observations in $R_2(j,s)$.
+which we want to minimize by considering all predictors
+$x_1,x_2,\dots,x_p$. We consider also all possible values of $s$ for
+each predictor. These values could be determined by randomly assigned
+numbers or by starting at the midpoint and then proceed till we find
+an optimal value.
-Finding the values of j and s that
-minimize the above equation can be done quite quickly, especially when the number
-of features $p$ is not too large.
+For any $j$ and $s$, we define the pair of half-planes where
+$\overline{y}_{R_1}$ is the mean response for the training
+observations in $R_1(j,s)$, and $\overline{y}_{R_2}$ is the mean
+response for the training observations in $R_2(j,s)$.
+
+Finding the values of $j$ and $s$ that minimize the above equation can be
+done quite quickly, especially when the number of features $p$ is not
+too large.
Next, we repeat the process, looking
for the best predictor and best cutpoint in order to split the data
@@ -345,17 +361,24 @@ than is the classification error rate.
!split
===== Classification tree, how to split nodes =====
-If our targets are the outcome of a classification process that takes for example
-$k=1,2,\dots,K$ values, the only thing we need to think of is to set up the splitting criteria for each node.
+If our targets are the outcome of a classification process that takes
+for example $k=1,2,\dots,K$ values, the only thing we need to think of
+is to set up the splitting criteria for each node.
+
+We define a PDF $p_{mk}$ that represents the number of observations of
+a class $k$ in a region $R_m$ with $N_m$ observations. We represent
+this likelihood function in terms of the proportion $I(y_i=k)$ of
+observations of this class in the region $R_m$ as
-We define a PDF $p_{mk}$ that represents the number of observations of a class $k$ in a region $R_m$ with $N_m$ observations. We represent this likelihood function in terms of the proportion $I(y_i=k)$ of observations of this class in the region $R_m$ as
!bt
\[
p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
\]
!et
-We let $p_{mk}$ represent the majority class of observations in region $m$. The three most common ways of splitting a node are given by
+We let $p_{mk}$ represent the majority class of observations in region
+$m$. The three most common ways of splitting a node are given by
+
* Misclassification error
!bt
\[
@@ -655,6 +678,8 @@ plt.show()
* Can model nonlinear relationships
* Can model interactions between the different descriptive features
* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+
+
!split
===== Disadvantages =====
@@ -740,11 +765,13 @@ use only one of those $m$ predictors.
A fresh sample of $m$ predictors is
taken at each split, and typically we choose
+
!bt
\[
m\approx \sqrt{p}.
\]
!et
+
In building a random forest, at
each split in the tree, the algorithm is not even allowed to consider
a majority of the available predictors.
@@ -755,12 +782,12 @@ moderately strong predictors. Then in the collection of bagged
variable importance random forest trees, most or all of the trees will
use this strong predictor in the top split. Consequently, all of the
bagged trees will look quite similar to each other. Hence the
-predictions from the bagged trees will be highly correlated.
-Unfortunately, averaging many highly correlated quantities does not lead
-to as large of a reduction in variance as averaging many uncorrelated
-quanti- ties. In particular, this means that bagging will not lead to
-a substantial reduction in variance over a single tree in this
-setting.
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
!split
===== A simple scikit-learn example =====
diff --git a/doc/src/DecisionTrees/DecisionTrees.html b/doc/src/DecisionTrees/DecisionTrees.html
new file mode 100644
index 000000000..1472b9062
--- /dev/null
+++ b/doc/src/DecisionTrees/DecisionTrees.html
@@ -0,0 +1,1216 @@
+
+
+
+
+
+
+
+
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+
+
+
+
+
+Morten Hjorth-Jensen [1, 2]
+
+
+
+
+
+
[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+
+
Oct 26, 2019
+
+
+
+
+
Decision trees, overarching aims
+
+
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+information regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the most
+informative feature is done until we accomplish a stopping criteria
+where we then finally end up in so called leaf nodes.
+
+
+A decision tree is typically divided into a root node, the interior nodes,
+and the final leaf nodes or just leaves. These entities are then connected by so-called branches.
+
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+
+
+
+
A typical Decision Tree with its pertinent Jargon, Classification Problem
+
+
+In the figure here we present a decision tree obtained from a classification problem
+
+
+
+
+
A typical Decision Tree with its pertinent Jargon, Regeression Problem
+
+
+In the figure we present a decision tree obtained from a simple regression problem
+
+
+
+
+
General Features
+
+
+The overarching approach to decision trees is a top-down approach.
+
+
+
A leaf provides the classification of a given instance.
+
A node specifies a test of some attribute of the instance.
+
A branch corresponds to a possible values of an attribute.
+
An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+
+
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+
+
+
How do we set it up?
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+
+
Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
+
Show query instances to the tree and run down the tree until we arrive at leaf nodes
We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
+
For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
+
+
+How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
+regions could have any shape. However, we choose to divide the
+predictor space into high-dimensional rectangles, or boxes, for
+simplicity and for ease of interpretation of the resulting predictive
+model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
+MSE, given by
+
+$$
+\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
+$$
+
+
+where \( \overline{y}_{R_j} \) is the mean response for the training observations
+within box \( j \).
+
+
+
+
+
A top-down approach, recursive binary splitting
+
+
+Unfortunately, it is computationally infeasible to consider every
+possible partition of the feature space into \( J \) boxes. The common
+strategy is to take a top-down approach
+
+
+The approach is top-down because it begins at the top of the tree (all
+observations belong to a single region) and then successively splits
+the predictor space; each split is indicated via two new branches
+further down on the tree. It is greedy because at each step of the
+tree-building process, the best split is made at that particular step,
+rather than looking ahead and picking a split that will lead to a
+better tree in some future step.
+
+
+
+
+
Making a tree
+
+
+In order to implement the recursive binary splitting we start by selecting
+the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
+$$
+\left\{X\vert x_j < s\right\},
+$$
+
+and
+$$
+\left\{X\vert x_j \geq s\right\},
+$$
+
+so that we obtain the lowest MSE, that is
+$$
+\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
+$$
+
+
+which we want to minimize by considering all predictors
+\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
+each predictor. These values could be determined by randomly assigned
+numbers or by starting at the midpoint and then proceed till we find
+an optimal value.
+
+
+For any \( j \) and \( s \), we define the pair of half-planes where
+\( \overline{y}_{R_1} \) is the mean response for the training
+observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
+response for the training observations in \( R_2(j,s) \).
+
+
+Finding the values of \( j \) and \( s \) that minimize the above equation can be
+done quite quickly, especially when the number of features \( p \) is not
+too large.
+
+
+Next, we repeat the process, looking
+for the best predictor and best cutpoint in order to split the data
+further so as to minimize the MSE within each of the resulting
+regions. However, this time, instead of splitting the entire predictor
+space, we split one of the two previously identified regions. We now
+have three regions. Again, we look to split one of these three regions
+further, so as to minimize the MSE. The process continues until a
+stopping criterion is reached; for instance, we may continue until no
+region contains more than five observations.
+
+
+
+
+
Pruning the tree
+
+
+The above procedure is rather straightforward, but leads often to
+overfitting and unnecessarily large and complicated trees. The basic
+idea is to grow a large tree \( T_0 \) and then prune it back in order to
+obtain a subtree. A smaller tree with fewer splits (fewer regions) can
+lead to smaller variance and better interpretation at the cost of a
+little more bias.
+
+
+The so-called Cost complexity pruning algorithm gives us a
+way to do just this. Rather than considering every possible subtree,
+we consider a sequence of trees indexed by a nonnegative tuning
+parameter \( \alpha \).
+
+
+
+
+
Cost complexity pruning
+For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that
+$$
+\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
+$$
+
+is as small as possible. Here \( \overline{T} \) is
+the number of terminal nodes of the tree \( T \) , \( R_m \) is the
+rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node.
+
+
+The tuning parameter \( \alpha \) controls a trade-off between the subtree’s
+com- plexity and its fit to the training data. When \( \alpha = 0 \), then the
+subtree \( T \) will simply equal \( T_0 \),
+because then the above equation just measures the
+training error.
+However, as \( \alpha \) increases, there is a price to pay for
+having a tree with many terminal nodes. The above equation will
+tend to be minimized for a smaller subtree.
+
+
+It turns out that as we increase \( \alpha \) from zero
+branches get pruned from the tree in a nested and predictable fashion,
+so obtaining the whole sequence of subtrees as a function of \( \alpha \) is
+easy. We can select a value of \( \alpha \) using a validation set or using
+cross-validation. We then return to the full data set and obtain the
+subtree corresponding to \( \alpha \).
+
+
+
+
+
Schematic Regression Procedure
+
+
+
+Building a Regression Tree.
+
+
+
+
Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
+
Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
+
Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
+
+
+
repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
+
Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
+
Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
+
+
+
Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
+
+
+
+
+
+
+
+
A Classification Tree
+
+
+A classification tree is very similar to a regression tree, except
+that it is used to predict a qualitative response rather than a
+quantitative one. Recall that for a regression tree, the predicted
+response for an observation is given by the mean response of the
+training observations that belong to the same terminal node. In
+contrast, for a classification tree, we predict that each observation
+belongs to the most commonly occurring class of training observations
+in the region to which it belongs. In interpreting the results of a
+classification tree, we are often interested not only in the class
+prediction corresponding to a particular terminal node region, but
+also in the class proportions among the training observations that
+fall into that region.
+
+
+
+
+
Growing a classification tree
+
+
+The task of growing a
+classification tree is quite similar to the task of growing a
+regression tree. Just as in the regression setting, we use recursive
+binary splitting to grow a classification tree. However, in the
+classification setting, the MSE cannot be used as a criterion for making
+the binary splits. A natural alternative to MSE is the classification
+error rate. Since we plan to assign an observation in a given region
+to the most commonly occurring error rate class of training
+observations in that region, the classification error rate is simply
+the fraction of the training observations in that region that do not
+belong to the most common class.
+
+
+When building a classification tree, either the Gini index or the
+entropy are typically used to evaluate the quality of a particular
+split, since these two approaches are more sensitive to node purity
+than is the classification error rate.
+
+
+
+
+
Classification tree, how to split nodes
+
+
+If our targets are the outcome of a classification process that takes
+for example \( k=1,2,\dots,K \) values, the only thing we need to think of
+is to set up the splitting criteria for each node.
+
+
+We define a PDF \( p_{mk} \) that represents the number of observations of
+a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
+this likelihood function in terms of the proportion \( I(y_i=k) \) of
+observations of this class in the region \( R_m \) as
+
+$$
+p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
+$$
+
+
+We let \( p_{mk} \) represent the majority class of observations in region
+\( m \). The three most common ways of splitting a node are given by
+
+
+ID3, learns decision trees by constructing
+them topdown, beginning with the question which attribute should be tested at the root of the tree?
+
+
+
Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
+
The best attribute is selected and used as the test at the root node of the tree.
+
A descendant of the root node is then created for each possible value of this attribute.
+
Training examples are sorted to the appropriate descendant node.
+
The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
+
This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
+
+
+The ID3 algorithm selects, which attribute to test at each node in the
+tree.
+
+
+We would like to select the attribute that is most useful for classifying
+examples.
+
+
+What is a good quantitative measure of the worth of an attribute?
+
+
+Information gain measures how well a given attribute separates the
+training examples according to their target classification.
+
+
+The ID3 algorithm uses this information gain measure to select among the candidate
+attributes at each step while growing the tree.
+
+
+
+
+
Implementing the ID3 Algorithm
+
+
+more text to come here, material presented during lecture Friday Oct 25.
+
+
+
+
+
Cancer Data again now with Decision Trees
+
+
+
+
importmatplotlib.pyplotasplt
+importnumpyasnp
+fromsklearn.model_selectionimport train_test_split
+fromsklearn.datasetsimport load_breast_cancer
+fromsklearn.svmimport SVC
+fromsklearn.linear_modelimport LogisticRegression
+fromsklearn.treeimport DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+fromsklearn.preprocessingimport StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+
Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+
No feature normalization needed
+
Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+
Can model nonlinear relationships
+
Can model interactions between the different descriptive features
+
Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+
+
+
+
+
Disadvantages
+
+
+
Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+
If continuous features are used the tree may become quite large and hence less interpretable
+
Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+
Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+
Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+
If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+
Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+
+
+However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
+
+
+
+
+
Bagging
+
+
+The plain decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of \( n \) to \( p \) is moderately large.
+
+
+Bootstrap aggregation, or just bagging, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all \( B \) possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all \( B \) trees.
+
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of \( m \) predictors is chosen as split
+candidates from the full set of \( p \) predictors. The split is allowed to
+use only one of those \( m \) predictors.
+
+
+A fresh sample of \( m \) predictors is
+taken at each split, and typically we choose
+
+$$
+m\approx \sqrt{p}.
+$$
+
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+
+
+
+
A simple scikit-learn example
+
+
+
+
fromsklearn.ensembleimport RandomForestClassifier
+fromsklearn.preprocessingimport LabelEncoder
+fromsklearn.model_selectionimport cross_validate
+# Data set not specificied
+X = dataset.XXX
+Y = dataset.YYY
+#Instantiate the model with 100 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
+
+
+
+
+
+
+
diff --git a/doc/src/DecisionTrees/DecisionTrees.ipynb b/doc/src/DecisionTrees/DecisionTrees.ipynb
new file mode 100644
index 000000000..3a926590f
--- /dev/null
+++ b/doc/src/DecisionTrees/DecisionTrees.ipynb
@@ -0,0 +1,1241 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "# Data Analysis and Machine Learning: From Decision Trees to Forests and all that\n",
+ "\n",
+ " \n",
+ "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
+ "\n",
+ "Date: **Oct 26, 2019**\n",
+ "\n",
+ "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Decision trees, overarching aims\n",
+ "\n",
+ "\n",
+ "Decision trees are supervised learning algorithms used for both,\n",
+ "classification and regression tasks.\n",
+ "\n",
+ "\n",
+ "The main idea of decision trees\n",
+ "is to find those descriptive features which contain the most\n",
+ "**information** regarding the target feature and then split the dataset\n",
+ "along the values of these features such that the target feature values\n",
+ "for the resulting underlying datasets are as pure as possible.\n",
+ "\n",
+ "The descriptive features which reproduce best the target/output features are normally said\n",
+ "to be the most informative ones. The process of finding the **most\n",
+ "informative** feature is done until we accomplish a stopping criteria\n",
+ "where we then finally end up in so called **leaf nodes**. \n",
+ "\n",
+ "A decision tree is typically divided into a **root node**, the **interior nodes**,\n",
+ "and the final **leaf nodes** or just **leaves**. These entities are then connected by so-called **branches**.\n",
+ "\n",
+ "The leaf nodes\n",
+ "contain the predictions we will make for new query instances presented\n",
+ "to our trained model. This is possible since the model has \n",
+ "learned the underlying structure of the training data and hence can,\n",
+ "given some assumptions, make predictions about the target feature value\n",
+ "(class) of unseen query instances.\n",
+ "\n",
+ "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n",
+ "\n",
+ "In the figure here we present a decision tree obtained from a classification problem\n",
+ "\n",
+ "\n",
+ "## A typical Decision Tree with its pertinent Jargon, Regeression Problem\n",
+ "\n",
+ "In the figure we present a decision tree obtained from a simple regression problem\n",
+ "\n",
+ "\n",
+ "## General Features\n",
+ "\n",
+ "The overarching approach to decision trees is a top-down approach.\n",
+ "\n",
+ "* A leaf provides the classification of a given instance.\n",
+ "\n",
+ "* A node specifies a test of some attribute of the instance.\n",
+ "\n",
+ "* A branch corresponds to a possible values of an attribute.\n",
+ "\n",
+ "* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.\n",
+ "\n",
+ "This process is then repeated for the subtree rooted at the new\n",
+ "node.\n",
+ "\n",
+ "\n",
+ "## How do we set it up?\n",
+ "\n",
+ "\n",
+ "In simplified terms, the process of training a decision tree and\n",
+ "predicting the target features of query instances is as follows:\n",
+ "\n",
+ "1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature\n",
+ "\n",
+ "2. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process\n",
+ "\n",
+ "3. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances\n",
+ "\n",
+ "4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n",
+ "\n",
+ "Then we are essentially done!\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Decision trees and Regression"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "\n",
+ "steps=250\n",
+ "\n",
+ "distance=0\n",
+ "x=0\n",
+ "distance_list=[]\n",
+ "steps_list=[]\n",
+ "while x\n",
+ "## Pruning the tree\n",
+ "\n",
+ "The above procedure is rather straightforward, but leads often to\n",
+ "overfitting and unnecessarily large and complicated trees. The basic\n",
+ "idea is to grow a large tree $T_0$ and then prune it back in order to\n",
+ "obtain a subtree. A smaller tree with fewer splits (fewer regions) can\n",
+ "lead to smaller variance and better interpretation at the cost of a\n",
+ "little more bias.\n",
+ "\n",
+ "The so-called Cost complexity pruning algorithm gives us a\n",
+ "way to do just this. Rather than considering every possible subtree,\n",
+ "we consider a sequence of trees indexed by a nonnegative tuning\n",
+ "parameter $\\alpha$.\n",
+ "\n",
+ "## Cost complexity pruning\n",
+ "For each value of $\\alpha$ there corresponds a subtree $T \\in T_0$ such that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{m=1}^{\\overline{T}}\\sum_{i:x_i\\in R_m}(y_i-\\overline{y}_{R_m})^2+\\alpha\\overline{T},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is as small as possible. Here $\\overline{T}$ is \n",
+ "the number of terminal nodes of the tree $T$ , $R_m$ is the\n",
+ "rectangle (i.e. the subset of predictor space) corresponding to the $m$-th terminal node.\n",
+ "\n",
+ "The tuning parameter $\\alpha$ controls a trade-off between the subtree’s\n",
+ "com- plexity and its fit to the training data. When $\\alpha = 0$, then the\n",
+ "subtree $T$ will simply equal $T_0$, \n",
+ "because then the above equation just measures the\n",
+ "training error. \n",
+ "However, as $\\alpha$ increases, there is a price to pay for\n",
+ "having a tree with many terminal nodes. The above equation will\n",
+ "tend to be minimized for a smaller subtree. \n",
+ "\n",
+ "\n",
+ "It turns out that as we increase $\\alpha$ from zero\n",
+ "branches get pruned from the tree in a nested and predictable fashion,\n",
+ "so obtaining the whole sequence of subtrees as a function of $\\alpha$ is\n",
+ "easy. We can select a value of $\\alpha$ using a validation set or using\n",
+ "cross-validation. We then return to the full data set and obtain the\n",
+ "subtree corresponding to $\\alpha$. \n",
+ "\n",
+ "\n",
+ "## Schematic Regression Procedure\n",
+ "\n",
+ "**Building a Regression Tree.**\n",
+ "\n",
+ "1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.\n",
+ "\n",
+ "2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of $\\alpha$.\n",
+ "\n",
+ "3. Use for example $K$-fold cross-validation to choose $\\alpha$. Divide the training observations into $K$ folds. For each $k=1,2,\\dots,K$ we: \n",
+ "\n",
+ " * repeat steps 1 and 2 on all but the $k$-th fold of the training data. \n",
+ "\n",
+ " * Then we valuate the mean squared prediction error on the data in the left-out $k$-th fold, as a function of $\\alpha$.\n",
+ "\n",
+ " * Finally we average the results for each value of $\\alpha$, and pick $\\alpha$ to minimize the average error.\n",
+ "\n",
+ "\n",
+ "4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## A Classification Tree\n",
+ "\n",
+ "A classification tree is very similar to a regression tree, except\n",
+ "that it is used to predict a qualitative response rather than a\n",
+ "quantitative one. Recall that for a regression tree, the predicted\n",
+ "response for an observation is given by the mean response of the\n",
+ "training observations that belong to the same terminal node. In\n",
+ "contrast, for a classification tree, we predict that each observation\n",
+ "belongs to the most commonly occurring class of training observations\n",
+ "in the region to which it belongs. In interpreting the results of a\n",
+ "classification tree, we are often interested not only in the class\n",
+ "prediction corresponding to a particular terminal node region, but\n",
+ "also in the class proportions among the training observations that\n",
+ "fall into that region. \n",
+ "\n",
+ "## Growing a classification tree\n",
+ "\n",
+ "The task of growing a\n",
+ "classification tree is quite similar to the task of growing a\n",
+ "regression tree. Just as in the regression setting, we use recursive\n",
+ "binary splitting to grow a classification tree. However, in the\n",
+ "classification setting, the MSE cannot be used as a criterion for making\n",
+ "the binary splits. A natural alternative to MSE is the **classification\n",
+ "error rate**. Since we plan to assign an observation in a given region\n",
+ "to the most commonly occurring error rate class of training\n",
+ "observations in that region, the classification error rate is simply\n",
+ "the fraction of the training observations in that region that do not\n",
+ "belong to the most common class. \n",
+ "\n",
+ "When building a classification tree, either the Gini index or the\n",
+ "entropy are typically used to evaluate the quality of a particular\n",
+ "split, since these two approaches are more sensitive to node purity\n",
+ "than is the classification error rate. \n",
+ "\n",
+ "\n",
+ "## Classification tree, how to split nodes\n",
+ "\n",
+ "If our targets are the outcome of a classification process that takes\n",
+ "for example $k=1,2,\\dots,K$ values, the only thing we need to think of\n",
+ "is to set up the splitting criteria for each node.\n",
+ "\n",
+ "We define a PDF $p_{mk}$ that represents the number of observations of\n",
+ "a class $k$ in a region $R_m$ with $N_m$ observations. We represent\n",
+ "this likelihood function in terms of the proportion $I(y_i=k)$ of\n",
+ "observations of this class in the region $R_m$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i=k).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We let $p_{mk}$ represent the majority class of observations in region\n",
+ "$m$. The three most common ways of splitting a node are given by\n",
+ "\n",
+ "* Misclassification error"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "* Gini index $g$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "g = \\sum_{k=1}^K p_{mk}(1-p_{mk}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "* Information entropy or just entropy $s$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Entropy and the ID3 algorithm\n",
+ "\n",
+ "ID3, learns decision trees by constructing\n",
+ "them topdown, beginning with the question **which attribute should be tested at the root of the tree**?\n",
+ "\n",
+ "1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.\n",
+ "\n",
+ "2. The best attribute is selected and used as the test at the root node of the tree.\n",
+ "\n",
+ "3. A descendant of the root node is then created for each possible value of this attribute.\n",
+ "\n",
+ "4. Training examples are sorted to the appropriate descendant node.\n",
+ "\n",
+ "5. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.\n",
+ "\n",
+ "6. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices. \n",
+ "\n",
+ "The ID3 algorithm selects, which attribute to test at each node in the\n",
+ "tree.\n",
+ "\n",
+ "We would like to select the attribute that is most useful for classifying\n",
+ "examples.\n",
+ "\n",
+ "What is a good quantitative measure of the worth of an attribute?\n",
+ "\n",
+ "Information gain measures how well a given attribute separates the\n",
+ "training examples according to their target classification.\n",
+ "\n",
+ "The ID3 algorithm uses this information gain measure to select among the candidate\n",
+ "attributes at each step while growing the tree.\n",
+ "\n",
+ "## Implementing the ID3 Algorithm\n",
+ "\n",
+ "**more text to come here**, material presented during lecture Friday Oct 25.\n",
+ "\n",
+ "## Cancer Data again now with Decision Trees"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.svm import SVC\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "\n",
+ "# Load the data\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "print(X_train.shape)\n",
+ "print(X_test.shape)\n",
+ "# Logistic Regression\n",
+ "logreg = LogisticRegression(solver='lbfgs')\n",
+ "logreg.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
+ "# Support vector machine\n",
+ "svm = SVC(gamma='auto', C=100)\n",
+ "svm.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n",
+ "# Decision Trees\n",
+ "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n",
+ "deep_tree_clf.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n",
+ "#now scale the data\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "scaler = StandardScaler()\n",
+ "scaler.fit(X_train)\n",
+ "X_train_scaled = scaler.transform(X_train)\n",
+ "X_test_scaled = scaler.transform(X_test)\n",
+ "# Logistic Regression\n",
+ "logreg.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
+ "# Support Vector Machine\n",
+ "svm.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
+ "# Decision Trees\n",
+ "deep_tree_clf.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Another example, the moons again"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from __future__ import division, print_function, unicode_literals\n",
+ "\n",
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import os\n",
+ "\n",
+ "# to make this notebook's output stable across runs\n",
+ "np.random.seed(42)\n",
+ "\n",
+ "# To plot pretty figures\n",
+ "import matplotlib\n",
+ "import matplotlib.pyplot as plt\n",
+ "from matplotlib.colors import ListedColormap\n",
+ "plt.rcParams['axes.labelsize'] = 14\n",
+ "plt.rcParams['xtick.labelsize'] = 12\n",
+ "plt.rcParams['ytick.labelsize'] = 12\n",
+ "\n",
+ "\n",
+ "from sklearn.svm import SVC\n",
+ "from sklearn import datasets\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "from sklearn.datasets import make_moons\n",
+ "from sklearn.tree import export_graphviz\n",
+ "\n",
+ "Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)\n",
+ "\n",
+ "deep_tree_clf1 = DecisionTreeClassifier(random_state=42)\n",
+ "deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)\n",
+ "deep_tree_clf1.fit(Xm, ym)\n",
+ "deep_tree_clf2.fit(Xm, ym)\n",
+ "\n",
+ "\n",
+ "def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):\n",
+ " x1s = np.linspace(axes[0], axes[1], 100)\n",
+ " x2s = np.linspace(axes[2], axes[3], 100)\n",
+ " x1, x2 = np.meshgrid(x1s, x2s)\n",
+ " X_new = np.c_[x1.ravel(), x2.ravel()]\n",
+ " y_pred = clf.predict(X_new).reshape(x1.shape)\n",
+ " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
+ " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
+ " if not iris:\n",
+ " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
+ " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
+ " if plot_training:\n",
+ " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", label=\"Iris-Setosa\")\n",
+ " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", label=\"Iris-Versicolor\")\n",
+ " plt.plot(X[:, 0][y==2], X[:, 1][y==2], \"g^\", label=\"Iris-Virginica\")\n",
+ " plt.axis(axes)\n",
+ " if iris:\n",
+ " plt.xlabel(\"Petal length\", fontsize=14)\n",
+ " plt.ylabel(\"Petal width\", fontsize=14)\n",
+ " else:\n",
+ " plt.xlabel(r\"$x_1$\", fontsize=18)\n",
+ " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
+ " if legend:\n",
+ " plt.legend(loc=\"lower right\", fontsize=14)\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "plt.subplot(121)\n",
+ "plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n",
+ "plt.title(\"No restrictions\", fontsize=16)\n",
+ "plt.subplot(122)\n",
+ "plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n",
+ "plt.title(\"min_samples_leaf = {}\".format(deep_tree_clf2.min_samples_leaf), fontsize=14)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Playing around with regions"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "np.random.seed(6)\n",
+ "Xs = np.random.rand(100, 2) - 0.5\n",
+ "ys = (Xs[:, 0] > 0).astype(np.float32) * 2\n",
+ "\n",
+ "angle = np.pi / 4\n",
+ "rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n",
+ "Xsr = Xs.dot(rotation_matrix)\n",
+ "\n",
+ "tree_clf_s = DecisionTreeClassifier(random_state=42)\n",
+ "tree_clf_s.fit(Xs, ys)\n",
+ "tree_clf_sr = DecisionTreeClassifier(random_state=42)\n",
+ "tree_clf_sr.fit(Xsr, ys)\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "plt.subplot(121)\n",
+ "plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n",
+ "plt.subplot(122)\n",
+ "plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Regression trees"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# Quadratic training set + noise\n",
+ "np.random.seed(42)\n",
+ "m = 200\n",
+ "X = np.random.rand(m, 1)\n",
+ "y = 4 * (X - 0.5) ** 2\n",
+ "y = y + np.random.randn(m, 1) / 10"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.tree import DecisionTreeRegressor\n",
+ "\n",
+ "tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n",
+ "tree_reg.fit(X, y)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Final regressor code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.tree import DecisionTreeRegressor\n",
+ "\n",
+ "tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n",
+ "tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n",
+ "tree_reg1.fit(X, y)\n",
+ "tree_reg2.fit(X, y)\n",
+ "\n",
+ "def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n",
+ " x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n",
+ " y_pred = tree_reg.predict(x1)\n",
+ " plt.axis(axes)\n",
+ " plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ " if ylabel:\n",
+ " plt.ylabel(ylabel, fontsize=18, rotation=0)\n",
+ " plt.plot(X, y, \"b.\")\n",
+ " plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "plt.subplot(121)\n",
+ "plot_regression_predictions(tree_reg1, X, y)\n",
+ "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
+ " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
+ "plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n",
+ "plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n",
+ "plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n",
+ "plt.legend(loc=\"upper center\", fontsize=18)\n",
+ "plt.title(\"max_depth=2\", fontsize=14)\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n",
+ "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
+ " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
+ "for split in (0.0458, 0.1298, 0.2873, 0.9040):\n",
+ " plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n",
+ "plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n",
+ "plt.title(\"max_depth=3\", fontsize=14)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "tree_reg1 = DecisionTreeRegressor(random_state=42)\n",
+ "tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n",
+ "tree_reg1.fit(X, y)\n",
+ "tree_reg2.fit(X, y)\n",
+ "\n",
+ "x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n",
+ "y_pred1 = tree_reg1.predict(x1)\n",
+ "y_pred2 = tree_reg2.predict(x1)\n",
+ "\n",
+ "plt.figure(figsize=(11, 4))\n",
+ "\n",
+ "plt.subplot(121)\n",
+ "plt.plot(X, y, \"b.\")\n",
+ "plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "plt.axis([0, 1, -0.2, 1.1])\n",
+ "plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ "plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n",
+ "plt.legend(loc=\"upper center\", fontsize=18)\n",
+ "plt.title(\"No restrictions\", fontsize=14)\n",
+ "\n",
+ "plt.subplot(122)\n",
+ "plt.plot(X, y, \"b.\")\n",
+ "plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
+ "plt.axis([0, 1, -0.2, 1.1])\n",
+ "plt.xlabel(\"$x_1$\", fontsize=18)\n",
+ "plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Pros and cons of trees, pros\n",
+ "\n",
+ "* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)\n",
+ "\n",
+ "* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n",
+ "\n",
+ "* No feature normalization needed\n",
+ "\n",
+ "* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n",
+ "\n",
+ "* Can model nonlinear relationships\n",
+ "\n",
+ "* Can model interactions between the different descriptive features\n",
+ "\n",
+ "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)\n",
+ "\n",
+ "## Disadvantages\n",
+ "\n",
+ "* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n",
+ "\n",
+ "* If continuous features are used the tree may become quite large and hence less interpretable\n",
+ "\n",
+ "* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented\n",
+ "\n",
+ "* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests\n",
+ "\n",
+ "* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. \n",
+ "\n",
+ "* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n",
+ "\n",
+ "* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain\n",
+ "\n",
+ "However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved. \n",
+ "\n",
+ "## Bagging\n",
+ "\n",
+ "The **plain** decision trees suffer from high\n",
+ "variance. This means that if we split the training data into two parts\n",
+ "at random, and fit a decision tree to both halves, the results that we\n",
+ "get could be quite different. In contrast, a procedure with low\n",
+ "variance will yield similar results if applied repeatedly to distinct\n",
+ "data sets; linear regression tends to have low variance, if the ratio\n",
+ "of $n$ to $p$ is moderately large. \n",
+ "\n",
+ "**Bootstrap aggregation**, or just **bagging**, is a\n",
+ "general-purpose procedure for reducing the variance of a statistical\n",
+ "learning method. \n",
+ "\n",
+ "\n",
+ "Bagging typically results in improved accuracy\n",
+ "over prediction using a single tree. Unfortunately, however, it can be\n",
+ "difficult to interpret the resulting model. Recall that one of the\n",
+ "advantages of decision trees is the attractive and easily interpreted\n",
+ "diagram that results.\n",
+ "\n",
+ "However, when we bag a large number of trees, it is no longer\n",
+ "possible to represent the resulting statistical learning procedure\n",
+ "using a single tree, and it is no longer clear which variables are\n",
+ "most important to the procedure. Thus, bagging improves prediction\n",
+ "accuracy at the expense of interpretability. Although the collection\n",
+ "of bagged trees is much more difficult to interpret than a single\n",
+ "tree, one can obtain an overall summary of the importance of each\n",
+ "predictor using the MSE (for bagging regression trees) or the Gini\n",
+ "index (for bagging classification trees). In the case of bagging\n",
+ "regression trees, we can record the total amount that the MSE is\n",
+ "decreased due to splits over a given predictor, averaged over all $B$ possible\n",
+ "trees. A large value indicates an important predictor. Similarly, in\n",
+ "the context of bagging classification trees, we can add up the total\n",
+ "amount that the Gini index is decreased by splits over a given\n",
+ "predictor, averaged over all $B$ trees.\n",
+ "\n",
+ "## Simple example, head or tail"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "heads_proba = 0.51\n",
+ "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n",
+ "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n",
+ "plt.figure(figsize=(8,3.5))\n",
+ "plt.plot(cumulative_heads_ratio)\n",
+ "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n",
+ "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n",
+ "plt.xlabel(\"Number of coin tosses\")\n",
+ "plt.ylabel(\"Heads ratio\")\n",
+ "plt.legend(loc=\"lower right\")\n",
+ "plt.axis([0, 10000, 0.42, 0.58])\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Random forests\n",
+ "\n",
+ "Random forests provide an improvement over bagged trees by way of a\n",
+ "small tweak that decorrelates the trees. \n",
+ "\n",
+ "As in bagging, we build a\n",
+ "number of decision trees on bootstrapped training samples. But when\n",
+ "building these decision trees, each time a split in a tree is\n",
+ "considered, a random sample of $m$ predictors is chosen as split\n",
+ "candidates from the full set of $p$ predictors. The split is allowed to\n",
+ "use only one of those $m$ predictors. \n",
+ "\n",
+ "A fresh sample of $m$ predictors is\n",
+ "taken at each split, and typically we choose"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "m\\approx \\sqrt{p}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In building a random forest, at\n",
+ "each split in the tree, the algorithm is not even allowed to consider\n",
+ "a majority of the available predictors. \n",
+ "\n",
+ "The reason for this is rather clever. Suppose that there is one very\n",
+ "strong predictor in the data set, along with a number of other\n",
+ "moderately strong predictors. Then in the collection of bagged\n",
+ "variable importance random forest trees, most or all of the trees will\n",
+ "use this strong predictor in the top split. Consequently, all of the\n",
+ "bagged trees will look quite similar to each other. Hence the\n",
+ "predictions from the bagged trees will be highly correlated.\n",
+ "Unfortunately, averaging many highly correlated quantities does not\n",
+ "lead to as large of a reduction in variance as averaging many\n",
+ "uncorrelated quanti- ties. In particular, this means that bagging will\n",
+ "not lead to a substantial reduction in variance over a single tree in\n",
+ "this setting.\n",
+ "\n",
+ "## A simple scikit-learn example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.ensemble import RandomForestClassifier\n",
+ "from sklearn.preprocessing import LabelEncoder\n",
+ "from sklearn.model_selection import cross_validate\n",
+ "# Data set not specificied\n",
+ "X = dataset.XXX\n",
+ "Y = dataset.YYY\n",
+ "#Instantiate the model with 100 trees and entropy as splitting criteria\n",
+ "Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion=\"entropy\")\n",
+ "#Cross validation\n",
+ "accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Please, not the moons again!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.datasets import make_moons\n",
+ "\n",
+ "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
+ "from sklearn.ensemble import RandomForestClassifier\n",
+ "from sklearn.ensemble import VotingClassifier\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "from sklearn.svm import SVC\n",
+ "\n",
+ "log_clf = LogisticRegression(random_state=42)\n",
+ "rnd_clf = RandomForestClassifier(random_state=42)\n",
+ "svm_clf = SVC(random_state=42)\n",
+ "\n",
+ "voting_clf = VotingClassifier(\n",
+ " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
+ " voting='hard')\n",
+ "voting_clf.fit(X_train, y_train)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.metrics import accuracy_score\n",
+ "\n",
+ "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
+ " clf.fit(X_train, y_train)\n",
+ " y_pred = clf.predict(X_test)\n",
+ " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "log_clf = LogisticRegression(random_state=42)\n",
+ "rnd_clf = RandomForestClassifier(random_state=42)\n",
+ "svm_clf = SVC(probability=True, random_state=42)\n",
+ "\n",
+ "voting_clf = VotingClassifier(\n",
+ " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
+ " voting='soft')\n",
+ "voting_clf.fit(X_train, y_train)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.metrics import accuracy_score\n",
+ "\n",
+ "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
+ " clf.fit(X_train, y_train)\n",
+ " y_pred = clf.predict(X_test)\n",
+ " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Bagging examples"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.ensemble import BaggingClassifier\n",
+ "from sklearn.tree import DecisionTreeClassifier\n",
+ "\n",
+ "bag_clf = BaggingClassifier(\n",
+ " DecisionTreeClassifier(random_state=42), n_estimators=500,\n",
+ " max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)\n",
+ "bag_clf.fit(X_train, y_train)\n",
+ "y_pred = bag_clf.predict(X_test)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from sklearn.metrics import accuracy_score\n",
+ "print(accuracy_score(y_test, y_pred))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "tree_clf = DecisionTreeClassifier(random_state=42)\n",
+ "tree_clf.fit(X_train, y_train)\n",
+ "y_pred_tree = tree_clf.predict(X_test)\n",
+ "print(accuracy_score(y_test, y_pred_tree))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "from matplotlib.colors import ListedColormap\n",
+ "\n",
+ "def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):\n",
+ " x1s = np.linspace(axes[0], axes[1], 100)\n",
+ " x2s = np.linspace(axes[2], axes[3], 100)\n",
+ " x1, x2 = np.meshgrid(x1s, x2s)\n",
+ " X_new = np.c_[x1.ravel(), x2.ravel()]\n",
+ " y_pred = clf.predict(X_new).reshape(x1.shape)\n",
+ " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
+ " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
+ " if contour:\n",
+ " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
+ " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
+ " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=alpha)\n",
+ " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=alpha)\n",
+ " plt.axis(axes)\n",
+ " plt.xlabel(r\"$x_1$\", fontsize=18)\n",
+ " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
+ "plt.figure(figsize=(11,4))\n",
+ "plt.subplot(121)\n",
+ "plot_decision_boundary(tree_clf, X, y)\n",
+ "plt.title(\"Decision Tree\", fontsize=14)\n",
+ "plt.subplot(122)\n",
+ "plot_decision_boundary(bag_clf, X, y)\n",
+ "plt.title(\"Decision Trees with Bagging\", fontsize=14)\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Then random forests"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "bag_clf = BaggingClassifier(\n",
+ " DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n",
+ " n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "bag_clf.fit(X_train, y_train)\n",
+ "y_pred = bag_clf.predict(X_test)\n",
+ "from sklearn.ensemble import RandomForestClassifier\n",
+ "rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)\n",
+ "rnd_clf.fit(X_train, y_train)\n",
+ "y_pred_rf = rnd_clf.predict(X_test)\n",
+ "np.sum(y_pred == y_pred_rf) / len(y_pred)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "## Boosting and more\n",
+ "More material to come here."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/doc/src/DecisionTrees/DecisionTrees.p.tex b/doc/src/DecisionTrees/DecisionTrees.p.tex
new file mode 100644
index 000000000..a76b30666
--- /dev/null
+++ b/doc/src/DecisionTrees/DecisionTrees.p.tex
@@ -0,0 +1,1160 @@
+%%
+%% Automatically generated file from DocOnce source
+%% (https://github.com/hplgit/doconce/)
+%%
+%%
+% #ifdef PTEX2TEX_EXPLANATION
+%%
+%% The file follows the ptex2tex extended LaTeX format, see
+%% ptex2tex: http://code.google.com/p/ptex2tex/
+%%
+%% Run
+%% ptex2tex myfile
+%% or
+%% doconce ptex2tex myfile
+%%
+%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex.
+%% (The ptex2tex program: http://code.google.com/p/ptex2tex)
+%% Many preprocess options can be added to ptex2tex or doconce ptex2tex
+%%
+%% ptex2tex -DMINTED myfile
+%% doconce ptex2tex myfile envir=minted
+%%
+%% ptex2tex will typeset code environments according to a global or local
+%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code
+%% according to options on the command line (just type doconce ptex2tex to
+%% see examples). If doconce ptex2tex has envir=minted, it enables the
+%% minted style without needing -DMINTED.
+% #endif
+
+% #define PREAMBLE
+
+% #ifdef PREAMBLE
+%-------------------- begin preamble ----------------------
+
+\documentclass[%
+oneside, % oneside: electronic viewing, twoside: printing
+final, % draft: marks overfull hboxes, figures with paths
+10pt]{article}
+
+\listfiles % print all files needed to compile this document
+
+\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}
+\usepackage[table]{xcolor}
+\usepackage{bm,ltablex,microtype}
+
+\usepackage[pdftex]{graphicx}
+
+\usepackage{ptex2tex}
+% #ifdef MINTED
+\usepackage{minted}
+\usemintedstyle{default}
+% #endif
+
+\usepackage[T1]{fontenc}
+%\usepackage[latin1]{inputenc}
+\usepackage{ucs}
+\usepackage[utf8x]{inputenc}
+
+\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern
+
+% Hyperlinks in PDF:
+\definecolor{linkcolor}{rgb}{0,0,0.4}
+\usepackage{hyperref}
+\hypersetup{
+ breaklinks=true,
+ colorlinks=true,
+ linkcolor=linkcolor,
+ urlcolor=linkcolor,
+ citecolor=black,
+ filecolor=black,
+ %filecolor=blue,
+ pdfmenubar=true,
+ pdftoolbar=true,
+ bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC
+ }
+%\hyperbaseurl{} % hyperlinks are relative to this root
+
+\setcounter{tocdepth}{2} % levels in table of contents
+
+% --- fancyhdr package for fancy headers ---
+\usepackage{fancyhdr}
+\fancyhf{} % sets both header and footer to nothing
+\renewcommand{\headrulewidth}{0pt}
+\fancyfoot[LE,RO]{\thepage}
+% Ensure copyright on titlepage (article style) and chapter pages (book style)
+\fancypagestyle{plain}{
+ \fancyhf{}
+ \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}}
+% \renewcommand{\footrulewidth}{0mm}
+ \renewcommand{\headrulewidth}{0mm}
+}
+% Ensure copyright on titlepages with \thispagestyle{empty}
+\fancypagestyle{empty}{
+ \fancyhf{}
+ \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}}
+ \renewcommand{\footrulewidth}{0mm}
+ \renewcommand{\headrulewidth}{0mm}
+}
+
+\pagestyle{fancy}
+
+
+\usepackage[framemethod=TikZ]{mdframed}
+
+% --- begin definitions of admonition environments ---
+
+% --- end of definitions of admonition environments ---
+
+% prevent orhpans and widows
+\clubpenalty = 10000
+\widowpenalty = 10000
+
+% --- end of standard preamble for documents ---
+
+
+% insert custom LaTeX commands...
+
+\raggedbottom
+\makeindex
+\usepackage[totoc]{idxlayout} % for index in the toc
+\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc
+
+%-------------------- end preamble ----------------------
+
+\begin{document}
+
+% matching end for #ifdef PREAMBLE
+% #endif
+
+\newcommand{\exercisesection}[1]{\subsection*{#1}}
+
+
+% ------------------- main content ----------------------
+
+
+
+% ----------------- title -------------------------
+
+\thispagestyle{empty}
+
+\begin{center}
+{\LARGE\bf
+\begin{spacing}{1.25}
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+\end{spacing}
+}
+\end{center}
+
+% ----------------- author(s) -------------------------
+
+\begin{center}
+{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm]
+\end{center}
+
+\begin{center}
+% List of all institutions:
+\centerline{{\small ${}^1$Department of Physics, University of Oslo}}
+\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}}
+\end{center}
+
+% ----------------- end author(s) -------------------------
+
+% --- begin date ---
+\begin{center}
+Oct 26, 2019
+\end{center}
+% --- end date ---
+
+\vspace{1cm}
+
+
+% !split
+\subsection{Decision trees, overarching aims}
+
+
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+\textbf{information} regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the \textbf{most
+informative} feature is done until we accomplish a stopping criteria
+where we then finally end up in so called \textbf{leaf nodes}.
+
+A decision tree is typically divided into a \textbf{root node}, the \textbf{interior nodes},
+and the final \textbf{leaf nodes} or just \textbf{leaves}. These entities are then connected by so-called \textbf{branches}.
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+% !split
+\subsection{A typical Decision Tree with its pertinent Jargon, Classification Problem}
+
+In the figure here we present a decision tree obtained from a classification problem
+
+
+% !split
+\subsection{A typical Decision Tree with its pertinent Jargon, Regeression Problem}
+
+In the figure we present a decision tree obtained from a simple regression problem
+
+
+% !split
+\subsection{General Features}
+
+The overarching approach to decision trees is a top-down approach.
+
+\begin{itemize}
+\item A leaf provides the classification of a given instance.
+
+\item A node specifies a test of some attribute of the instance.
+
+\item A branch corresponds to a possible values of an attribute.
+
+\item An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+\end{itemize}
+
+\noindent
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+% !split
+\subsection{How do we set it up?}
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+\begin{enumerate}
+\item Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
+\item Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
+\item Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the \emph{predictions} we want to make for new query instances
+
+\item Show query instances to the tree and run down the tree until we arrive at leaf nodes
+\end{enumerate}
+
+\noindent
+Then we are essentially done!
+
+
+
+
+
+% !split
+\subsection{Decision trees and Regression}
+\bpycod
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x 0).astype(np.float32) * 2
+
+angle = np.pi / 4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+\epycod
+
+% !split
+\subsection{Regression trees}
+\bpycod
+# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+\epycod
+
+\bpycod
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+\epycod
+
+% !split
+\subsection{Final regressor code}
+\bpycod
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+\epycod
+
+\bpycod
+tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+\epycod
+
+
+
+% !split
+\subsection{Pros and cons of trees, pros}
+
+\begin{itemize}
+\item White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+
+\item Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+
+\item No feature normalization needed
+
+\item Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+
+\item Can model nonlinear relationships
+
+\item Can model interactions between the different descriptive features
+
+\item Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+\end{itemize}
+
+\noindent
+% !split
+\subsection{Disadvantages}
+
+\begin{itemize}
+\item Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+
+\item If continuous features are used the tree may become quite large and hence less interpretable
+
+\item Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+
+\item Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+
+\item Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+
+\item If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+
+\item Features with many levels may be preferred over features with less levels since for them it is \emph{more easy} to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+\end{itemize}
+
+\noindent
+However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
+
+% !split
+\subsection{Bagging}
+
+The \textbf{plain} decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of $n$ to $p$ is moderately large.
+
+\textbf{Bootstrap aggregation}, or just \textbf{bagging}, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all $B$ possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all $B$ trees.
+
+% !split
+\subsection{Simple example, head or tail}
+\bpycod
+heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+plt.show()
+
+\epycod
+
+
+% !split
+\subsection{Random forests}
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of $m$ predictors is chosen as split
+candidates from the full set of $p$ predictors. The split is allowed to
+use only one of those $m$ predictors.
+
+A fresh sample of $m$ predictors is
+taken at each split, and typically we choose
+
+\[
+m\approx \sqrt{p}.
+\]
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+% !split
+\subsection{A simple scikit-learn example}
+\bpycod
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+X = dataset.XXX
+Y = dataset.YYY
+#Instantiate the model with 100 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
+\epycod
+
+% !split
+\subsection{Please, not the moons again!}
+\bpycod
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+voting_clf.fit(X_train, y_train)
+\epycod
+
+\bpycod
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+\epycod
+
+\bpycod
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+\epycod
+
+\bpycod
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+\epycod
+
+% !split
+\subsection{Bagging examples}
+
+\bpycod
+from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(random_state=42), n_estimators=500,
+ max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+\epycod
+
+
+\bpycod
+from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+\epycod
+
+\bpycod
+tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+\epycod
+
+\bpycod
+from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if contour:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+ plt.axis(axes)
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+plt.show()
+\epycod
+
+% !split
+\subsection{Then random forests}
+\bpycod
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+ n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+\epycod
+
+
+
+\bpycod
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred)
+\epycod
+
+
+% !split
+\subsection{Boosting and more}
+More material to come here.
+
+
+
+% ------------------- end of main content ---------------
+
+% #ifdef PREAMBLE
+\end{document}
+% #endif
+
diff --git a/doc/src/DecisionTrees/DecisionTrees.tex b/doc/src/DecisionTrees/DecisionTrees.tex
new file mode 100644
index 000000000..f125241e4
--- /dev/null
+++ b/doc/src/DecisionTrees/DecisionTrees.tex
@@ -0,0 +1,1130 @@
+%%
+%% Automatically generated file from DocOnce source
+%% (https://github.com/hplgit/doconce/)
+%%
+%%
+
+
+%-------------------- begin preamble ----------------------
+
+\documentclass[%
+oneside, % oneside: electronic viewing, twoside: printing
+final, % draft: marks overfull hboxes, figures with paths
+10pt]{article}
+
+\listfiles % print all files needed to compile this document
+
+\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}
+\usepackage[table]{xcolor}
+\usepackage{bm,ltablex,microtype}
+
+\usepackage[pdftex]{graphicx}
+
+\usepackage{fancyvrb} % packages needed for verbatim environments
+\usepackage{minted}
+\usemintedstyle{default}
+
+\usepackage[T1]{fontenc}
+%\usepackage[latin1]{inputenc}
+\usepackage{ucs}
+\usepackage[utf8x]{inputenc}
+
+\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern
+
+% Hyperlinks in PDF:
+\definecolor{linkcolor}{rgb}{0,0,0.4}
+\usepackage{hyperref}
+\hypersetup{
+ breaklinks=true,
+ colorlinks=true,
+ linkcolor=linkcolor,
+ urlcolor=linkcolor,
+ citecolor=black,
+ filecolor=black,
+ %filecolor=blue,
+ pdfmenubar=true,
+ pdftoolbar=true,
+ bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC
+ }
+%\hyperbaseurl{} % hyperlinks are relative to this root
+
+\setcounter{tocdepth}{2} % levels in table of contents
+
+% --- fancyhdr package for fancy headers ---
+\usepackage{fancyhdr}
+\fancyhf{} % sets both header and footer to nothing
+\renewcommand{\headrulewidth}{0pt}
+\fancyfoot[LE,RO]{\thepage}
+% Ensure copyright on titlepage (article style) and chapter pages (book style)
+\fancypagestyle{plain}{
+ \fancyhf{}
+ \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}}
+% \renewcommand{\footrulewidth}{0mm}
+ \renewcommand{\headrulewidth}{0mm}
+}
+% Ensure copyright on titlepages with \thispagestyle{empty}
+\fancypagestyle{empty}{
+ \fancyhf{}
+ \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}}
+ \renewcommand{\footrulewidth}{0mm}
+ \renewcommand{\headrulewidth}{0mm}
+}
+
+\pagestyle{fancy}
+
+
+\usepackage[framemethod=TikZ]{mdframed}
+
+% --- begin definitions of admonition environments ---
+
+% --- end of definitions of admonition environments ---
+
+% prevent orhpans and widows
+\clubpenalty = 10000
+\widowpenalty = 10000
+
+% --- end of standard preamble for documents ---
+
+
+% insert custom LaTeX commands...
+
+\raggedbottom
+\makeindex
+\usepackage[totoc]{idxlayout} % for index in the toc
+\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc
+
+%-------------------- end preamble ----------------------
+
+\begin{document}
+
+% matching end for #ifdef PREAMBLE
+
+\newcommand{\exercisesection}[1]{\subsection*{#1}}
+
+
+% ------------------- main content ----------------------
+
+
+
+% ----------------- title -------------------------
+
+\thispagestyle{empty}
+
+\begin{center}
+{\LARGE\bf
+\begin{spacing}{1.25}
+Data Analysis and Machine Learning: From Decision Trees to Forests and all that
+\end{spacing}
+}
+\end{center}
+
+% ----------------- author(s) -------------------------
+
+\begin{center}
+{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm]
+\end{center}
+
+\begin{center}
+% List of all institutions:
+\centerline{{\small ${}^1$Department of Physics, University of Oslo}}
+\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}}
+\end{center}
+
+% ----------------- end author(s) -------------------------
+
+% --- begin date ---
+\begin{center}
+Oct 26, 2019
+\end{center}
+% --- end date ---
+
+\vspace{1cm}
+
+
+% !split
+\subsection*{Decision trees, overarching aims}
+
+
+Decision trees are supervised learning algorithms used for both,
+classification and regression tasks.
+
+
+The main idea of decision trees
+is to find those descriptive features which contain the most
+\textbf{information} regarding the target feature and then split the dataset
+along the values of these features such that the target feature values
+for the resulting underlying datasets are as pure as possible.
+
+The descriptive features which reproduce best the target/output features are normally said
+to be the most informative ones. The process of finding the \textbf{most
+informative} feature is done until we accomplish a stopping criteria
+where we then finally end up in so called \textbf{leaf nodes}.
+
+A decision tree is typically divided into a \textbf{root node}, the \textbf{interior nodes},
+and the final \textbf{leaf nodes} or just \textbf{leaves}. These entities are then connected by so-called \textbf{branches}.
+
+The leaf nodes
+contain the predictions we will make for new query instances presented
+to our trained model. This is possible since the model has
+learned the underlying structure of the training data and hence can,
+given some assumptions, make predictions about the target feature value
+(class) of unseen query instances.
+
+% !split
+\subsection*{A typical Decision Tree with its pertinent Jargon, Classification Problem}
+
+In the figure here we present a decision tree obtained from a classification problem
+
+
+% !split
+\subsection*{A typical Decision Tree with its pertinent Jargon, Regeression Problem}
+
+In the figure we present a decision tree obtained from a simple regression problem
+
+
+% !split
+\subsection*{General Features}
+
+The overarching approach to decision trees is a top-down approach.
+
+\begin{itemize}
+\item A leaf provides the classification of a given instance.
+
+\item A node specifies a test of some attribute of the instance.
+
+\item A branch corresponds to a possible values of an attribute.
+
+\item An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
+\end{itemize}
+
+\noindent
+This process is then repeated for the subtree rooted at the new
+node.
+
+
+% !split
+\subsection*{How do we set it up?}
+
+
+In simplified terms, the process of training a decision tree and
+predicting the target features of query instances is as follows:
+
+\begin{enumerate}
+\item Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
+
+\item Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
+
+\item Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the \emph{predictions} we want to make for new query instances
+
+\item Show query instances to the tree and run down the tree until we arrive at leaf nodes
+\end{enumerate}
+
+\noindent
+Then we are essentially done!
+
+
+
+
+
+% !split
+\subsection*{Decision trees and Regression}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x 0).astype(np.float32) * 2
+
+angle = np.pi / 4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+\end{minted}
+
+% !split
+\subsection*{Regression trees}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+\end{minted}
+
+% !split
+\subsection*{Final regressor code}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+ x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+ y_pred = tree_reg.predict(x1)
+ plt.axis(axes)
+ plt.xlabel("$x_1$", fontsize=18)
+ if ylabel:
+ plt.ylabel(ylabel, fontsize=18, rotation=0)
+ plt.plot(X, y, "b.")
+ plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+ plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+ plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+\end{minted}
+
+
+
+% !split
+\subsection*{Pros and cons of trees, pros}
+
+\begin{itemize}
+\item White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
+
+\item Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
+
+\item No feature normalization needed
+
+\item Tree models can handle both continuous and categorical data (Classification and Regression Trees)
+
+\item Can model nonlinear relationships
+
+\item Can model interactions between the different descriptive features
+
+\item Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
+\end{itemize}
+
+\noindent
+% !split
+\subsection*{Disadvantages}
+
+\begin{itemize}
+\item Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
+
+\item If continuous features are used the tree may become quite large and hence less interpretable
+
+\item Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
+
+\item Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
+
+\item Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
+
+\item If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
+
+\item Features with many levels may be preferred over features with less levels since for them it is \emph{more easy} to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
+\end{itemize}
+
+\noindent
+However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
+
+% !split
+\subsection*{Bagging}
+
+The \textbf{plain} decision trees suffer from high
+variance. This means that if we split the training data into two parts
+at random, and fit a decision tree to both halves, the results that we
+get could be quite different. In contrast, a procedure with low
+variance will yield similar results if applied repeatedly to distinct
+data sets; linear regression tends to have low variance, if the ratio
+of $n$ to $p$ is moderately large.
+
+\textbf{Bootstrap aggregation}, or just \textbf{bagging}, is a
+general-purpose procedure for reducing the variance of a statistical
+learning method.
+
+
+Bagging typically results in improved accuracy
+over prediction using a single tree. Unfortunately, however, it can be
+difficult to interpret the resulting model. Recall that one of the
+advantages of decision trees is the attractive and easily interpreted
+diagram that results.
+
+However, when we bag a large number of trees, it is no longer
+possible to represent the resulting statistical learning procedure
+using a single tree, and it is no longer clear which variables are
+most important to the procedure. Thus, bagging improves prediction
+accuracy at the expense of interpretability. Although the collection
+of bagged trees is much more difficult to interpret than a single
+tree, one can obtain an overall summary of the importance of each
+predictor using the MSE (for bagging regression trees) or the Gini
+index (for bagging classification trees). In the case of bagging
+regression trees, we can record the total amount that the MSE is
+decreased due to splits over a given predictor, averaged over all $B$ possible
+trees. A large value indicates an important predictor. Similarly, in
+the context of bagging classification trees, we can add up the total
+amount that the Gini index is decreased by splits over a given
+predictor, averaged over all $B$ trees.
+
+% !split
+\subsection*{Simple example, head or tail}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+plt.show()
+
+\end{minted}
+
+
+% !split
+\subsection*{Random forests}
+
+Random forests provide an improvement over bagged trees by way of a
+small tweak that decorrelates the trees.
+
+As in bagging, we build a
+number of decision trees on bootstrapped training samples. But when
+building these decision trees, each time a split in a tree is
+considered, a random sample of $m$ predictors is chosen as split
+candidates from the full set of $p$ predictors. The split is allowed to
+use only one of those $m$ predictors.
+
+A fresh sample of $m$ predictors is
+taken at each split, and typically we choose
+
+\[
+m\approx \sqrt{p}.
+\]
+
+In building a random forest, at
+each split in the tree, the algorithm is not even allowed to consider
+a majority of the available predictors.
+
+The reason for this is rather clever. Suppose that there is one very
+strong predictor in the data set, along with a number of other
+moderately strong predictors. Then in the collection of bagged
+variable importance random forest trees, most or all of the trees will
+use this strong predictor in the top split. Consequently, all of the
+bagged trees will look quite similar to each other. Hence the
+predictions from the bagged trees will be highly correlated.
+Unfortunately, averaging many highly correlated quantities does not
+lead to as large of a reduction in variance as averaging many
+uncorrelated quanti- ties. In particular, this means that bagging will
+not lead to a substantial reduction in variance over a single tree in
+this setting.
+
+% !split
+\subsection*{A simple scikit-learn example}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+X = dataset.XXX
+Y = dataset.YYY
+#Instantiate the model with 100 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
+\end{minted}
+
+% !split
+\subsection*{Please, not the moons again!}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+voting_clf.fit(X_train, y_train)
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+\end{minted}
+
+% !split
+\subsection*{Bagging examples}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(random_state=42), n_estimators=500,
+ max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+\end{minted}
+
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+\end{minted}
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+ x1s = np.linspace(axes[0], axes[1], 100)
+ x2s = np.linspace(axes[2], axes[3], 100)
+ x1, x2 = np.meshgrid(x1s, x2s)
+ X_new = np.c_[x1.ravel(), x2.ravel()]
+ y_pred = clf.predict(X_new).reshape(x1.shape)
+ custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+ plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+ if contour:
+ custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+ plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+ plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+ plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+ plt.axis(axes)
+ plt.xlabel(r"$x_1$", fontsize=18)
+ plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+plt.show()
+\end{minted}
+
+% !split
+\subsection*{Then random forests}
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+ n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+\end{minted}
+
+
+
+\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python}
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred)
+\end{minted}
+
+
+% !split
+\subsection*{Boosting and more}
+More material to come here.
+
+
+
+% ------------------- end of main content ---------------
+
+\end{document}
+
diff --git a/doc/src/DecisionTrees/README.txt b/doc/src/DecisionTrees/README.txt
new file mode 100644
index 000000000..2b30616f8
--- /dev/null
+++ b/doc/src/DecisionTrees/README.txt
@@ -0,0 +1,2 @@
+This IPython notebook DecisionTrees.ipynb does not require any additional
+programs.
diff --git a/doc/src/DecisionTrees/_minted-DecisionTrees/default.pygstyle b/doc/src/DecisionTrees/_minted-DecisionTrees/default.pygstyle
new file mode 100644
index 000000000..e69de29bb
diff --git a/doc/src/DecisionTrees/ipynb-DecisionTrees-src.tar.gz b/doc/src/DecisionTrees/ipynb-DecisionTrees-src.tar.gz
new file mode 100644
index 000000000..d19892834
Binary files /dev/null and b/doc/src/DecisionTrees/ipynb-DecisionTrees-src.tar.gz differ
diff --git a/doc/src/DecisionTrees/reveal.js/.gitignore b/doc/src/DecisionTrees/reveal.js/.gitignore
new file mode 100644
index 000000000..a5df3133d
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/.gitignore
@@ -0,0 +1,8 @@
+.DS_Store
+.svn
+log/*.log
+tmp/**
+node_modules/
+.sass-cache
+css/reveal.min.css
+js/reveal.min.js
diff --git a/doc/src/DecisionTrees/reveal.js/.travis.yml b/doc/src/DecisionTrees/reveal.js/.travis.yml
new file mode 100644
index 000000000..165d9ae9f
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/.travis.yml
@@ -0,0 +1,5 @@
+language: node_js
+node_js:
+ - 0.10
+before_script:
+ - npm install -g grunt-cli
\ No newline at end of file
diff --git a/doc/src/DecisionTrees/reveal.js/CONTRIBUTING.md b/doc/src/DecisionTrees/reveal.js/CONTRIBUTING.md
new file mode 100644
index 000000000..c2091e88f
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/CONTRIBUTING.md
@@ -0,0 +1,23 @@
+## Contributing
+
+Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**.
+
+
+### Personal Support
+If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js).
+
+
+### Bug Reports
+When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested.
+
+
+### Pull Requests
+- Should follow the coding style of the file you work in, most importantly:
+ - Tabs to indent
+ - Single-quoted strings
+- Should be made towards the **dev branch**
+- Should be submitted from a feature/topic branch (not your master)
+
+
+### Plugins
+Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines
diff --git a/doc/src/DecisionTrees/reveal.js/Gruntfile.js b/doc/src/DecisionTrees/reveal.js/Gruntfile.js
new file mode 100644
index 000000000..b257e8f32
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/Gruntfile.js
@@ -0,0 +1,140 @@
+/* global module:false */
+module.exports = function(grunt) {
+ var port = grunt.option('port') || 8000;
+ // Project configuration
+ grunt.initConfig({
+ pkg: grunt.file.readJSON('package.json'),
+ meta: {
+ banner:
+ '/*!\n' +
+ ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
+ ' * http://lab.hakim.se/reveal-js\n' +
+ ' * MIT licensed\n' +
+ ' *\n' +
+ ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' +
+ ' */'
+ },
+
+ qunit: {
+ files: [ 'test/*.html' ]
+ },
+
+ uglify: {
+ options: {
+ banner: '<%= meta.banner %>\n'
+ },
+ build: {
+ src: 'js/reveal.js',
+ dest: 'js/reveal.min.js'
+ }
+ },
+
+ cssmin: {
+ compress: {
+ files: {
+ 'css/reveal.min.css': [ 'css/reveal.css' ]
+ }
+ }
+ },
+
+ sass: {
+ main: {
+ files: {
+ 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss',
+ 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss',
+ 'css/theme/cbc.css': 'css/theme/source/cbc.scss',
+ 'css/theme/default.css': 'css/theme/source/default.scss',
+ 'css/theme/beige.css': 'css/theme/source/beige.scss',
+ 'css/theme/night.css': 'css/theme/source/night.scss',
+ 'css/theme/serif.css': 'css/theme/source/serif.scss',
+ 'css/theme/simple.css': 'css/theme/source/simple.scss',
+ 'css/theme/sky.css': 'css/theme/source/sky.scss',
+ 'css/theme/moon.css': 'css/theme/source/moon.scss',
+ 'css/theme/solarized.css': 'css/theme/source/solarized.scss',
+ 'css/theme/blood.css': 'css/theme/source/blood.scss'
+ }
+ }
+ },
+
+ jshint: {
+ options: {
+ curly: false,
+ eqeqeq: true,
+ immed: true,
+ latedef: true,
+ newcap: true,
+ noarg: true,
+ sub: true,
+ undef: true,
+ eqnull: true,
+ browser: true,
+ expr: true,
+ globals: {
+ head: false,
+ module: false,
+ console: false,
+ unescape: false
+ }
+ },
+ files: [ 'Gruntfile.js', 'js/reveal.js' ]
+ },
+
+ connect: {
+ server: {
+ options: {
+ port: port,
+ base: '.'
+ }
+ }
+ },
+
+ zip: {
+ 'reveal-js-presentation.zip': [
+ 'index.html',
+ 'css/**',
+ 'js/**',
+ 'lib/**',
+ 'images/**',
+ 'plugin/**'
+ ]
+ },
+
+ watch: {
+ main: {
+ files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ],
+ tasks: 'default'
+ },
+ theme: {
+ files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ],
+ tasks: 'themes'
+ }
+ }
+
+ });
+
+ // Dependencies
+ grunt.loadNpmTasks( 'grunt-contrib-qunit' );
+ grunt.loadNpmTasks( 'grunt-contrib-jshint' );
+ grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
+ grunt.loadNpmTasks( 'grunt-contrib-uglify' );
+ grunt.loadNpmTasks( 'grunt-contrib-watch' );
+ grunt.loadNpmTasks( 'grunt-contrib-sass' );
+ grunt.loadNpmTasks( 'grunt-contrib-connect' );
+ grunt.loadNpmTasks( 'grunt-zip' );
+
+ // Default task
+ grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] );
+
+ // Theme task
+ grunt.registerTask( 'themes', [ 'sass' ] );
+
+ // Package presentation to archive
+ grunt.registerTask( 'package', [ 'default', 'zip' ] );
+
+ // Serve presentation locally
+ grunt.registerTask( 'serve', [ 'connect', 'watch' ] );
+
+ // Run tests
+ grunt.registerTask( 'test', [ 'jshint', 'qunit' ] );
+
+};
diff --git a/doc/src/DecisionTrees/reveal.js/LICENSE b/doc/src/DecisionTrees/reveal.js/LICENSE
new file mode 100644
index 000000000..09623076f
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/LICENSE
@@ -0,0 +1,19 @@
+Copyright (C) 2015 Hakim El Hattab, http://hakim.se
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/doc/src/DecisionTrees/reveal.js/README.md b/doc/src/DecisionTrees/reveal.js/README.md
new file mode 100644
index 000000000..573b19597
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/README.md
@@ -0,0 +1,1052 @@
+# reveal.js [](https://travis-ci.org/hakimel/reveal.js)
+
+A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/).
+
+reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere.
+
+
+#### More reading:
+- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer.
+- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history.
+- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own!
+- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks.
+- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js.
+
+## Online Editor
+
+Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com).
+
+
+## Instructions
+
+### Markup
+
+Markup hierarchy needs to be ``
`` where the ```` represents one slide and can be repeated indefinitely. If you place multiple ````'s inside of another ```` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example:
+
+```html
+
+```
+
+### Markdown
+
+It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your `````` elements and wrap the contents in a ```
+
+```
+
+#### External Markdown
+
+You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file.
+
+When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup).
+
+```html
+
+
+```
+
+#### Element Attributes
+
+Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things.
+
+```html
+
+
+
+```
+
+#### Slide Attributes
+
+Special syntax (in html comment) is available for adding attributes to the slide `` elements generated by your Markdown.
+
+```html
+
+
+
+```
+
+
+### Configuration
+
+At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below.
+
+```javascript
+Reveal.initialize({
+
+ // Display controls in the bottom right corner
+ controls: true,
+
+ // Display a presentation progress bar
+ progress: true,
+
+ // Display the page number of the current slide
+ slideNumber: false,
+
+ // Push each slide change to the browser history
+ history: false,
+
+ // Enable keyboard shortcuts for navigation
+ keyboard: true,
+
+ // Enable the slide overview mode
+ overview: true,
+
+ // Vertical centering of slides
+ center: true,
+
+ // Enables touch navigation on devices with touch input
+ touch: true,
+
+ // Loop the presentation
+ loop: false,
+
+ // Change the presentation direction to be RTL
+ rtl: false,
+
+ // Turns fragments on and off globally
+ fragments: true,
+
+ // Flags if the presentation is running in an embedded mode,
+ // i.e. contained within a limited portion of the screen
+ embedded: false,
+
+ // Flags if we should show a help overlay when the questionmark
+ // key is pressed
+ help: true,
+
+ // Number of milliseconds between automatically proceeding to the
+ // next slide, disabled when set to 0, this value can be overwritten
+ // by using a data-autoslide attribute on your slides
+ autoSlide: 0,
+
+ // Stop auto-sliding after user input
+ autoSlideStoppable: true,
+
+ // Enable slide navigation via mouse wheel
+ mouseWheel: false,
+
+ // Hides the address bar on mobile devices
+ hideAddressBar: true,
+
+ // Opens links in an iframe preview overlay
+ previewLinks: false,
+
+ // Transition style
+ transition: 'default', // none/fade/slide/convex/concave/zoom
+
+ // Transition speed
+ transitionSpeed: 'default', // default/fast/slow
+
+ // Transition style for full page slide backgrounds
+ backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom
+
+ // Number of slides away from the current that are visible
+ viewDistance: 3,
+
+ // Parallax background image
+ parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
+
+ // Parallax background size
+ parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px"
+
+ // Amount to move parallax background (horizontal and vertical) on slide change
+ // Number, e.g. 100
+ parallaxBackgroundHorizontal: '',
+ parallaxBackgroundVertical: ''
+
+});
+```
+
+
+The configuration can be updated after initialization using the ```configure``` method:
+
+```javascript
+// Turn autoSlide off
+Reveal.configure({ autoSlide: 0 });
+
+// Start auto-sliding every 5s
+Reveal.configure({ autoSlide: 5000 });
+```
+
+
+### Dependencies
+
+Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example:
+
+```javascript
+Reveal.initialize({
+ dependencies: [
+ // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/
+ { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
+
+ // Interpret Markdown in elements
+ { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
+ { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
+
+ // Syntax highlight for elements
+ { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
+
+ // Zoom in and out with Alt+click
+ { src: 'plugin/zoom-js/zoom.js', async: true },
+
+ // Speaker notes
+ { src: 'plugin/notes/notes.js', async: true },
+
+ // Remote control your reveal.js presentation using a touch device
+ { src: 'plugin/remotes/remotes.js', async: true },
+
+ // MathJax
+ { src: 'plugin/math/math.js', async: true }
+ ]
+});
+```
+
+You can add your own extensions using the same syntax. The following properties are available for each dependency object:
+- **src**: Path to the script to load
+- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false
+- **callback**: [optional] Function to execute when the script has loaded
+- **condition**: [optional] Function which must return true for the script to be loaded
+
+
+### Ready Event
+
+A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`.
+
+```javascript
+Reveal.addEventListener( 'ready', function( event ) {
+ // event.currentSlide, event.indexh, event.indexv
+} );
+```
+
+
+### Presentation Size
+
+All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport.
+
+See below for a list of configuration options related to sizing, including default values:
+
+```javascript
+Reveal.initialize({
+
+ ...
+
+ // The "normal" size of the presentation, aspect ratio will be preserved
+ // when the presentation is scaled to fit different resolutions. Can be
+ // specified using percentage units.
+ width: 960,
+ height: 700,
+
+ // Factor of the display size that should remain empty around the content
+ margin: 0.1,
+
+ // Bounds for smallest/largest possible scale to apply to content
+ minScale: 0.2,
+ maxScale: 1.5
+
+});
+```
+
+
+### Auto-sliding
+
+Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides:
+
+```javascript
+// Slide every five seconds
+Reveal.configure({
+ autoSlide: 5000
+});
+```
+When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config.
+
+You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute:
+
+```html
+
+
After 2 seconds the first fragment will be shown.
+
After 10 seconds the next fragment will be shown.
+
Now, the fragment is displayed for 2 seconds before the next slide is shown.
+
+```
+
+Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired.
+
+
+### Keyboard Bindings
+
+If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option:
+
+```javascript
+Reveal.configure({
+ keyboard: {
+ 13: 'next', // go to the next slide when the ENTER key is pressed
+ 27: function() {}, // do something custom when ESC is pressed
+ 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding)
+ }
+});
+```
+
+### Lazy Loading
+
+When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option.
+
+To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible.
+
+```html
+
+
+
+
+
+```
+
+
+### API
+
+The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state:
+
+```javascript
+// Navigation
+Reveal.slide( indexh, indexv, indexf );
+Reveal.left();
+Reveal.right();
+Reveal.up();
+Reveal.down();
+Reveal.prev();
+Reveal.next();
+Reveal.prevFragment();
+Reveal.nextFragment();
+
+// Toggle presentation states, optionally pass true/false to force on/off
+Reveal.toggleOverview();
+Reveal.togglePause();
+Reveal.toggleAutoSlide();
+
+// Change a config value at runtime
+Reveal.configure({ controls: true });
+
+// Returns the present configuration options
+Reveal.getConfig();
+
+// Fetch the current scale of the presentation
+Reveal.getScale();
+
+// Retrieves the previous and current slide elements
+Reveal.getPreviousSlide();
+Reveal.getCurrentSlide();
+
+Reveal.getIndices(); // { h: 0, v: 0 } }
+Reveal.getProgress(); // 0-1
+Reveal.getTotalSlides();
+
+// State checks
+Reveal.isFirstSlide();
+Reveal.isLastSlide();
+Reveal.isOverview();
+Reveal.isPaused();
+Reveal.isAutoSliding();
+```
+
+### Slide Changed Event
+
+A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes.
+
+Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback.
+
+```javascript
+Reveal.addEventListener( 'slidechanged', function( event ) {
+ // event.previousSlide, event.currentSlide, event.indexh, event.indexv
+} );
+```
+
+### Presentation State
+
+The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire.
+
+```javascript
+Reveal.slide( 1 );
+// we're on slide 1
+
+var state = Reveal.getState();
+
+Reveal.slide( 3 );
+// we're on slide 3
+
+Reveal.setState( state );
+// we're back on slide 1
+```
+
+### Slide States
+
+If you set ``data-state="somestate"`` on a slide ````, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide.
+
+Furthermore you can also listen to these changes in state via JavaScript:
+
+```javascript
+Reveal.addEventListener( 'somestate', function() {
+ // TODO: Sprinkle magic
+}, false );
+```
+
+### Slide Backgrounds
+
+Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your `````` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples.
+
+```html
+
+
All CSS color formats are supported, like rgba() or hsl().
+
+
+
This slide will have a full-size background image.
+
+
+
This background image will be sized to 100px and repeated.
+
+
+
Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.
+
+
+
Embeds a web page as a background. Note that the page won't be interactive.
+
+```
+
+Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition.
+
+
+### Parallax Background
+
+If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional).
+
+```javascript
+Reveal.initialize({
+
+ // Parallax background image
+ parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg"
+
+ // Parallax background size
+ parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto)
+
+ // Amount of pixels to move the parallax background per slide step,
+ // a value of 0 disables movement along the given axis
+ // These are optional, if they aren't specified they'll be calculated automatically
+ parallaxBackgroundHorizontal: 200,
+ parallaxBackgroundVertical: 50
+
+});
+```
+
+Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px).
+
+
+
+### Slide Transitions
+The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute:
+
+```html
+
+
This slide will override the presentation transition and zoom!
+
+
+
+
Choose from three transition speeds: default, fast or slow!
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/src/DecisionTrees/reveal.js/test/test-markdown-element-attributes.js b/doc/src/DecisionTrees/reveal.js/test/test-markdown-element-attributes.js
new file mode 100644
index 000000000..10a250375
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/test/test-markdown-element-attributes.js
@@ -0,0 +1,46 @@
+
+
+Reveal.addEventListener( 'ready', function() {
+
+ QUnit.module( 'Markdown' );
+
+ test( 'Vertical separator', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section' ).length, 4, 'found four slides' );
+ });
+
+
+ test( 'Attributes on element header in vertical slides', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides section>section h2.fragment.fade-out' ).length, 1, 'found one vertical slide with class fragment.fade-out on header' );
+ strictEqual( document.querySelectorAll( '.reveal .slides section>section h2.fragment.shrink' ).length, 1, 'found one vertical slide with class fragment.shrink on header' );
+ });
+
+ test( 'Attributes on element paragraphs in vertical slides', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides section>section p.fragment.grow' ).length, 2, 'found a vertical slide with two paragraphs with class fragment.grow' );
+ });
+
+ test( 'Attributes on element list items in vertical slides', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides section>section li.fragment.grow' ).length, 3, 'found a vertical slide with three list items with class fragment.grow' );
+ });
+
+ test( 'Attributes on element paragraphs in horizontal slides', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides section p.fragment.highlight-red' ).length, 4, 'found a horizontal slide with four paragraphs with class fragment.grow' );
+ });
+ test( 'Attributes on element list items in horizontal slides', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides section li.fragment.highlight-green' ).length, 5, 'found a horizontal slide with five list items with class fragment.roll-in' );
+ });
+ test( 'Attributes on element list items in horizontal slides', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides section img.reveal.stretch' ).length, 1, 'found a horizontal slide with stretched image, class img.reveal.stretch' );
+ });
+
+ test( 'Attributes on elements in vertical slides with default element attribute separator', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides section h2.fragment.highlight-red' ).length, 2, 'found two h2 titles with fragment highlight-red in vertical slides with default element attribute separator' );
+ });
+
+ test( 'Attributes on elements in single slides with default element attribute separator', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides section p.fragment.highlight-blue' ).length, 3, 'found three elements with fragment highlight-blue in single slide with default element attribute separator' );
+ });
+
+} );
+
+Reveal.initialize();
+
diff --git a/doc/src/DecisionTrees/reveal.js/test/test-markdown-slide-attributes.html b/doc/src/DecisionTrees/reveal.js/test/test-markdown-slide-attributes.html
new file mode 100644
index 000000000..ab6ece4ed
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/test/test-markdown-slide-attributes.html
@@ -0,0 +1,128 @@
+
+
+
+
+
+
+ reveal.js - Test Markdown Attributes
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/src/DecisionTrees/reveal.js/test/test-markdown-slide-attributes.js b/doc/src/DecisionTrees/reveal.js/test/test-markdown-slide-attributes.js
new file mode 100644
index 000000000..3817fd37c
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/test/test-markdown-slide-attributes.js
@@ -0,0 +1,47 @@
+
+
+Reveal.addEventListener( 'ready', function() {
+
+ QUnit.module( 'Markdown' );
+
+ test( 'Vertical separator', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section' ).length, 6, 'found six vertical slides' );
+ });
+
+ test( 'Id on slide', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section#slide2' ).length, 1, 'found one slide with id slide2' );
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section a[href="#/slide2"]' ).length, 1, 'found one slide with a link to slide2' );
+ });
+
+ test( 'data-background attributes', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section[data-background="#A0C66B"]' ).length, 1, 'found one vertical slide with data-background="#A0C66B"' );
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section[data-background="#ff0000"]' ).length, 1, 'found one vertical slide with data-background="#ff0000"' );
+ strictEqual( document.querySelectorAll( '.reveal .slides>section[data-background="#C6916B"]' ).length, 1, 'found one slide with data-background="#C6916B"' );
+ });
+
+ test( 'data-transition attributes', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section[data-transition="zoom"]' ).length, 1, 'found one vertical slide with data-transition="zoom"' );
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section[data-transition="fade"]' ).length, 1, 'found one vertical slide with data-transition="fade"' );
+ strictEqual( document.querySelectorAll( '.reveal .slides section [data-transition="zoom"]' ).length, 1, 'found one slide with data-transition="zoom"' );
+ });
+
+ test( 'data-background attributes with default separator', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section[data-background="#A7C66B"]' ).length, 1, 'found one vertical slide with data-background="#A0C66B"' );
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section[data-background="#f70000"]' ).length, 1, 'found one vertical slide with data-background="#ff0000"' );
+ strictEqual( document.querySelectorAll( '.reveal .slides>section[data-background="#C7916B"]' ).length, 1, 'found one slide with data-background="#C6916B"' );
+ });
+
+ test( 'data-transition attributes with default separator', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section[data-transition="concave"]' ).length, 1, 'found one vertical slide with data-transition="zoom"' );
+ strictEqual( document.querySelectorAll( '.reveal .slides>section>section[data-transition="page"]' ).length, 1, 'found one vertical slide with data-transition="fade"' );
+ strictEqual( document.querySelectorAll( '.reveal .slides section [data-transition="concave"]' ).length, 1, 'found one slide with data-transition="zoom"' );
+ });
+
+ test( 'data-transition attributes with inline content', function() {
+ strictEqual( document.querySelectorAll( '.reveal .slides>section[data-background="#ff0000"]' ).length, 3, 'found three horizontal slides with data-background="#ff0000"' );
+ });
+
+} );
+
+Reveal.initialize();
+
diff --git a/doc/src/DecisionTrees/reveal.js/test/test-markdown.html b/doc/src/DecisionTrees/reveal.js/test/test-markdown.html
new file mode 100644
index 000000000..7ff0efe8a
--- /dev/null
+++ b/doc/src/DecisionTrees/reveal.js/test/test-markdown.html
@@ -0,0 +1,52 @@
+
+
+
+
+
+
+ reveal.js - Test Markdown
+
+
+
+
+
+
+
+
+
+
+