diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index 9b208d6d2..e6071ed7c 100644 --- a/doc/pub/week45/html/._week45-bs000.html +++ b/doc/pub/week45/html/._week45-bs000.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
+

 

 

 

+ -
-
-

Week 45: Decisions Trees, Random Forests, Bagging and Boosting

-
+ + +
+

Week 45: Decisions Trees, Random Forests, Bagging and Boosting

+ +

+

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 -
-
-
-

Nov 9, 2021

-
-
+

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Nov 10, 2021

+
+

Read »

@@ -421,18 +349,25 @@ MathJax.Hub.Config({
  • »
  • +
    + + +
    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    + + + diff --git a/doc/pub/week45/html/._week45-bs001.html b/doc/pub/week45/html/._week45-bs001.html index e5aba384d..e19211e5c 100644 --- a/doc/pub/week45/html/._week45-bs001.html +++ b/doc/pub/week45/html/._week45-bs001.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Overview of week 45

    + +

    Overview of week 45

    + +

    - +

    +

    1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion.
    @@ -401,6 +334,7 @@ MathJax.Hub.Config({
    +

      @@ -421,18 +355,25 @@ MathJax.Hub.Config({
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs002.html b/doc/pub/week45/html/._week45-bs002.html index 595542bd8..7440b4378 100644 --- a/doc/pub/week45/html/._week45-bs002.html +++ b/doc/pub/week45/html/._week45-bs002.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Decision trees, overarching aims

    -

    We start here with the most basic algorithm, the so-called decision +

    Decision trees, overarching aims

    + +

    +We start here with the most basic algorithm, the so-called decision tree. With this basic algorithm we can in turn build more complex networks, spanning from homogeneous and heterogenous forests (bagging, random forests and more) to one of the most popular supervised algorithms nowadays, the extreme gradient boosting, or just XGBoost. But let us start with the simplest possible ingredient. -

    -

    Decision trees are supervised learning algorithms used for both, +

    +Decision trees are supervised learning algorithms used for both, classification and regression tasks. -

    -

    The main idea of decision trees +

    +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 +

    +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. -

    +where we then finally end up in so called leaf nodes. +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs003.html b/doc/pub/week45/html/._week45-bs003.html index 584d18486..fa056f37d 100644 --- a/doc/pub/week45/html/._week45-bs003.html +++ b/doc/pub/week45/html/._week45-bs003.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Basics of a tree

    -

    A decision tree is typically divided into a root node, the interior nodes, +

    Basics of a tree

    + +

    +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 +

    +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. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs004.html b/doc/pub/week45/html/._week45-bs004.html index 5681fbc5a..ceb0130f2 100644 --- a/doc/pub/week45/html/._week45-bs004.html +++ b/doc/pub/week45/html/._week45-bs004.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    A Sketch of a Tree, Regression problem

    +

    A Sketch of a Tree, Regression problem

    + +

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs005.html b/doc/pub/week45/html/._week45-bs005.html index 7214fe91d..2431d9d19 100644 --- a/doc/pub/week45/html/._week45-bs005.html +++ b/doc/pub/week45/html/._week45-bs005.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    A Sketch of a Tree, Classification problem

    +

    A Sketch of a Tree, Classification problem

    + +

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs006.html b/doc/pub/week45/html/._week45-bs006.html index 6f7eb59ec..a7547ffa9 100644 --- a/doc/pub/week45/html/._week45-bs006.html +++ b/doc/pub/week45/html/._week45-bs006.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    -

    -
    -

    -
    -

    +

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    -

    This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches.

    +

    +



    +

    +This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches. + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs007.html b/doc/pub/week45/html/._week45-bs007.html index c839830c0..6744841af 100644 --- a/doc/pub/week45/html/._week45-bs007.html +++ b/doc/pub/week45/html/._week45-bs007.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    General Features

    -

    The overarching approach to decision trees is a top-down approach.

    +

    General Features

    + +

    +The overarching approach to decision trees is a top-down approach.

    -

    This process is then repeated for the subtree rooted at the new -node. -

    +This process is then repeated for the subtree rooted at the new +node. + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs008.html b/doc/pub/week45/html/._week45-bs008.html index 0ce7375a4..986561c8b 100644 --- a/doc/pub/week45/html/._week45-bs008.html +++ b/doc/pub/week45/html/._week45-bs008.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    How do we set it up?

    -

    In simplified terms, the process of training a decision tree and +

    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: -

    1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
    2. @@ -386,8 +314,10 @@ predicting the target features of query instances is as follows:
    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
    4. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    -

    Then we are essentially done!

    +Then we are essentially done! + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs009.html b/doc/pub/week45/html/._week45-bs009.html index 15b25bcbd..68df708ab 100644 --- a/doc/pub/week45/html/._week45-bs009.html +++ b/doc/pub/week45/html/._week45-bs009.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Decision trees and Regression

    + +

    Decision trees and Regression

    +

    -

    -
    -
    -
    -
    -
    import numpy as np
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.preprocessing import PolynomialFeatures
     from sklearn.linear_model import LinearRegression
    @@ -470,22 +394,8 @@ plt.ylabel(&quo
     plt.title("Decision Tree Regression")
     plt.legend()
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs010.html b/doc/pub/week45/html/._week45-bs010.html index 95bf38cd4..85096c864 100644 --- a/doc/pub/week45/html/._week45-bs010.html +++ b/doc/pub/week45/html/._week45-bs010.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Building a tree, regression

    -

    There are mainly two steps

    +

    Building a tree, regression

    + +

    +There are mainly two steps +

    1. 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 \).
    2. 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 + +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 \). -

    +

    +where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \). +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs011.html b/doc/pub/week45/html/._week45-bs011.html index 1ced5775f..26eb58c8f 100644 --- a/doc/pub/week45/html/._week45-bs011.html +++ b/doc/pub/week45/html/._week45-bs011.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    A top-down approach, recursive binary splitting

    -

    Unfortunately, it is computationally infeasible to consider every +

    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 +

    +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/week45/html/._week45-bs012.html b/doc/pub/week45/html/._week45-bs012.html index ddef5e95a..a7a741c07 100644 --- a/doc/pub/week45/html/._week45-bs012.html +++ b/doc/pub/week45/html/._week45-bs012.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Making a tree

    -

    In order to implement the recursive binary splitting we start by selecting +

    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

    +and $$ \left\{X\vert x_j \geq s\right\}, $$ -

    so that we obtain the lowest MSE, that is

    +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 +

    +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 +

    +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 +

    +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 +

    +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 @@ -420,8 +349,8 @@ 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. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs013.html b/doc/pub/week45/html/._week45-bs013.html index 98b40a18f..af308f80c 100644 --- a/doc/pub/week45/html/._week45-bs013.html +++ b/doc/pub/week45/html/._week45-bs013.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Pruning the tree

    -

    The above procedure is rather straightforward, but leads often to +

    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 +

    +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 \). -

    -

    Read more at the following Scikit-Learn link on pruning.

    +

    +Read more at the following Scikit-Learn link on pruning. +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs014.html b/doc/pub/week45/html/._week45-bs014.html index 242744e67..563bef4fc 100644 --- a/doc/pub/week45/html/._week45-bs014.html +++ b/doc/pub/week45/html/._week45-bs014.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Cost complexity pruning

    -

    For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that

    +

    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 +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 +

    +The tuning parameter \( \alpha \) controls a trade-off between the subtree’s complexity 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. -

    +tend to be minimized for a smaller subtree. -

    It turns out that as we increase \( \alpha \) from zero +

    +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 \). -

    +subtree corresponding to \( \alpha \). +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs015.html b/doc/pub/week45/html/._week45-bs015.html index e455050b4..414b7d479 100644 --- a/doc/pub/week45/html/._week45-bs015.html +++ b/doc/pub/week45/html/._week45-bs015.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Schematic Regression Procedure

    +

    Schematic Regression Procedure

    + +

    - +

    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.
    2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    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:
    4. +
      • 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.
      +
    5. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs016.html b/doc/pub/week45/html/._week45-bs016.html index e5042d19e..70141b360 100644 --- a/doc/pub/week45/html/._week45-bs016.html +++ b/doc/pub/week45/html/._week45-bs016.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    A Classification Tree

    -

    A classification tree is very similar to a regression tree, except +

    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 @@ -387,9 +316,9 @@ 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. -

    +fall into that region. +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs017.html b/doc/pub/week45/html/._week45-bs017.html index 9514c9eef..436f8c0f9 100644 --- a/doc/pub/week45/html/._week45-bs017.html +++ b/doc/pub/week45/html/._week45-bs017.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Growing a classification tree

    -

    The task of growing a +

    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 @@ -386,15 +315,15 @@ 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. -

    +belong to the most common class. -

    When building a classification tree, either the Gini index or the +

    +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. -

    +than is the classification error rate. +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs018.html b/doc/pub/week45/html/._week45-bs018.html index 0b98928c8..dfb4b24d2 100644 --- a/doc/pub/week45/html/._week45-bs018.html +++ b/doc/pub/week45/html/._week45-bs018.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Classification tree, how to split nodes

    -

    If our targets are the outcome of a classification process that takes +

    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 +

    +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). +p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). $$ -

    We let \( p_{mk} \) represent the majority class of observations in region +

    +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 -

    + $$ -p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +\frac{1}{N_m}\sum_{i\in R_m}I(y_i\ne k) = 1-p_{mk}. $$ + + $$ g = \sum_{k=1}^K p_{mk}(1-p_{mk}). $$ + + $$ s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. $$ - +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs019.html b/doc/pub/week45/html/._week45-bs019.html index 7dec16fcd..6bbd8b0e5 100644 --- a/doc/pub/week45/html/._week45-bs019.html +++ b/doc/pub/week45/html/._week45-bs019.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Visualizing the Tree, Classification

    + +

    Visualizing the Tree, Classification

    +

    -

    -
    -
    -
    -
    -
    import os
    +
    import os
     from sklearn.datasets import load_breast_cancer
     from sklearn.tree import DecisionTreeClassifier
     from sklearn.model_selection import train_test_split
    @@ -415,22 +339,8 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs020.html b/doc/pub/week45/html/._week45-bs020.html index 1183f109f..cb8da4f27 100644 --- a/doc/pub/week45/html/._week45-bs020.html +++ b/doc/pub/week45/html/._week45-bs020.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Visualizing the Tree, The Moons

    + +

    Visualizing the Tree, The Moons

    +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.tree import DecisionTreeClassifier
    @@ -406,22 +330,8 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs021.html b/doc/pub/week45/html/._week45-bs021.html index cd5d4cb96..0b60f1384 100644 --- a/doc/pub/week45/html/._week45-bs021.html +++ b/doc/pub/week45/html/._week45-bs021.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Other ways of visualizing the trees

    -

    Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.

    +

    Other ways of visualizing the trees

    +

    +Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. + +

    -

    -
    -
    -
    -
    -
    from sklearn.datasets import load_iris
    +
    from sklearn.datasets import load_iris
     from sklearn import tree
     X, y = load_iris(return_X_y=True)
     tree_clf = tree.DecisionTreeClassifier()
     tree_clf = tree_clf.fit(X, y)
     # and then plot the tree
     tree.plot_tree(tree_clf) 
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs022.html b/doc/pub/week45/html/._week45-bs022.html index f214fb51f..b88ed717c 100644 --- a/doc/pub/week45/html/._week45-bs022.html +++ b/doc/pub/week45/html/._week45-bs022.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Printing out as text

    -

    Alternatively, the tree can also be exported in textual format with the function exporttext. +

    Printing out as text

    + +

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

    +

    -

    -
    -
    -
    -
    -
    from sklearn.datasets import load_iris
    +
    from sklearn.datasets import load_iris
     from sklearn.tree import DecisionTreeClassifier
     from sklearn.tree import export_text
     iris = load_iris()
    @@ -395,22 +319,8 @@ decision_tree = DecisionTreeClassifier(rando
     decision_tree = decision_tree.fit(iris.data, iris.target)
     r = export_text(decision_tree, feature_names=iris['feature_names'])
     print(r)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs023.html b/doc/pub/week45/html/._week45-bs023.html index 3d7c0b193..db110f913 100644 --- a/doc/pub/week45/html/._week45-bs023.html +++ b/doc/pub/week45/html/._week45-bs023.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Algorithms for Setting up Decision Trees

    -

    Two algorithms stand out in the set up of decision trees:

    +

    Algorithms for Setting up Decision Trees

    + +

    +Two algorithms stand out in the set up of decision trees: +

    1. The CART (Classification And Regression Tree) algorithm for both classification and regression
    2. The ID3 algorithm based on the computation of the information gain for classification
    -

    We discuss both algorithms with applications here. The popular library + +We discuss both algorithms with applications here. The popular library Scikit-Learn uses the CART algorithm. For classification problems you can use either the gini index or the entropy to split a tree in two branches. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs024.html b/doc/pub/week45/html/._week45-bs024.html index adc4d2bc0..29fa4728b 100644 --- a/doc/pub/week45/html/._week45-bs024.html +++ b/doc/pub/week45/html/._week45-bs024.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    The CART algorithm for Classification

    -

    For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +

    The CART algorithm for Classification

    + +

    +For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). This could be for example a threshold set by a number below a certain circumference of a malign tumor. -

    -

    How do we find these two quantities? +

    +How do we find these two quantities? We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). The cost function it tries to minimize is then -

    $$ C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, $$ -

    where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) +where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) is the number of instances in the left/right subset -

    -

    Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +

    +Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the \( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), \( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs025.html b/doc/pub/week45/html/._week45-bs025.html index 7978c4bd0..754c9eaa5 100644 --- a/doc/pub/week45/html/._week45-bs025.html +++ b/doc/pub/week45/html/._week45-bs025.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    The CART algorithm for Regression

    -

    The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +

    The CART algorithm for Regression

    + +

    +The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now -

    $$ C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. $$ -

    Here the MSE for a specific node is defined as

    +Here the MSE for a specific node is defined as $$ \mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, $$ -

    with

    +with $$ \overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, $$ -

    the mean value of all observations in a specific node.

    +the mean value of all observations in a specific node. -

    Without any regularization, the regression task for decision trees, +

    +Without any regularization, the regression task for decision trees, just like for classification tasks, is prone to overfitting. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs026.html b/doc/pub/week45/html/._week45-bs026.html index df025d454..0b6fba35e 100644 --- a/doc/pub/week45/html/._week45-bs026.html +++ b/doc/pub/week45/html/._week45-bs026.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Computing the Gini index

    -

    The example we will look at is a classical one in many Machine +

    Computing the Gini index

    + +

    +The example we will look at is a classical one in many Machine Learning applications. Based on various meteorological features, we have several so-called attributes which decide whether we at the end will do some outdoor activity like skiing, going for a bike ride etc @@ -386,12 +315,13 @@ etc. The table here contains the feautures outlook, temperature, attributes for each feature are then sunny, overcast and rain for the outlook, hot, cold and mild for temperature, high and normal for humidity and weak and strong for wind. -

    -

    The table here summarizes the various attributes and

    +

    +The table here summarizes the various attributes and +

    - +
    @@ -414,7 +344,7 @@ humidity and weak and strong for wind.
    Day Outlook Temperature Humidity Wind Ride
    - +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs027.html b/doc/pub/week45/html/._week45-bs027.html index 1f347bfc4..24950fc48 100644 --- a/doc/pub/week45/html/._week45-bs027.html +++ b/doc/pub/week45/html/._week45-bs027.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Simple Python Code to read in Data and perform Classification

    +

    Simple Python Code to read in Data and perform Classification

    + +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -450,22 +374,8 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs028.html b/doc/pub/week45/html/._week45-bs028.html index e95274d58..671de813d 100644 --- a/doc/pub/week45/html/._week45-bs028.html +++ b/doc/pub/week45/html/._week45-bs028.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Computing the Gini Factor

    -

    The above functions (gini, entropy and misclassification error) are +

    Computing the Gini Factor

    + +

    +The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm below after we have discussed the information gain algorithm ID3. -

    -

    In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.

    +

    +In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. +

    -

    -
    -
    -
    -
    -
    # Split a dataset based on an attribute and an attribute value
    +
    # Split a dataset based on an attribute and an attribute value
     def test_split(index, value, dataset):
     	left, right = list(), list()
     	for row in dataset:
    @@ -451,22 +376,8 @@ dataset = [[0= get_split(dataset)
     print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs029.html b/doc/pub/week45/html/._week45-bs029.html index d43fc002a..074a07e1d 100644 --- a/doc/pub/week45/html/._week45-bs029.html +++ b/doc/pub/week45/html/._week45-bs029.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Entropy and the ID3 algorithm

    -

    The ID3 algorithm learns decision trees by constructing +

    Entropy and the ID3 algorithm

    + +

    +The ID3 algorithm learns decision trees by constructing them in a top down way, beginning with the question which attribute should be tested at the root of the tree? -

    1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
    2. @@ -388,24 +316,26 @@ them in a top down way, beginning with the question which attribute should be
    3. 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.
    4. 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 + +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 +

    +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?

    +

    +What is a good quantitative measure of the worth of an attribute? -

    Information gain measures how well a given attribute separates the +

    +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 +

    +The ID3 algorithm uses this information gain measure to select among the candidate attributes at each step while growing the tree. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs030.html b/doc/pub/week45/html/._week45-bs030.html index b9e717ce5..f82c5146a 100644 --- a/doc/pub/week45/html/._week45-bs030.html +++ b/doc/pub/week45/html/._week45-bs030.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Cancer Data again now with Decision Trees and other Methods

    + +

    Cancer Data again now with Decision Trees and other Methods

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -423,22 +347,8 @@ svm.fit(X_train_scaled, y_train)
     # 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/week45/html/._week45-bs031.html b/doc/pub/week45/html/._week45-bs031.html index d2b9e2106..996acd39f 100644 --- a/doc/pub/week45/html/._week45-bs031.html +++ b/doc/pub/week45/html/._week45-bs031.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Another example, the moons again

    + +

    Another example, the moons again

    +

    -

    -
    -
    -
    -
    -
    from __future__ import division, print_function, unicode_literals
    +
    from __future__ import division, print_function, unicode_literals
     
     # Common imports
     import numpy as np
    @@ -446,22 +370,8 @@ plt.subplot(122
     plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
     plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs032.html b/doc/pub/week45/html/._week45-bs032.html index 999571e8f..05f152103 100644 --- a/doc/pub/week45/html/._week45-bs032.html +++ b/doc/pub/week45/html/._week45-bs032.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Playing around with regions

    + +

    Playing around with regions

    +

    -

    -
    -
    -
    -
    -
    np.random.seed(6)
    +
    np.random.seed(6)
     Xs = np.random.rand(100, 2) - 0.5
     ys = (Xs[:, 0] > 0).astype(np.float32) * 2
     
    @@ -402,22 +326,8 @@ plt.subplot(122
     plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs033.html b/doc/pub/week45/html/._week45-bs033.html index 2bb94767c..bf4160ed2 100644 --- a/doc/pub/week45/html/._week45-bs033.html +++ b/doc/pub/week45/html/._week45-bs033.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Regression trees

    + +

    Regression trees

    +

    -

    -
    -
    -
    -
    -
    # Quadratic training set + noise
    +
    # 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
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    +
    from sklearn.tree import DecisionTreeRegressor
     
     tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
     tree_reg.fit(X, y)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

      @@ -456,18 +351,25 @@ tree_reg.fit(X, y)
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs034.html b/doc/pub/week45/html/._week45-bs034.html index ece8fcbfe..cd0c9566b 100644 --- a/doc/pub/week45/html/._week45-bs034.html +++ b/doc/pub/week45/html/._week45-bs034.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Final regressor code

    + +

    Final regressor code

    +

    -

    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    +
    from sklearn.tree import DecisionTreeRegressor
     
     tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
     tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
    @@ -420,26 +344,11 @@ plt.text(0.3.title("max_depth=3", fontsize=14)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    tree_reg1 = DecisionTreeRegressor(random_state=42)
    +
    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)
    @@ -467,22 +376,8 @@ plt.xlabel(&quo
     plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

      @@ -512,18 +407,25 @@ plt.show()
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs035.html b/doc/pub/week45/html/._week45-bs035.html index df438ea0f..14163942f 100644 --- a/doc/pub/week45/html/._week45-bs035.html +++ b/doc/pub/week45/html/._week45-bs035.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Pros and cons of trees, pros

    + +

    Pros and cons of trees, pros

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs036.html b/doc/pub/week45/html/._week45-bs036.html index f8d1cd9ef..b6ebe72c2 100644 --- a/doc/pub/week45/html/._week45-bs036.html +++ b/doc/pub/week45/html/._week45-bs036.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Disadvantages

    + +

    Disadvantages

    -

    However, by aggregating many decision trees, using methods like + +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/week45/html/._week45-bs037.html b/doc/pub/week45/html/._week45-bs037.html index 90cd45945..f781f35a6 100644 --- a/doc/pub/week45/html/._week45-bs037.html +++ b/doc/pub/week45/html/._week45-bs037.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

    -

    As stated above and seen in many of the examples discussed here about +

    Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

    + +

    +As stated above and seen in many of the examples discussed here about a single decision tree, we often end up overfitting our training data. This normally means that we have a high variance. Can we reduce the variance of a statistical learning method? -

    -

    This leads us to a set of different methods that can combine different +

    +This leads us to a set of different methods that can combine different machine learning algorithms or just use one of them to construct forests and jungles of trees, homogeneous ones or heterogenous ones. These methods are recognized by different names which we will try to explain here. These are -

    1. Voting classifiers
    2. @@ -395,8 +323,10 @@ try to explain here. These are
    3. Random forests
    4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
    -

    We discuss these methods here.

    +We discuss these methods here. + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs038.html b/doc/pub/week45/html/._week45-bs038.html index 71333f1f8..8aaf74d8c 100644 --- a/doc/pub/week45/html/._week45-bs038.html +++ b/doc/pub/week45/html/._week45-bs038.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    An Overview of Ensemble Methods

    -

    -
    -

    -
    -

    +

    An Overview of Ensemble Methods

    +

    +



    + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs039.html b/doc/pub/week45/html/._week45-bs039.html index bc3c79b0e..d86b571b7 100644 --- a/doc/pub/week45/html/._week45-bs039.html +++ b/doc/pub/week45/html/._week45-bs039.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Bagging

    -

    The plain decision trees suffer from high +

    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. -

    +of \( n \) to \( p \) is moderately large. -

    Bootstrap aggregation, or just bagging, is a +

    +Bootstrap aggregation, or just bagging, is a general-purpose procedure for reducing the variance of a statistical -learning method. -

    +learning method. +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs040.html b/doc/pub/week45/html/._week45-bs040.html index efa344e0f..c7ea74721 100644 --- a/doc/pub/week45/html/._week45-bs040.html +++ b/doc/pub/week45/html/._week45-bs040.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    More bagging

    -

    Bagging typically results in improved accuracy +

    More bagging

    + +

    +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 +

    +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 @@ -398,8 +327,8 @@ 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/week45/html/._week45-bs041.html b/doc/pub/week45/html/._week45-bs041.html index d3ab059e4..090a57ede 100644 --- a/doc/pub/week45/html/._week45-bs041.html +++ b/doc/pub/week45/html/._week45-bs041.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Simple Voting Example, head or tail

    + +

    Simple Voting Example, head or tail

    +

    -

    -
    -
    -
    -
    -
    heads_proba = 0.51
    +
    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))
    @@ -395,22 +319,8 @@ plt.legend(loc=
     plt.axis([0, 10000, 0.42, 0.58])
     save_fig("votingsimple")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs042.html b/doc/pub/week45/html/._week45-bs042.html index 2bec4ad6d..3b3b30afe 100644 --- a/doc/pub/week45/html/._week45-bs042.html +++ b/doc/pub/week45/html/._week45-bs042.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Using the Voting Classifier

    + +

    Using the Voting Classifier

    +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -425,22 +349,8 @@ voting_clf.fit(X_train, y_train)
         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/week45/html/._week45-bs043.html b/doc/pub/week45/html/._week45-bs043.html index 1b2892602..0dd01299d 100644 --- a/doc/pub/week45/html/._week45-bs043.html +++ b/doc/pub/week45/html/._week45-bs043.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Please, not the moons again! Voting and Bagging

    +

    Please, not the moons again! Voting and Bagging

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -401,51 +325,21 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='hard')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    log_clf = LogisticRegression(random_state=42)
    +
    log_clf = LogisticRegression(random_state=42)
     rnd_clf = RandomForestClassifier(random_state=42)
     svm_clf = SVC(probability=True, random_state=42)
     
    @@ -453,47 +347,18 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='soft')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

      @@ -523,18 +388,25 @@ voting_clf.fit(X_train, y_train)
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs044.html b/doc/pub/week45/html/._week45-bs044.html index 28cdba414..3a09f2a78 100644 --- a/doc/pub/week45/html/._week45-bs044.html +++ b/doc/pub/week45/html/._week45-bs044.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Bagging Examples

    +

    Bagging Examples

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.ensemble import BaggingClassifier
    +
    from sklearn.ensemble import BaggingClassifier
     from sklearn.tree import DecisionTreeClassifier
     
     bag_clf = BaggingClassifier(
    @@ -391,70 +315,25 @@ bag_clf = BaggingClassifier(
         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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    from sklearn.metrics import accuracy_score
     print(accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    tree_clf = DecisionTreeClassifier(random_state=42)
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from matplotlib.colors import ListedColormap
    +
    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)
    @@ -481,22 +360,8 @@ plot_decision_boundary(bag_clf, X, y)
     plt.title("Decision Trees with Bagging", fontsize=14)
     save_fig("baggingtree")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

      @@ -526,18 +391,25 @@ plt.show()
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs045.html b/doc/pub/week45/html/._week45-bs045.html index 1f3d09484..69129fbba 100644 --- a/doc/pub/week45/html/._week45-bs045.html +++ b/doc/pub/week45/html/._week45-bs045.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Making your own Bootstrap: Changing the Level of the Decision Tree

    -

    Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +

    Making your own Bootstrap: Changing the Level of the Decision Tree

    + +

    +Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). -

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     from sklearn.pipeline import make_pipeline
    @@ -443,22 +367,8 @@ plt.plot(polydegree, variance, label.legend()
     save_fig("baggingboot")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

      @@ -488,18 +398,25 @@ plt.show()
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs046.html b/doc/pub/week45/html/._week45-bs046.html index f13436891..a8d98ce44 100644 --- a/doc/pub/week45/html/._week45-bs046.html +++ b/doc/pub/week45/html/._week45-bs046.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Why Voting?

    -

    The idea behind boosting, and voting as well can be phrased as follows: +

    Why Voting?

    + +

    +The idea behind boosting, and voting as well can be phrased as follows: Can a group of people somehow arrive at highly reasoned decisions, despite the weak judgement of the individual members? -

    -

    The aim is to create a good classifier by combining several weak classifiers. +

    +The aim is to create a good classifier by combining several weak classifiers. A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random. -

    -

    The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. +

    +The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in -each iteration. -

    +each iteration. -

    Decision trees play an important role as our weak classifier. They serve as the basic method.

    +

    +Decision trees play an important role as our weak classifier. They serve as the basic method. +

      @@ -422,18 +352,25 @@ each iteration.
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs047.html b/doc/pub/week45/html/._week45-bs047.html index 7e32b6a7e..e83bd310f 100644 --- a/doc/pub/week45/html/._week45-bs047.html +++ b/doc/pub/week45/html/._week45-bs047.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Tossing coins

    -

    The simplest case is a so-called voting ensemble. To illustrate this, +

    Tossing coins

    + +

    +The simplest case is a so-called voting ensemble. To illustrate this, think of yourself tossing coins with a biased outcome of 51 per cent for heads and 49% for tails. With only few tosses, you may not clearly see this distribution for heads and tails. However, after some thousands of tosses, there will be a clear majority of heads. With 2000 tosses you should see approximately 1020 heads and 980 tails. -

    -

    We can then state that the outcome is a clear majority of heads. If +

    +We can then state that the outcome is a clear majority of heads. If you do this ten thousand times, it is easy to see that there is a 97% likelihood of a majority of heads. -

    -

    Another example would be to collect all polls before an +

    +Another example would be to collect all polls before an election. Different polls may show different likelihoods for a candidate winning with say a majority of the popular vote. The majority vote would then consist in many polls indicating that this candidate will actually win. -

    -

    The example here shows how we can implement the coin tossing case, +

    +The example here shows how we can implement the coin tossing case, clealry demostrating that after some tosses we see the law of large numbers kicking in. -

    +

      @@ -430,18 +359,25 @@ numbers kicking in.
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs048.html b/doc/pub/week45/html/._week45-bs048.html index e01e0e507..7d0a40156 100644 --- a/doc/pub/week45/html/._week45-bs048.html +++ b/doc/pub/week45/html/._week45-bs048.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Standard imports first

    +

    Standard imports first

    + +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     from IPython.display import Image 
     from pydot import graph_from_dot_data
     import pandas as pd
    @@ -420,22 +344,8 @@ DATA_ID = "
     
     def save_fig(fig_id):
         plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

      @@ -465,18 +375,25 @@ DATA_ID = "
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs049.html b/doc/pub/week45/html/._week45-bs049.html index 9464541e2..4093a2585 100644 --- a/doc/pub/week45/html/._week45-bs049.html +++ b/doc/pub/week45/html/._week45-bs049.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Simple Voting Example, head or tail

    + +

    Simple Voting Example, head or tail

    +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     import matplotlib
     import matplotlib.pyplot as plt
    @@ -404,22 +328,8 @@ plt.legend(loc=
     plt.axis([0, 10000, 0.42, 0.58])
     save_fig("votingsimple")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs050.html b/doc/pub/week45/html/._week45-bs050.html index 82e2ae1be..33ca8c7e1 100644 --- a/doc/pub/week45/html/._week45-bs050.html +++ b/doc/pub/week45/html/._week45-bs050.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Using the Voting Classifier

    -

    We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.

    +

    Using the Voting Classifier

    + +

    +We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn. +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -426,22 +351,8 @@ voting_clf.fit(X_train, y_train)
         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/week45/html/._week45-bs051.html b/doc/pub/week45/html/._week45-bs051.html index b9e4c076b..cf61d060e 100644 --- a/doc/pub/week45/html/._week45-bs051.html +++ b/doc/pub/week45/html/._week45-bs051.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Voting and Bagging

    +

    Voting and Bagging

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -401,51 +325,21 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='hard')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    log_clf = LogisticRegression(random_state=42)
    +
    log_clf = LogisticRegression(random_state=42)
     rnd_clf = RandomForestClassifier(random_state=42)
     svm_clf = SVC(probability=True, random_state=42)
     
    @@ -453,47 +347,18 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='soft')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

      @@ -523,18 +388,25 @@ voting_clf.fit(X_train, y_train)
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs052.html b/doc/pub/week45/html/._week45-bs052.html index 62dfad659..7b6e3911d 100644 --- a/doc/pub/week45/html/._week45-bs052.html +++ b/doc/pub/week45/html/._week45-bs052.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Random forests

    -

    Random forests provide an improvement over bagged trees by way of a -small tweak that decorrelates the trees. -

    +

    Random forests

    -

    As in bagging, we build a +

    +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. -

    +use only one of those \( m \) predictors. -

    A fresh sample of \( m \) predictors is +

    +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 +

    +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. -

    +a majority of the available predictors. -

    The reason for this is rather clever. Suppose that there is one very +

    +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 @@ -413,8 +342,8 @@ lead to as large of a reduction in variance as averaging many uncorrelated quantities. In particular, this means that bagging will not lead to a substantial reduction in variance over a single tree in this setting. -

    +

      @@ -444,18 +373,25 @@ this setting.
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs053.html b/doc/pub/week45/html/._week45-bs053.html index ba119cc67..f70977691 100644 --- a/doc/pub/week45/html/._week45-bs053.html +++ b/doc/pub/week45/html/._week45-bs053.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Random Forest Algorithm

    -

    The algorithm described here can be applied to both classification and regression problems.

    -

    We will grow of forest of say \( B \) trees.

    +

    Random Forest Algorithm

    +The algorithm described here can be applied to both classification and regression problems. + +

    +We will grow of forest of say \( B \) trees. +

    1. For \( b=1:B \)
    2. +
      • Draw a bootstrap sample from the training data organized in our \( \boldsymbol{X} \) matrix.
      • We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
      • +
        1. we select \( m \le p \) variables at random from the \( p \) predictors/features
        2. pick the best split point among the \( m \) features using for example the CART algorithm and create a new node
        3. split the node into daughter nodes
        +
      +
    3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
    +

      @@ -420,18 +355,25 @@ MathJax.Hub.Config({
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs054.html b/doc/pub/week45/html/._week45-bs054.html index 496cf2537..1b5dba499 100644 --- a/doc/pub/week45/html/._week45-bs054.html +++ b/doc/pub/week45/html/._week45-bs054.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Random Forests Compared with other Methods on the Cancer Data

    + +

    Random Forests Compared with other Methods on the Cancer Data

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -448,31 +372,18 @@ skplt.metrics.<
     plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Recall that the cumulative gains curve shows the percentage of the +

    +

    +Recall that the cumulative gains curve shows the percentage of the overall number of cases in a given category gained by targeting a percentage of the total number of cases. -

    -

    Similarly, the receiver operating characteristic curve, or ROC curve, +

    +Similarly, the receiver operating characteristic curve, or ROC curve, displays the diagnostic ability of a binary classifier system as its discrimination threshold is varied. It plots the true positive rate against the false positive rate. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs055.html b/doc/pub/week45/html/._week45-bs055.html index 2ec95e02b..918ba2c9e 100644 --- a/doc/pub/week45/html/._week45-bs055.html +++ b/doc/pub/week45/html/._week45-bs055.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Compare Bagging on Trees with Random Forests

    + +

    Compare Bagging on Trees with Random Forests

    +

    -

    -
    -
    -
    -
    -
    bag_clf = BaggingClassifier(
    +
    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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    bag_clf.fit(X_train, y_train)
    +
    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) 
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

      @@ -456,18 +351,25 @@ np.sum(y_pred =
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs056.html b/doc/pub/week45/html/._week45-bs056.html index eba024d51..2fdf49cb5 100644 --- a/doc/pub/week45/html/._week45-bs056.html +++ b/doc/pub/week45/html/._week45-bs056.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + +
    +
    +

     

     

     

    + -

    Boosting, a Bird's Eye View

    -

    The basic idea is to combine weak classifiers in order to create a good +

    Boosting, a Bird's Eye View

    + +

    +The basic idea is to combine weak classifiers in order to create a good classifier. With a weak classifier we often intend a classifier which produces results which are only slightly better than we would get by random guesses. -

    -

    This is done by applying in an iterative way a weak (or a standard +

    +This is done by applying in an iterative way a weak (or a standard classifier like decision trees) to modify the data. In each iteration we emphasize those observations which are misclassified by weighting them with a factor. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs057.html b/doc/pub/week45/html/._week45-bs057.html index d0ae95147..18e8e3eb3 100644 --- a/doc/pub/week45/html/._week45-bs057.html +++ b/doc/pub/week45/html/._week45-bs057.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    What is boosting? Additive Modelling/Iterative Fitting

    -

    Boosting is a way of fitting an additive expansion in a set of +

    What is boosting? Additive Modelling/Iterative Fitting

    + +

    +Boosting is a way of fitting an additive expansion in a set of elementary basis functions like for example some simple polynomials. Assume for example that we have a function -

    $$ f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ -

    where \( \beta_m \) are the expansion parameters to be determined in a +

    +where \( \beta_m \) are the expansion parameters to be determined in a minimization process and \( b(x;\gamma_m) \) are some simple functions of the multivariable parameter \( x \) which is characterized by the parameters \( \gamma_m \). -

    -

    As an example, consider the Sigmoid function we used in logistic +

    +As an example, consider the Sigmoid function we used in logistic regression. In that case, we can translate the function \( b(x;\gamma_m) \) into the Sigmoid function -

    $$ \sigma(t) = \frac{1}{1+\exp{(-t)}}, $$ -

    where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and +

    +where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and \( \gamma_1 \) were determined by the Logistic Regression fitting algorithm. -

    -

    As another example, consider the cost function we defined for linear regression

    +

    +As another example, consider the cost function we defined for linear regression $$ C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    In this case the function \( f(x) \) was replaced by the design matrix +

    +In this case the function \( f(x) \) was replaced by the design matrix \( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can simply invert a matrix and obtain the parameters \( \beta \) by -

    $$ \boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

    In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).

    +

    +In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \). +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs058.html b/doc/pub/week45/html/._week45-bs058.html index 10b102b13..f4a2c7baa 100644 --- a/doc/pub/week45/html/._week45-bs058.html +++ b/doc/pub/week45/html/._week45-bs058.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Iterative Fitting, Regression and Squared-error Cost Function

    -

    The way we proceed is as follows (here we specialize to the squared-error cost function)

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    + +

    +The way we proceed is as follows (here we specialize to the squared-error cost function)

    1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
    2. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    3. For \( m=1:M \) +
      1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
      2. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
      3. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
      +
    -

    We could use any of the algorithms we have discussed till now. If we + +We could use any of the algorithms we have discussed till now. If we use trees, \( \gamma \) parameterizes the split variables and split points at the internal nodes, and the predictions at the terminal nodes. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs059.html b/doc/pub/week45/html/._week45-bs059.html index fb7b629d4..f8176c72e 100644 --- a/doc/pub/week45/html/._week45-bs059.html +++ b/doc/pub/week45/html/._week45-bs059.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Squared-Error Example and Iterative Fitting

    -

    To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.

    +

    Squared-Error Example and Iterative Fitting

    -

    For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \).

    +

    +To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. -

    This means that for every iteration \( m \), we need to optimize

    +

    +For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). + +

    +This means that for every iteration \( m \), we need to optimize $$ (\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. $$ -

    We start our iteration by simply setting \( f_0(x)=0 \). +

    +We start our iteration by simply setting \( f_0(x)=0 \). Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain -

    $$ \frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, $$ -

    and

    +and $$ \frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. $$ -

    We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)

    +We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) $$ \gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, $$ -

    which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have

    +which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have $$ \beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, $$ -

    which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting -for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. -

    +

    +which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting +for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. -

    The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as -\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). -

    +

    +The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as +\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs060.html b/doc/pub/week45/html/._week45-bs060.html index 50b3550ab..39d5384b5 100644 --- a/doc/pub/week45/html/._week45-bs060.html +++ b/doc/pub/week45/html/._week45-bs060.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Iterative Fitting, Classification and AdaBoost

    -

    Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +

    Iterative Fitting, Classification and AdaBoost

    + +

    +Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values \( \{-1,1\} \). -

    -

    The error rate of the training sample is then

    +

    +The error rate of the training sample is then $$ \mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). $$ -

    The iterative procedure starts with defining a weak classifier whose +

    +The iterative procedure starts with defining a weak classifier whose error rate is barely better than random guessing. The iterative procedure in boosting is to sequentially apply a weak classification algorithm to repeatedly modified versions of the data producing a sequence of weak classifiers \( G_m(x) \). -

    -

    Here we will express our function \( f(x) \) in terms of \( G(x) \). That is

    +

    +Here we will express our function \( f(x) \) in terms of \( G(x) \). That is $$ f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ -

    will be a function of

    +will be a function of $$ G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). $$ - +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs061.html b/doc/pub/week45/html/._week45-bs061.html index 3705fe1a4..bc363142c 100644 --- a/doc/pub/week45/html/._week45-bs061.html +++ b/doc/pub/week45/html/._week45-bs061.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Adaptive Boosting, AdaBoost

    -

    In our iterative procedure we define thus

    +

    Adaptive Boosting, AdaBoost

    + +

    +In our iterative procedure we define thus $$ f_m(x) = f_{m-1}(x)+\beta_mG_m(x). $$ -

    The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the +

    +The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the exponential cost/loss function defined as -

    $$ C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. $$ -

    We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. +

    +We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. This is normally done in two steps. Let us however first rewrite the cost function as -

    $$ C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, $$ -

    where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

    +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \). +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs062.html b/doc/pub/week45/html/._week45-bs062.html index 3418fa8c8..273c1d877 100644 --- a/doc/pub/week45/html/._week45-bs062.html +++ b/doc/pub/week45/html/._week45-bs062.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Building up AdaBoost

    -

    First, for any \( \beta > 0 \), we optimize \( G \) by setting

    +

    Building up AdaBoost

    + +

    +First, for any \( \beta > 0 \), we optimize \( G \) by setting $$ G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), $$ -

    which is the classifier that minimizes the weighted error rate in predicting \( y \).

    +which is the classifier that minimizes the weighted error rate in predicting \( y \). -

    We can do this by rewriting

    +

    +We can do this by rewriting $$ \exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, $$ -

    which can be rewritten as

    +which can be rewritten as $$ (\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, $$ -

    which leads to

    +which leads to $$ \beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, $$ -

    where we have redefined the error as

    +where we have redefined the error as $$ \mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, $$ -

    which leads to an update of

    +which leads to an update of $$ f_m(x) = f_{m-1}(x) +\beta_m G_m(x). $$ -

    This leads to the new weights

    +This leads to the new weights $$ w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} $$ - +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs063.html b/doc/pub/week45/html/._week45-bs063.html index cadeaee11..3f17d3c07 100644 --- a/doc/pub/week45/html/._week45-bs063.html +++ b/doc/pub/week45/html/._week45-bs063.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Adaptive boosting: AdaBoost, Basic Algorithm

    -

    The algorithm here is rather straightforward. Assume that our weak +

    Adaptive boosting: AdaBoost, Basic Algorithm

    + +

    +The algorithm here is rather straightforward. Assume that our weak classifier is a decision tree and we consider a binary set of outputs with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of observations. Our design matrix is given in terms of the feature/predictor vectors \( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a -classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). -

    +classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). -

    We have already defined the misclassification error \( \mathrm{err} \) as

    +

    +We have already defined the misclassification error \( \mathrm{err} \) as $$ \mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), $$ -

    where the function \( I() \) is one if we misclassify and zero if we classify correctly.

    +where the function \( I() \) is one if we misclassify and zero if we classify correctly. +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs064.html b/doc/pub/week45/html/._week45-bs064.html index b2e2bd3e4..45170c3ae 100644 --- a/doc/pub/week45/html/._week45-bs064.html +++ b/doc/pub/week45/html/._week45-bs064.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Basic Steps of AdaBoost

    -

    With the above definitions we are now ready to set up the algorithm for AdaBoost. +

    Basic Steps of AdaBoost

    + +

    +With the above definitions we are now ready to set up the algorithm for AdaBoost. The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. -

    +
    1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
    2. We rewrite the misclassification error as
    + $$ \mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, $$ +
    1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. +
      1. Fit then a given classifier to the training set using the weights \( w_i \).
      2. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
      3. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
      4. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
      +
    2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
    -

    For the iterations with \( m \le 2 \) the weights are modified + +For the iterations with \( m \le 2 \) the weights are modified individually at each steps. The observations which were misclassified at iteration \( m-1 \) have a weight which is larger than those which were classified properly. As this proceeds, the observations which were difficult to classifiy correctly are given a larger influence. Each new classification step \( m \) is then forced to concentrate on those observations that are missed in the previous iterations. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs065.html b/doc/pub/week45/html/._week45-bs065.html index 573b2ead2..c800e1816 100644 --- a/doc/pub/week45/html/._week45-bs065.html +++ b/doc/pub/week45/html/._week45-bs065.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    AdaBoost Examples

    -

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.

    +

    AdaBoost Examples

    +

    +Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. + +

    -

    -
    -
    -
    -
    -
    from sklearn.ensemble import AdaBoostClassifier
    +
    from sklearn.ensemble import AdaBoostClassifier
     
     ada_clf = AdaBoostClassifier(
         DecisionTreeClassifier(max_depth=1), n_estimators=200,
    @@ -406,22 +331,8 @@ skplt.metrics.<
     plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs066.html b/doc/pub/week45/html/._week45-bs066.html index 2128826a2..c31c9fc2a 100644 --- a/doc/pub/week45/html/._week45-bs066.html +++ b/doc/pub/week45/html/._week45-bs066.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    -

    Gradient boosting is again a similar technique to Adaptive boosting, +

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    + +

    +Gradient boosting is again a similar technique to Adaptive boosting, it combines so-called weak classifiers or regressors into a strong method via a series of iterations. -

    -

    In order to understand the method, let us illustrate its basics by +

    +In order to understand the method, let us illustrate its basics by bringing back the essential steps in linear regression, where our cost function was the least squares function. -

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs067.html b/doc/pub/week45/html/._week45-bs067.html index 291a11266..c687af957 100644 --- a/doc/pub/week45/html/._week45-bs067.html +++ b/doc/pub/week45/html/._week45-bs067.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    The Squared-Error again! Steepest Descent

    -

    We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize +

    The Squared-Error again! Steepest Descent

    + +

    +We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize This means that for every iteration, we need to optimize -

    $$ (\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as

    +

    +We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as $$ f_M(x) = \sum_{m=0}^M h_m(x). $$ -

    In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as

    +

    +In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as $$ g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. $$ -

    With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that +

    +With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). -

    -

    Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have

    +

    +Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have $$ (\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. $$ - +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs068.html b/doc/pub/week45/html/._week45-bs068.html index c865ab7bc..17f97bab8 100644 --- a/doc/pub/week45/html/._week45-bs068.html +++ b/doc/pub/week45/html/._week45-bs068.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Steepest Descent Example

    -

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that

    +

    Steepest Descent Example

    + +

    +Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that $$ f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. $$ -

    We can then proceed and compute

    +We can then proceed and compute $$ g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, $$ -

    and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting.

    +and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting. +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs069.html b/doc/pub/week45/html/._week45-bs069.html index 15fb71827..8400fb878 100644 --- a/doc/pub/week45/html/._week45-bs069.html +++ b/doc/pub/week45/html/._week45-bs069.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Gradient Boosting, algorithm

    -

    Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, +

    Gradient Boosting, algorithm

    + +

    +Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, so we do not learn a function that can generalize. However, we can modify the algorithm by -fitting a weak learner to approximate the negative gradient signal. -

    +fitting a weak learner to approximate the negative gradient signal. -

    Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function

    +

    +Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function $$ C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    The way we proceed in an iterative fashion is to

    +

    +The way we proceed in an iterative fashion is to +

    1. Initialize our estimate \( f_0(x) \).
    2. For \( m=1:M \), we +
      1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
      2. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      3. update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);
      +
    3. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs070.html b/doc/pub/week45/html/._week45-bs070.html index abc749067..7bbac6dcf 100644 --- a/doc/pub/week45/html/._week45-bs070.html +++ b/doc/pub/week45/html/._week45-bs070.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Gradient Boosting, Examples of Regression

    + +

    Gradient Boosting, Examples of Regression

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     from sklearn.ensemble import GradientBoostingRegressor
    @@ -428,22 +352,8 @@ plt.plot(polydegree, variance, label.legend()
     save_fig("gdregression")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs071.html b/doc/pub/week45/html/._week45-bs071.html index 458bd8a3d..b64ddb47c 100644 --- a/doc/pub/week45/html/._week45-bs071.html +++ b/doc/pub/week45/html/._week45-bs071.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Gradient Boosting, Classification Example

    + +

    Gradient Boosting, Classification Example

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -422,22 +346,8 @@ plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     save_fig("gdclassiffiercgain")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs072.html b/doc/pub/week45/html/._week45-bs072.html index 9391c31d7..f71902e30 100644 --- a/doc/pub/week45/html/._week45-bs072.html +++ b/doc/pub/week45/html/._week45-bs072.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    XGBoost: Extreme Gradient Boosting

    -

    XGBoost or Extreme Gradient +

    XGBoost: Extreme Gradient Boosting

    + +

    +XGBoost or Extreme Gradient Boosting, is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting that solve many data science problems in a fast and accurate way. See the article by Chen and Guestrin. -

    -

    The authors design and build a highly scalable end-to-end tree +

    +The authors design and build a highly scalable end-to-end tree boosting system. It has a theoretically justified weighted quantile sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. -

    -

    It is now the algorithm which wins essentially all ML competitions!!!

    +

    +It is now the algorithm which wins essentially all ML competitions!!! +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs073.html b/doc/pub/week45/html/._week45-bs073.html index 62cca6362..d7ab7b52f 100644 --- a/doc/pub/week45/html/._week45-bs073.html +++ b/doc/pub/week45/html/._week45-bs073.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Regression Case

    +

    Regression Case

    + +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     import xgboost as xgb
    @@ -429,22 +353,8 @@ plt.plot(polydegree, bias, label.plot(polydegree, variance, label='Variance')
     plt.legend()
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs074.html b/doc/pub/week45/html/._week45-bs074.html index faa7cffbb..ffc16d1d9 100644 --- a/doc/pub/week45/html/._week45-bs074.html +++ b/doc/pub/week45/html/._week45-bs074.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -

    Xgboost on the Cancer Data

    -

    As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.

    +

    Xgboost on the Cancer Data

    + +

    +As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -435,21 +360,8 @@ xgb.plot_importance(xg_clf)
     plt.rcParams['figure.figsize'] = [5, 5]
     save_fig("xgparams")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - +
    +

    @@ -468,18 +380,25 @@ plt.show()

  • 75
  • +
    + + +
    + + + diff --git a/doc/pub/week45/html/week45-bs.html b/doc/pub/week45/html/week45-bs.html index 9b208d6d2..e6071ed7c 100644 --- a/doc/pub/week45/html/week45-bs.html +++ b/doc/pub/week45/html/week45-bs.html @@ -1,28 +1,31 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + - + + + @@ -274,6 +195,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + -
    -
    -

    Week 45: Decisions Trees, Random Forests, Bagging and Boosting

    -
    + + +
    +

    Week 45: Decisions Trees, Random Forests, Bagging and Boosting

    + +

    +

    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 -
    -
    -
    -

    Nov 9, 2021

    -
    -
    +

    + + +

    [1] Department of Physics, University of Oslo
    +
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    +
    +

    +

    Nov 10, 2021

    +
    +

    Read »

    @@ -421,18 +349,25 @@ MathJax.Hub.Config({
  • »
  • +
    + + +
    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    + + + diff --git a/doc/pub/week45/html/week45-reveal.html b/doc/pub/week45/html/week45-reveal.html index ef385e828..3f12eb200 100644 --- a/doc/pub/week45/html/week45-reveal.html +++ b/doc/pub/week45/html/week45-reveal.html @@ -1,18 +1,19 @@ - - - + - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting - + + + + + + + @@ -54,81 +55,36 @@ document.getElementsByTagName( 'head' )[0].appendChild( link ); + + + @@ -301,122 +215,144 @@ MathJax.Hub.Config({ - -
    -

    Week 45: Decisions Trees, Random Forests, Bagging and Boosting

    -
    + + + + + +

    Week 45: Decisions Trees, Random Forests, Bagging and Boosting

    + +

    +

    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 -
    -
    -
    -

    Nov 9, 2021

    -
    -
    +

    + + +

    [1] Department of Physics, University of Oslo
    +
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    +
    +

    +

    Nov 10, 2021

    +
    +











    -

    Overview of week 45

    + +

    Overview of week 45

    • Thursday: Basics of Decision Trees, Bagging and Voting
    • Friday: More on Bagging, Voting, Random Forests and start Boosting
    + -
    -Reading

    +

    +Reading. +

    +

    1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion.
    +











    -

    Decision trees, overarching aims

    -

    We start here with the most basic algorithm, the so-called decision +

    Decision trees, overarching aims

    + +

    +We start here with the most basic algorithm, the so-called decision tree. With this basic algorithm we can in turn build more complex networks, spanning from homogeneous and heterogenous forests (bagging, random forests and more) to one of the most popular supervised algorithms nowadays, the extreme gradient boosting, or just XGBoost. But let us start with the simplest possible ingredient. -

    -

    Decision trees are supervised learning algorithms used for both, +

    +Decision trees are supervised learning algorithms used for both, classification and regression tasks. -

    -

    The main idea of decision trees +

    +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 +

    +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. -

    +where we then finally end up in so called leaf nodes. +











    -

    Basics of a tree

    -

    A decision tree is typically divided into a root node, the interior nodes, +

    Basics of a tree

    + +

    +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 +

    +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 Sketch of a Tree, Regression problem

    +

    A Sketch of a Tree, Regression problem

    + +

    +











    -

    A Sketch of a Tree, Classification problem

    +

    A Sketch of a Tree, Classification problem

    + +

    +











    -

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    -

    -
    -

    -
    -

    +

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    -

    This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches.

    +

    +



    +

    +This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches. + +











    -

    General Features

    -

    The overarching approach to decision trees is a top-down approach.

    +

    General Features

    + +

    +The overarching approach to decision trees is a top-down approach.

    • A leaf provides the classification of a given instance.
    • @@ -424,16 +360,18 @@ given some assumptions, make predictions about the target feature value
    • 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 + +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 +

    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: -

    1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
    2. @@ -441,18 +379,17 @@ predicting the target features of query instances is as follows:
    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
    4. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    -

    Then we are essentially done!

    +Then we are essentially done! + +











    -

    Decision trees and Regression

    + +

    Decision trees and Regression

    +

    -

    -
    -
    -
    -
    -
    import numpy as np
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.preprocessing import PolynomialFeatures
     from sklearn.linear_model import LinearRegression
    @@ -490,7 +427,7 @@ c=lin_reg.intercept_
     print ("first power: ", b[0])
     print ("second power: ",b[1])
     
    -z = np.arange(0, steps, .01)
    +z = np.arange(0, steps, .01)
     z_mod=b[1]*z**2+b[0]*z+c
     
     fit_mod=b[1]*X**2+b[0]*X+c
    @@ -540,102 +477,96 @@ plt.ylabel("Darget")
     plt.title("Decision Tree Regression")
     plt.legend()
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Building a tree, regression

    -

    There are mainly two steps

    +

    Building a tree, regression

    + +

    +There are mainly two steps +

    1. 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 \).
    2. 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 + +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 \). -

    +

    +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 +

    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 +

    +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 +

    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

    +and $$ \left\{X\vert x_j \geq s\right\}, $$ -

    so that we obtain the lowest MSE, that is

    +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 +

    +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 +

    +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 +

    +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 +

    +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 @@ -644,83 +575,95 @@ 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 +

    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 +

    +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 \). -

    -

    Read more at the following Scikit-Learn link on pruning.

    +

    +Read more at the following Scikit-Learn link on pruning. +











    -

    Cost complexity pruning

    -

    For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that

    +

    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 +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 +

    +The tuning parameter \( \alpha \) controls a trade-off between the subtree’s complexity 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. -

    +tend to be minimized for a smaller subtree. -

    It turns out that as we increase \( \alpha \) from zero +

    +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 \). -

    +subtree corresponding to \( \alpha \). +











    -

    Schematic Regression Procedure

    +

    Schematic Regression Procedure

    + +

    -Building a Regression Tree +Building a Regression Tree.

    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.
    2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    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:
    4. +
      • 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.
      +
    5. 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 +

    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 @@ -731,13 +674,15 @@ 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. -

    +fall into that region. +











    -

    Growing a classification tree

    -

    The task of growing a +

    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 @@ -747,69 +692,72 @@ 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. -

    +belong to the most common class. -

    When building a classification tree, either the Gini index or the +

    +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. -

    +than is the classification error rate. +











    -

    Classification tree, how to split nodes

    -

    If our targets are the outcome of a classification process that takes +

    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 +

    +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). +p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). $$ -

    We let \( p_{mk} \) represent the majority class of observations in region +

    +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
    + $$ -p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +\frac{1}{N_m}\sum_{i\in R_m}I(y_i\ne k) = 1-p_{mk}. $$ +
    • Gini index \( g \)
    + $$ g = \sum_{k=1}^K p_{mk}(1-p_{mk}). $$ +
    • Information entropy or just entropy \( s \)
    + $$ s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. $$ - +











    -

    Visualizing the Tree, Classification

    + +

    Visualizing the Tree, Classification

    +

    -

    -
    -
    -
    -
    -
    import os
    +
    import os
     from sklearn.datasets import load_breast_cancer
     from sklearn.tree import DecisionTreeClassifier
     from sklearn.model_selection import train_test_split
    @@ -842,32 +790,15 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Visualizing the Tree, The Moons

    + +

    Visualizing the Tree, The Moons

    +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.tree import DecisionTreeClassifier
    @@ -891,72 +822,39 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Other ways of visualizing the trees

    -

    Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.

    +

    Other ways of visualizing the trees

    +

    +Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. + +

    -

    -
    -
    -
    -
    -
    from sklearn.datasets import load_iris
    +
    from sklearn.datasets import load_iris
     from sklearn import tree
     X, y = load_iris(return_X_y=True)
     tree_clf = tree.DecisionTreeClassifier()
     tree_clf = tree_clf.fit(X, y)
     # and then plot the tree
     tree.plot_tree(tree_clf) 
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Printing out as text

    -

    Alternatively, the tree can also be exported in textual format with the function exporttext. +

    Printing out as text

    + +

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

    +

    -

    -
    -
    -
    -
    -
    from sklearn.datasets import load_iris
    +
    from sklearn.datasets import load_iris
     from sklearn.tree import DecisionTreeClassifier
     from sklearn.tree import export_text
     iris = load_iris()
    @@ -964,92 +862,87 @@ decision_tree = DecisionTreeClassifier(random_state='feature_names'])
     print(r)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Algorithms for Setting up Decision Trees

    -

    Two algorithms stand out in the set up of decision trees:

    +

    Algorithms for Setting up Decision Trees

    + +

    +Two algorithms stand out in the set up of decision trees: +

    1. The CART (Classification And Regression Tree) algorithm for both classification and regression
    2. The ID3 algorithm based on the computation of the information gain for classification
    -

    We discuss both algorithms with applications here. The popular library + +We discuss both algorithms with applications here. The popular library Scikit-Learn uses the CART algorithm. For classification problems you can use either the gini index or the entropy to split a tree in two branches. -

    +











    -

    The CART algorithm for Classification

    -

    For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +

    The CART algorithm for Classification

    + +

    +For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). This could be for example a threshold set by a number below a certain circumference of a malign tumor. -

    -

    How do we find these two quantities? +

    +How do we find these two quantities? We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). The cost function it tries to minimize is then -

    $$ C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, $$ -

    where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) +where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) is the number of instances in the left/right subset -

    -

    Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +

    +Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the \( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), \( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). -

    +











    -

    The CART algorithm for Regression

    -

    The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +

    The CART algorithm for Regression

    + +

    +The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now -

    $$ C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. $$ -

    Here the MSE for a specific node is defined as

    +Here the MSE for a specific node is defined as $$ \mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, $$ -

    with

    +with $$ \overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, $$ -

    the mean value of all observations in a specific node.

    +the mean value of all observations in a specific node. -

    Without any regularization, the regression task for decision trees, +

    +Without any regularization, the regression task for decision trees, just like for classification tasks, is prone to overfitting. -

    +











    -

    Computing the Gini index

    -

    The example we will look at is a classical one in many Machine +

    Computing the Gini index

    + +

    +The example we will look at is a classical one in many Machine Learning applications. Based on various meteorological features, we have several so-called attributes which decide whether we at the end will do some outdoor activity like skiing, going for a bike ride etc @@ -1059,10 +952,10 @@ etc. The table here contains the feautures outlook, temperature, attributes for each feature are then sunny, overcast and rain for the outlook, hot, cold and mild for temperature, high and normal for humidity and weak and strong for wind. -

    -

    The table here summarizes the various attributes and

    - +

    +The table here summarizes the various attributes and +

    @@ -1083,18 +976,15 @@ humidity and weak and strong for wind.
    Day Outlook Temperature Humidity Wind Ride
    14 Rain Mild High Strong 0
    - +











    -

    Simple Python Code to read in Data and perform Classification

    +

    Simple Python Code to read in Data and perform Classification

    + +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -1161,41 +1051,25 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Computing the Gini Factor

    -

    The above functions (gini, entropy and misclassification error) are +

    Computing the Gini Factor

    + +

    +The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm below after we have discussed the information gain algorithm ID3. -

    -

    In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.

    +

    +In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. +

    -

    -
    -
    -
    -
    -
    # Split a dataset based on an attribute and an attribute value
    +
    # Split a dataset based on an attribute and an attribute value
     def test_split(index, value, dataset):
     	left, right = list(), list()
     	for row in dataset:
    @@ -1255,28 +1129,15 @@ dataset = [[0,0
     
     split = get_split(dataset)
     print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Entropy and the ID3 algorithm

    -

    The ID3 algorithm learns decision trees by constructing +

    Entropy and the ID3 algorithm

    + +

    +The ID3 algorithm learns decision trees by constructing them in a top down way, beginning with the question which attribute should be tested at the root of the tree? -

    1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
    2. @@ -1286,34 +1147,33 @@ them in a top down way, beginning with the question which attribute should be
    3. 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.
    4. 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 + +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 +

    +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?

    +

    +What is a good quantitative measure of the worth of an attribute? -

    Information gain measures how well a given attribute separates the +

    +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 +

    +The ID3 algorithm uses this information gain measure to select among the candidate attributes at each step while growing the tree. -

    +











    -

    Cancer Data again now with Decision Trees and other Methods

    + +

    Cancer Data again now with Decision Trees and other Methods

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -1354,32 +1214,15 @@ svm.fit(X_train_scaled, y_train)
     # 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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Another example, the moons again

    + +

    Another example, the moons again

    +

    -

    -
    -
    -
    -
    -
    from __future__ import division, print_function, unicode_literals
    +
    from __future__ import division, print_function, unicode_literals
     
     # Common imports
     import numpy as np
    @@ -1443,32 +1286,15 @@ plt.subplot(122)
     plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
     plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Playing around with regions

    + +

    Playing around with regions

    +

    -

    -
    -
    -
    -
    -
    np.random.seed(6)
    +
    np.random.seed(6)
     Xs = np.random.rand(100, 2) - 0.5
     ys = (Xs[:, 0] > 0).astype(np.float32) * 2
     
    @@ -1488,86 +1314,37 @@ plt.subplot(122)
     plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Regression trees

    + +

    Regression trees

    +

    -

    -
    -
    -
    -
    -
    # Quadratic training set + noise
    +
    # 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
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    +
    from sklearn.tree import DecisionTreeRegressor
     
     tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
     tree_reg.fit(X, y)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Final regressor code

    + +

    Final regressor code

    +

    -

    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    +
    from sklearn.tree import DecisionTreeRegressor
     
     tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
     tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
    @@ -1605,26 +1382,11 @@ plt.text(0.3, 0
     plt.title("max_depth=3", fontsize=14)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    tree_reg1 = DecisionTreeRegressor(random_state=42)
    +
    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)
    @@ -1652,24 +1414,11 @@ plt.xlabel("$x_1$", fontsize="min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Pros and cons of trees, pros

    + +

    Pros and cons of trees, pros

    • 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)
    • @@ -1680,8 +1429,10 @@ plt.show()
    • 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

    + +

    Disadvantages

    • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
    • @@ -1692,26 +1443,28 @@ plt.show()
    • 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 + +However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved. -

    +











    -

    Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

    -

    As stated above and seen in many of the examples discussed here about +

    Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

    + +

    +As stated above and seen in many of the examples discussed here about a single decision tree, we often end up overfitting our training data. This normally means that we have a high variance. Can we reduce the variance of a statistical learning method? -

    -

    This leads us to a set of different methods that can combine different +

    +This leads us to a set of different methods that can combine different machine learning algorithms or just use one of them to construct forests and jungles of trees, homogeneous ones or heterogenous ones. These methods are recognized by different names which we will try to explain here. These are -

    1. Voting classifiers
    2. @@ -1719,45 +1472,50 @@ try to explain here. These are
    3. Random forests
    4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
    -

    We discuss these methods here.

    +We discuss these methods here. + +











    -

    An Overview of Ensemble Methods

    -

    -
    -

    -
    -

    +

    An Overview of Ensemble Methods

    +

    +



    + +











    -

    Bagging

    -

    The plain decision trees suffer from high +

    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. -

    +of \( n \) to \( p \) is moderately large. -

    Bootstrap aggregation, or just bagging, is a +

    +Bootstrap aggregation, or just bagging, is a general-purpose procedure for reducing the variance of a statistical -learning method. -

    +learning method. +











    -

    More bagging

    -

    Bagging typically results in improved accuracy +

    More bagging

    + +

    +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 +

    +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 @@ -1772,18 +1530,15 @@ 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. -

    +











    -

    Simple Voting Example, head or tail

    + +

    Simple Voting Example, head or tail

    +

    -

    -
    -
    -
    -
    -
    heads_proba = 0.51
    +
    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))
    @@ -1796,32 +1551,15 @@ plt.legend(loc="lower right")
     plt.axis([0, 10000, 0.42, 0.58])
     save_fig("votingsimple")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Using the Voting Classifier

    + +

    Using the Voting Classifier

    +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -1864,33 +1602,16 @@ voting_clf.fit(X_train, y_train)
         clf.fit(X_train, y_train)
         y_pred = clf.predict(X_test)
         print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Please, not the moons again! Voting and Bagging

    +

    Please, not the moons again! Voting and Bagging

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -1908,51 +1629,21 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='hard')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    log_clf = LogisticRegression(random_state=42)
    +
    log_clf = LogisticRegression(random_state=42)
     rnd_clf = RandomForestClassifier(random_state=42)
     svm_clf = SVC(probability=True, random_state=42)
     
    @@ -1960,58 +1651,26 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='soft')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Bagging Examples

    +

    Bagging Examples

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.ensemble import BaggingClassifier
    +
    from sklearn.ensemble import BaggingClassifier
     from sklearn.tree import DecisionTreeClassifier
     
     bag_clf = BaggingClassifier(
    @@ -2019,70 +1678,25 @@ bag_clf = BaggingClassifier(
         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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    from sklearn.metrics import accuracy_score
     print(accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    tree_clf = DecisionTreeClassifier(random_state=42)
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from matplotlib.colors import ListedColormap
    +
    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)
    @@ -2109,36 +1723,19 @@ plot_decision_boundary(bag_clf, X, y)
     plt.title("Decision Trees with Bagging", fontsize=14)
     save_fig("baggingtree")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Making your own Bootstrap: Changing the Level of the Decision Tree

    -

    Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +

    Making your own Bootstrap: Changing the Level of the Decision Tree

    + +

    +Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). -

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     from sklearn.pipeline import make_pipeline
    @@ -2195,81 +1792,69 @@ plt.plot(polydegree, variance, label='Variance&
     plt.legend()
     save_fig("baggingboot")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Why Voting?

    -

    The idea behind boosting, and voting as well can be phrased as follows: +

    Why Voting?

    + +

    +The idea behind boosting, and voting as well can be phrased as follows: Can a group of people somehow arrive at highly reasoned decisions, despite the weak judgement of the individual members? -

    -

    The aim is to create a good classifier by combining several weak classifiers. +

    +The aim is to create a good classifier by combining several weak classifiers. A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random. -

    -

    The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. +

    +The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in -each iteration. -

    +each iteration. -

    Decision trees play an important role as our weak classifier. They serve as the basic method.

    +

    +Decision trees play an important role as our weak classifier. They serve as the basic method. +











    -

    Tossing coins

    -

    The simplest case is a so-called voting ensemble. To illustrate this, +

    Tossing coins

    + +

    +The simplest case is a so-called voting ensemble. To illustrate this, think of yourself tossing coins with a biased outcome of 51 per cent for heads and 49% for tails. With only few tosses, you may not clearly see this distribution for heads and tails. However, after some thousands of tosses, there will be a clear majority of heads. With 2000 tosses you should see approximately 1020 heads and 980 tails. -

    -

    We can then state that the outcome is a clear majority of heads. If +

    +We can then state that the outcome is a clear majority of heads. If you do this ten thousand times, it is easy to see that there is a 97% likelihood of a majority of heads. -

    -

    Another example would be to collect all polls before an +

    +Another example would be to collect all polls before an election. Different polls may show different likelihoods for a candidate winning with say a majority of the popular vote. The majority vote would then consist in many polls indicating that this candidate will actually win. -

    -

    The example here shows how we can implement the coin tossing case, +

    +The example here shows how we can implement the coin tossing case, clealry demostrating that after some tosses we see the law of large numbers kicking in. -

    +











    -

    Standard imports first

    +

    Standard imports first

    + +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     from IPython.display import Image 
     from pydot import graph_from_dot_data
     import pandas as pd
    @@ -2306,32 +1891,15 @@ DATA_ID = "DataFiles/"
     
     def save_fig(fig_id):
         plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Simple Voting Example, head or tail

    + +

    Simple Voting Example, head or tail

    +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     import matplotlib
     import matplotlib.pyplot as plt
    @@ -2353,34 +1921,18 @@ plt.legend(loc="lower right")
     plt.axis([0, 10000, 0.42, 0.58])
     save_fig("votingsimple")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Using the Voting Classifier

    -

    We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.

    +

    Using the Voting Classifier

    + +

    +We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn. +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -2422,33 +1974,16 @@ voting_clf.fit(X_train, y_train)
         clf.fit(X_train, y_train)
         y_pred = clf.predict(X_test)
         print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Voting and Bagging

    +

    Voting and Bagging

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -2466,51 +2001,21 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='hard')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    log_clf = LogisticRegression(random_state=42)
    +
    log_clf = LogisticRegression(random_state=42)
     rnd_clf = RandomForestClassifier(random_state=42)
     svm_clf = SVC(probability=True, random_state=42)
     
    @@ -2518,76 +2023,49 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='soft')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Random forests

    -

    Random forests provide an improvement over bagged trees by way of a -small tweak that decorrelates the trees. -

    +

    Random forests

    -

    As in bagging, we build a +

    +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. -

    +use only one of those \( m \) predictors. -

    A fresh sample of \( m \) predictors is +

    +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 +

    +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. -

    +a majority of the available predictors. -

    The reason for this is rather clever. Suppose that there is one very +

    +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 @@ -2599,36 +2077,41 @@ lead to as large of a reduction in variance as averaging many uncorrelated quantities. In particular, this means that bagging will not lead to a substantial reduction in variance over a single tree in this setting. -

    +











    -

    Random Forest Algorithm

    -

    The algorithm described here can be applied to both classification and regression problems.

    -

    We will grow of forest of say \( B \) trees.

    +

    Random Forest Algorithm

    +The algorithm described here can be applied to both classification and regression problems. + +

    +We will grow of forest of say \( B \) trees. +

    1. For \( b=1:B \)
    2. +
      • Draw a bootstrap sample from the training data organized in our \( \boldsymbol{X} \) matrix.
      • We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
      • +
        1. we select \( m \le p \) variables at random from the \( p \) predictors/features
        2. pick the best split point among the \( m \) features using for example the CART algorithm and create a new node
        3. split the node into daughter nodes
        +
      +
    3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
    +









    -

    Random Forests Compared with other Methods on the Cancer Data

    + +

    Random Forests Compared with other Methods on the Cancer Data

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -2694,374 +2177,362 @@ skplt.metrics.plot_roc(y_test, y_probas)
     plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Recall that the cumulative gains curve shows the percentage of the +

    +

    +Recall that the cumulative gains curve shows the percentage of the overall number of cases in a given category gained by targeting a percentage of the total number of cases. -

    -

    Similarly, the receiver operating characteristic curve, or ROC curve, +

    +Similarly, the receiver operating characteristic curve, or ROC curve, displays the diagnostic ability of a binary classifier system as its discrimination threshold is varied. It plots the true positive rate against the false positive rate. -

    +











    -

    Compare Bagging on Trees with Random Forests

    + +

    Compare Bagging on Trees with Random Forests

    +

    -

    -
    -
    -
    -
    -
    bag_clf = BaggingClassifier(
    +
    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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    bag_clf.fit(X_train, y_train)
    +
    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) 
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Boosting, a Bird's Eye View

    -

    The basic idea is to combine weak classifiers in order to create a good +

    Boosting, a Bird's Eye View

    + +

    +The basic idea is to combine weak classifiers in order to create a good classifier. With a weak classifier we often intend a classifier which produces results which are only slightly better than we would get by random guesses. -

    -

    This is done by applying in an iterative way a weak (or a standard +

    +This is done by applying in an iterative way a weak (or a standard classifier like decision trees) to modify the data. In each iteration we emphasize those observations which are misclassified by weighting them with a factor. -

    +











    -

    What is boosting? Additive Modelling/Iterative Fitting

    -

    Boosting is a way of fitting an additive expansion in a set of +

    What is boosting? Additive Modelling/Iterative Fitting

    + +

    +Boosting is a way of fitting an additive expansion in a set of elementary basis functions like for example some simple polynomials. Assume for example that we have a function -

    $$ f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ -

    where \( \beta_m \) are the expansion parameters to be determined in a +

    +where \( \beta_m \) are the expansion parameters to be determined in a minimization process and \( b(x;\gamma_m) \) are some simple functions of the multivariable parameter \( x \) which is characterized by the parameters \( \gamma_m \). -

    -

    As an example, consider the Sigmoid function we used in logistic +

    +As an example, consider the Sigmoid function we used in logistic regression. In that case, we can translate the function \( b(x;\gamma_m) \) into the Sigmoid function -

    $$ \sigma(t) = \frac{1}{1+\exp{(-t)}}, $$ -

    where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and +

    +where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and \( \gamma_1 \) were determined by the Logistic Regression fitting algorithm. -

    -

    As another example, consider the cost function we defined for linear regression

    +

    +As another example, consider the cost function we defined for linear regression $$ C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    In this case the function \( f(x) \) was replaced by the design matrix +

    +In this case the function \( f(x) \) was replaced by the design matrix \( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can simply invert a matrix and obtain the parameters \( \beta \) by -

    $$ \boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

    In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).

    +

    +In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \). +











    -

    Iterative Fitting, Regression and Squared-error Cost Function

    -

    The way we proceed is as follows (here we specialize to the squared-error cost function)

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    + +

    +The way we proceed is as follows (here we specialize to the squared-error cost function)

    1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
    2. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    3. For \( m=1:M \) +
      1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
      2. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
      3. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
      +
    -

    We could use any of the algorithms we have discussed till now. If we + +We could use any of the algorithms we have discussed till now. If we use trees, \( \gamma \) parameterizes the split variables and split points at the internal nodes, and the predictions at the terminal nodes. -

    +











    -

    Squared-Error Example and Iterative Fitting

    -

    To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.

    +

    Squared-Error Example and Iterative Fitting

    -

    For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \).

    +

    +To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. -

    This means that for every iteration \( m \), we need to optimize

    +

    +For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). + +

    +This means that for every iteration \( m \), we need to optimize $$ (\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. $$ -

    We start our iteration by simply setting \( f_0(x)=0 \). +

    +We start our iteration by simply setting \( f_0(x)=0 \). Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain -

    $$ \frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, $$ -

    and

    +and $$ \frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. $$ -

    We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)

    +We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) $$ \gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, $$ -

    which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have

    +which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have $$ \beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, $$ -

    which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting -for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. -

    +

    +which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting +for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. -

    The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as -\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). -

    +

    +The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as +\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). +











    -

    Iterative Fitting, Classification and AdaBoost

    -

    Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +

    Iterative Fitting, Classification and AdaBoost

    + +

    +Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values \( \{-1,1\} \). -

    -

    The error rate of the training sample is then

    +

    +The error rate of the training sample is then $$ \mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). $$ -

    The iterative procedure starts with defining a weak classifier whose +

    +The iterative procedure starts with defining a weak classifier whose error rate is barely better than random guessing. The iterative procedure in boosting is to sequentially apply a weak classification algorithm to repeatedly modified versions of the data producing a sequence of weak classifiers \( G_m(x) \). -

    -

    Here we will express our function \( f(x) \) in terms of \( G(x) \). That is

    +

    +Here we will express our function \( f(x) \) in terms of \( G(x) \). That is $$ f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ -

    will be a function of

    +will be a function of $$ G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). $$ - +











    -

    Adaptive Boosting, AdaBoost

    -

    In our iterative procedure we define thus

    +

    Adaptive Boosting, AdaBoost

    + +

    +In our iterative procedure we define thus $$ f_m(x) = f_{m-1}(x)+\beta_mG_m(x). $$ -

    The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the +

    +The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the exponential cost/loss function defined as -

    $$ C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. $$ -

    We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. +

    +We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. This is normally done in two steps. Let us however first rewrite the cost function as -

    $$ C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, $$ -

    where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

    +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \). +











    -

    Building up AdaBoost

    -

    First, for any \( \beta > 0 \), we optimize \( G \) by setting

    +

    Building up AdaBoost

    + +

    +First, for any \( \beta > 0 \), we optimize \( G \) by setting $$ G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), $$ -

    which is the classifier that minimizes the weighted error rate in predicting \( y \).

    +which is the classifier that minimizes the weighted error rate in predicting \( y \). -

    We can do this by rewriting

    +

    +We can do this by rewriting $$ \exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, $$ -

    which can be rewritten as

    +which can be rewritten as $$ (\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, $$ -

    which leads to

    +which leads to $$ \beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, $$ -

    where we have redefined the error as

    +where we have redefined the error as $$ \mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, $$ -

    which leads to an update of

    +which leads to an update of $$ f_m(x) = f_{m-1}(x) +\beta_m G_m(x). $$ -

    This leads to the new weights

    +This leads to the new weights $$ w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} $$ - +











    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    -

    The algorithm here is rather straightforward. Assume that our weak +

    Adaptive boosting: AdaBoost, Basic Algorithm

    + +

    +The algorithm here is rather straightforward. Assume that our weak classifier is a decision tree and we consider a binary set of outputs with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of observations. Our design matrix is given in terms of the feature/predictor vectors \( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a -classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). -

    +classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). -

    We have already defined the misclassification error \( \mathrm{err} \) as

    +

    +We have already defined the misclassification error \( \mathrm{err} \) as $$ \mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), $$ -

    where the function \( I() \) is one if we misclassify and zero if we classify correctly.

    +where the function \( I() \) is one if we misclassify and zero if we classify correctly. +











    -

    Basic Steps of AdaBoost

    -

    With the above definitions we are now ready to set up the algorithm for AdaBoost. +

    Basic Steps of AdaBoost

    + +

    +With the above definitions we are now ready to set up the algorithm for AdaBoost. The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. -

    +
    1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
    2. We rewrite the misclassification error as
    + $$ \mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, $$ +
    1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. +
      1. Fit then a given classifier to the training set using the weights \( w_i \).
      2. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
      3. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
      4. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
      +
    2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
    -

    For the iterations with \( m \le 2 \) the weights are modified + +For the iterations with \( m \le 2 \) the weights are modified individually at each steps. The observations which were misclassified at iteration \( m-1 \) have a weight which is larger than those which were classified properly. As this proceeds, the observations which were difficult to classifiy correctly are given a larger influence. Each new classification step \( m \) is then forced to concentrate on those observations that are missed in the previous iterations. -

    +











    -

    AdaBoost Examples

    -

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.

    +

    AdaBoost Examples

    +

    +Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. + +

    -

    -
    -
    -
    -
    -
    from sklearn.ensemble import AdaBoostClassifier
    +
    from sklearn.ensemble import AdaBoostClassifier
     
     ada_clf = AdaBoostClassifier(
         DecisionTreeClassifier(max_depth=1), n_estimators=200,
    @@ -3082,115 +2553,114 @@ skplt.metrics.plot_roc(y_test, y_probas)
     plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    -

    Gradient boosting is again a similar technique to Adaptive boosting, +

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    + +

    +Gradient boosting is again a similar technique to Adaptive boosting, it combines so-called weak classifiers or regressors into a strong method via a series of iterations. -

    -

    In order to understand the method, let us illustrate its basics by +

    +In order to understand the method, let us illustrate its basics by bringing back the essential steps in linear regression, where our cost function was the least squares function. -

    +











    -

    The Squared-Error again! Steepest Descent

    -

    We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize +

    The Squared-Error again! Steepest Descent

    + +

    +We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize This means that for every iteration, we need to optimize -

    $$ (\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as

    +

    +We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as $$ f_M(x) = \sum_{m=0}^M h_m(x). $$ -

    In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as

    +

    +In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as $$ g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. $$ -

    With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that +

    +With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). -

    -

    Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have

    +

    +Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have $$ (\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. $$ - +











    -

    Steepest Descent Example

    -

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that

    +

    Steepest Descent Example

    + +

    +Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that $$ f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. $$ -

    We can then proceed and compute

    +We can then proceed and compute $$ g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, $$ -

    and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting.

    +and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting. +











    -

    Gradient Boosting, algorithm

    -

    Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, +

    Gradient Boosting, algorithm

    + +

    +Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, so we do not learn a function that can generalize. However, we can modify the algorithm by -fitting a weak learner to approximate the negative gradient signal. -

    +fitting a weak learner to approximate the negative gradient signal. -

    Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function

    +

    +Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function $$ C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    The way we proceed in an iterative fashion is to

    +

    +The way we proceed in an iterative fashion is to +

    1. Initialize our estimate \( f_0(x) \).
    2. For \( m=1:M \), we +
      1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
      2. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      3. update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);
      +
    3. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    +









    -

    Gradient Boosting, Examples of Regression

    + +

    Gradient Boosting, Examples of Regression

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     from sklearn.ensemble import GradientBoostingRegressor
    @@ -3236,32 +2706,15 @@ plt.plot(polydegree, variance, label='Variance&
     plt.legend()
     save_fig("gdregression")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Gradient Boosting, Classification Example

    + +

    Gradient Boosting, Classification Example

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -3301,51 +2754,37 @@ plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     save_fig("gdclassiffiercgain")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    XGBoost: Extreme Gradient Boosting

    -

    XGBoost or Extreme Gradient +

    XGBoost: Extreme Gradient Boosting

    + +

    +XGBoost or Extreme Gradient Boosting, is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting that solve many data science problems in a fast and accurate way. See the article by Chen and Guestrin. -

    -

    The authors design and build a highly scalable end-to-end tree +

    +The authors design and build a highly scalable end-to-end tree boosting system. It has a theoretically justified weighted quantile sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. -

    -

    It is now the algorithm which wins essentially all ML competitions!!!

    +

    +It is now the algorithm which wins essentially all ML competitions!!! +











    -

    Regression Case

    +

    Regression Case

    + +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     import xgboost as xgb
    @@ -3391,34 +2830,18 @@ plt.plot(polydegree, bias, label='bias''Variance')
     plt.legend()
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Xgboost on the Cancer Data

    -

    As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.

    +

    Xgboost on the Cancer Data

    + +

    +As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -3469,26 +2892,18 @@ xgb.plot_importance(xg_clf)
     plt.rcParams['figure.figsize'] = [5, 5]
     save_fig("xgparams")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - +
    +

    + +

    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    + + + diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html index 7794e13ef..497127df5 100644 --- a/doc/pub/week45/html/week45.html +++ b/doc/pub/week45/html/week45.html @@ -1,105 +1,36 @@ - + + Week 45: Decisions Trees, Random Forests, Bagging and Boosting + + + + @@ -378,122 +220,144 @@ MathJax.Hub.Config({ - -
    -

    Week 45: Decisions Trees, Random Forests, Bagging and Boosting

    -
    + + + + + +

    Week 45: Decisions Trees, Random Forests, Bagging and Boosting

    + +

    +

    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 -
    -
    -
    -

    Nov 9, 2021

    -
    -
    +

    + + +

    [1] Department of Physics, University of Oslo
    +
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    +
    +

    +

    Nov 10, 2021

    +
    +











    -

    Overview of week 45

    + +

    Overview of week 45

    • Thursday: Basics of Decision Trees, Bagging and Voting
    • Friday: More on Bagging, Voting, Random Forests and start Boosting
    + -
    -Reading

    +

    +Reading. +

    +

    1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion.
    +











    -

    Decision trees, overarching aims

    -

    We start here with the most basic algorithm, the so-called decision +

    Decision trees, overarching aims

    + +

    +We start here with the most basic algorithm, the so-called decision tree. With this basic algorithm we can in turn build more complex networks, spanning from homogeneous and heterogenous forests (bagging, random forests and more) to one of the most popular supervised algorithms nowadays, the extreme gradient boosting, or just XGBoost. But let us start with the simplest possible ingredient. -

    -

    Decision trees are supervised learning algorithms used for both, +

    +Decision trees are supervised learning algorithms used for both, classification and regression tasks. -

    -

    The main idea of decision trees +

    +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 +

    +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. -

    +where we then finally end up in so called leaf nodes. +











    -

    Basics of a tree

    -

    A decision tree is typically divided into a root node, the interior nodes, +

    Basics of a tree

    + +

    +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 +

    +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 Sketch of a Tree, Regression problem

    +

    A Sketch of a Tree, Regression problem

    + +

    +











    -

    A Sketch of a Tree, Classification problem

    +

    A Sketch of a Tree, Classification problem

    + +

    +











    -

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    -

    -
    -

    -
    -

    +

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    -

    This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches.

    +

    +



    +

    +This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches. + +











    -

    General Features

    -

    The overarching approach to decision trees is a top-down approach.

    +

    General Features

    + +

    +The overarching approach to decision trees is a top-down approach.

    • A leaf provides the classification of a given instance.
    • @@ -501,16 +365,18 @@ given some assumptions, make predictions about the target feature value
    • 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 + +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 +

    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: -

    1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
    2. @@ -518,18 +384,17 @@ predicting the target features of query instances is as follows:
    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
    4. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    -

    Then we are essentially done!

    +Then we are essentially done! + +











    -

    Decision trees and Regression

    + +

    Decision trees and Regression

    +

    -

    -
    -
    -
    -
    -
    import numpy as np
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.preprocessing import PolynomialFeatures
     from sklearn.linear_model import LinearRegression
    @@ -617,102 +482,96 @@ plt.ylabel(&quo
     plt.title("Decision Tree Regression")
     plt.legend()
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Building a tree, regression

    -

    There are mainly two steps

    +

    Building a tree, regression

    + +

    +There are mainly two steps +

    1. 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 \).
    2. 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 + +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 \). -

    +

    +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 +

    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 +

    +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 +

    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

    +and $$ \left\{X\vert x_j \geq s\right\}, $$ -

    so that we obtain the lowest MSE, that is

    +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 +

    +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 +

    +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 +

    +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 +

    +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 @@ -721,83 +580,95 @@ 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 +

    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 +

    +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 \). -

    -

    Read more at the following Scikit-Learn link on pruning.

    +

    +Read more at the following Scikit-Learn link on pruning. +











    -

    Cost complexity pruning

    -

    For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that

    +

    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 +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 +

    +The tuning parameter \( \alpha \) controls a trade-off between the subtree’s complexity 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. -

    +tend to be minimized for a smaller subtree. -

    It turns out that as we increase \( \alpha \) from zero +

    +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 \). -

    +subtree corresponding to \( \alpha \). +











    -

    Schematic Regression Procedure

    +

    Schematic Regression Procedure

    + +

    -Building a Regression Tree +Building a Regression Tree.

    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.
    2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    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:
    4. +
      • 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.
      +
    5. 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 +

    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 @@ -808,13 +679,15 @@ 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. -

    +fall into that region. +











    -

    Growing a classification tree

    -

    The task of growing a +

    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 @@ -824,69 +697,72 @@ 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. -

    +belong to the most common class. -

    When building a classification tree, either the Gini index or the +

    +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. -

    +than is the classification error rate. +











    -

    Classification tree, how to split nodes

    -

    If our targets are the outcome of a classification process that takes +

    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 +

    +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). +p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). $$ -

    We let \( p_{mk} \) represent the majority class of observations in region +

    +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
    + $$ -p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +\frac{1}{N_m}\sum_{i\in R_m}I(y_i\ne k) = 1-p_{mk}. $$ +
    • Gini index \( g \)
    + $$ g = \sum_{k=1}^K p_{mk}(1-p_{mk}). $$ +
    • Information entropy or just entropy \( s \)
    + $$ s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. $$ - +











    -

    Visualizing the Tree, Classification

    + +

    Visualizing the Tree, Classification

    +

    -

    -
    -
    -
    -
    -
    import os
    +
    import os
     from sklearn.datasets import load_breast_cancer
     from sklearn.tree import DecisionTreeClassifier
     from sklearn.model_selection import train_test_split
    @@ -919,32 +795,15 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Visualizing the Tree, The Moons

    + +

    Visualizing the Tree, The Moons

    +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.tree import DecisionTreeClassifier
    @@ -968,72 +827,39 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Other ways of visualizing the trees

    -

    Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.

    +

    Other ways of visualizing the trees

    +

    +Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data. + +

    -

    -
    -
    -
    -
    -
    from sklearn.datasets import load_iris
    +
    from sklearn.datasets import load_iris
     from sklearn import tree
     X, y = load_iris(return_X_y=True)
     tree_clf = tree.DecisionTreeClassifier()
     tree_clf = tree_clf.fit(X, y)
     # and then plot the tree
     tree.plot_tree(tree_clf) 
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Printing out as text

    -

    Alternatively, the tree can also be exported in textual format with the function exporttext. +

    Printing out as text

    + +

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

    +

    -

    -
    -
    -
    -
    -
    from sklearn.datasets import load_iris
    +
    from sklearn.datasets import load_iris
     from sklearn.tree import DecisionTreeClassifier
     from sklearn.tree import export_text
     iris = load_iris()
    @@ -1041,92 +867,87 @@ decision_tree = DecisionTreeClassifier(rando
     decision_tree = decision_tree.fit(iris.data, iris.target)
     r = export_text(decision_tree, feature_names=iris['feature_names'])
     print(r)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Algorithms for Setting up Decision Trees

    -

    Two algorithms stand out in the set up of decision trees:

    +

    Algorithms for Setting up Decision Trees

    + +

    +Two algorithms stand out in the set up of decision trees: +

    1. The CART (Classification And Regression Tree) algorithm for both classification and regression
    2. The ID3 algorithm based on the computation of the information gain for classification
    -

    We discuss both algorithms with applications here. The popular library + +We discuss both algorithms with applications here. The popular library Scikit-Learn uses the CART algorithm. For classification problems you can use either the gini index or the entropy to split a tree in two branches. -

    +











    -

    The CART algorithm for Classification

    -

    For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +

    The CART algorithm for Classification

    + +

    +For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). This could be for example a threshold set by a number below a certain circumference of a malign tumor. -

    -

    How do we find these two quantities? +

    +How do we find these two quantities? We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). The cost function it tries to minimize is then -

    $$ C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, $$ -

    where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) +where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) is the number of instances in the left/right subset -

    -

    Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +

    +Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the \( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), \( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). -

    +











    -

    The CART algorithm for Regression

    -

    The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +

    The CART algorithm for Regression

    + +

    +The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now -

    $$ C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. $$ -

    Here the MSE for a specific node is defined as

    +Here the MSE for a specific node is defined as $$ \mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, $$ -

    with

    +with $$ \overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, $$ -

    the mean value of all observations in a specific node.

    +the mean value of all observations in a specific node. -

    Without any regularization, the regression task for decision trees, +

    +Without any regularization, the regression task for decision trees, just like for classification tasks, is prone to overfitting. -

    +











    -

    Computing the Gini index

    -

    The example we will look at is a classical one in many Machine +

    Computing the Gini index

    + +

    +The example we will look at is a classical one in many Machine Learning applications. Based on various meteorological features, we have several so-called attributes which decide whether we at the end will do some outdoor activity like skiing, going for a bike ride etc @@ -1136,10 +957,10 @@ etc. The table here contains the feautures outlook, temperature, attributes for each feature are then sunny, overcast and rain for the outlook, hot, cold and mild for temperature, high and normal for humidity and weak and strong for wind. -

    -

    The table here summarizes the various attributes and

    - +

    +The table here summarizes the various attributes and +

    @@ -1160,18 +981,15 @@ humidity and weak and strong for wind.
    Day Outlook Temperature Humidity Wind Ride
    14 Rain Mild High Strong 0
    - +











    -

    Simple Python Code to read in Data and perform Classification

    +

    Simple Python Code to read in Data and perform Classification

    + +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -1238,41 +1056,25 @@ export_graphviz(
     )
     cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
     os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Computing the Gini Factor

    -

    The above functions (gini, entropy and misclassification error) are +

    Computing the Gini Factor

    + +

    +The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm below after we have discussed the information gain algorithm ID3. -

    -

    In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.

    +

    +In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. +

    -

    -
    -
    -
    -
    -
    # Split a dataset based on an attribute and an attribute value
    +
    # Split a dataset based on an attribute and an attribute value
     def test_split(index, value, dataset):
     	left, right = list(), list()
     	for row in dataset:
    @@ -1332,28 +1134,15 @@ dataset = [[0= get_split(dataset)
     print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Entropy and the ID3 algorithm

    -

    The ID3 algorithm learns decision trees by constructing +

    Entropy and the ID3 algorithm

    + +

    +The ID3 algorithm learns decision trees by constructing them in a top down way, beginning with the question which attribute should be tested at the root of the tree? -

    1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
    2. @@ -1363,34 +1152,33 @@ them in a top down way, beginning with the question which attribute should be
    3. 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.
    4. 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 + +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 +

    +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?

    +

    +What is a good quantitative measure of the worth of an attribute? -

    Information gain measures how well a given attribute separates the +

    +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 +

    +The ID3 algorithm uses this information gain measure to select among the candidate attributes at each step while growing the tree. -

    +











    -

    Cancer Data again now with Decision Trees and other Methods

    + +

    Cancer Data again now with Decision Trees and other Methods

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -1431,32 +1219,15 @@ svm.fit(X_train_scaled, y_train)
     # 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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Another example, the moons again

    + +

    Another example, the moons again

    +

    -

    -
    -
    -
    -
    -
    from __future__ import division, print_function, unicode_literals
    +
    from __future__ import division, print_function, unicode_literals
     
     # Common imports
     import numpy as np
    @@ -1520,32 +1291,15 @@ plt.subplot(122
     plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
     plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Playing around with regions

    + +

    Playing around with regions

    +

    -

    -
    -
    -
    -
    -
    np.random.seed(6)
    +
    np.random.seed(6)
     Xs = np.random.rand(100, 2) - 0.5
     ys = (Xs[:, 0] > 0).astype(np.float32) * 2
     
    @@ -1565,86 +1319,37 @@ plt.subplot(122
     plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Regression trees

    + +

    Regression trees

    +

    -

    -
    -
    -
    -
    -
    # Quadratic training set + noise
    +
    # 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
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    +
    from sklearn.tree import DecisionTreeRegressor
     
     tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
     tree_reg.fit(X, y)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Final regressor code

    + +

    Final regressor code

    +

    -

    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    +
    from sklearn.tree import DecisionTreeRegressor
     
     tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
     tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
    @@ -1682,26 +1387,11 @@ plt.text(0.3.title("max_depth=3", fontsize=14)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    tree_reg1 = DecisionTreeRegressor(random_state=42)
    +
    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)
    @@ -1729,24 +1419,11 @@ plt.xlabel(&quo
     plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
     
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Pros and cons of trees, pros

    + +

    Pros and cons of trees, pros

    • 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)
    • @@ -1757,8 +1434,10 @@ plt.show()
    • 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

    + +

    Disadvantages

    • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
    • @@ -1769,26 +1448,28 @@ plt.show()
    • 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 + +However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved. -

    +











    -

    Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

    -

    As stated above and seen in many of the examples discussed here about +

    Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

    + +

    +As stated above and seen in many of the examples discussed here about a single decision tree, we often end up overfitting our training data. This normally means that we have a high variance. Can we reduce the variance of a statistical learning method? -

    -

    This leads us to a set of different methods that can combine different +

    +This leads us to a set of different methods that can combine different machine learning algorithms or just use one of them to construct forests and jungles of trees, homogeneous ones or heterogenous ones. These methods are recognized by different names which we will try to explain here. These are -

    1. Voting classifiers
    2. @@ -1796,45 +1477,50 @@ try to explain here. These are
    3. Random forests
    4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
    -

    We discuss these methods here.

    +We discuss these methods here. + +











    -

    An Overview of Ensemble Methods

    -

    -
    -

    -
    -

    +

    An Overview of Ensemble Methods

    +

    +



    + +











    -

    Bagging

    -

    The plain decision trees suffer from high +

    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. -

    +of \( n \) to \( p \) is moderately large. -

    Bootstrap aggregation, or just bagging, is a +

    +Bootstrap aggregation, or just bagging, is a general-purpose procedure for reducing the variance of a statistical -learning method. -

    +learning method. +











    -

    More bagging

    -

    Bagging typically results in improved accuracy +

    More bagging

    + +

    +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 +

    +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 @@ -1849,18 +1535,15 @@ 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. -

    +











    -

    Simple Voting Example, head or tail

    + +

    Simple Voting Example, head or tail

    +

    -

    -
    -
    -
    -
    -
    heads_proba = 0.51
    +
    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))
    @@ -1873,32 +1556,15 @@ plt.legend(loc=
     plt.axis([0, 10000, 0.42, 0.58])
     save_fig("votingsimple")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Using the Voting Classifier

    + +

    Using the Voting Classifier

    +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -1941,33 +1607,16 @@ voting_clf.fit(X_train, y_train)
         clf.fit(X_train, y_train)
         y_pred = clf.predict(X_test)
         print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Please, not the moons again! Voting and Bagging

    +

    Please, not the moons again! Voting and Bagging

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -1985,51 +1634,21 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='hard')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    log_clf = LogisticRegression(random_state=42)
    +
    log_clf = LogisticRegression(random_state=42)
     rnd_clf = RandomForestClassifier(random_state=42)
     svm_clf = SVC(probability=True, random_state=42)
     
    @@ -2037,58 +1656,26 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='soft')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Bagging Examples

    +

    Bagging Examples

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.ensemble import BaggingClassifier
    +
    from sklearn.ensemble import BaggingClassifier
     from sklearn.tree import DecisionTreeClassifier
     
     bag_clf = BaggingClassifier(
    @@ -2096,70 +1683,25 @@ bag_clf = BaggingClassifier(
         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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    from sklearn.metrics import accuracy_score
     print(accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    tree_clf = DecisionTreeClassifier(random_state=42)
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from matplotlib.colors import ListedColormap
    +
    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)
    @@ -2186,36 +1728,19 @@ plot_decision_boundary(bag_clf, X, y)
     plt.title("Decision Trees with Bagging", fontsize=14)
     save_fig("baggingtree")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Making your own Bootstrap: Changing the Level of the Decision Tree

    -

    Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +

    Making your own Bootstrap: Changing the Level of the Decision Tree

    + +

    +Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). -

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     from sklearn.pipeline import make_pipeline
    @@ -2272,81 +1797,69 @@ plt.plot(polydegree, variance, label.legend()
     save_fig("baggingboot")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Why Voting?

    -

    The idea behind boosting, and voting as well can be phrased as follows: +

    Why Voting?

    + +

    +The idea behind boosting, and voting as well can be phrased as follows: Can a group of people somehow arrive at highly reasoned decisions, despite the weak judgement of the individual members? -

    -

    The aim is to create a good classifier by combining several weak classifiers. +

    +The aim is to create a good classifier by combining several weak classifiers. A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random. -

    -

    The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. +

    +The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in -each iteration. -

    +each iteration. -

    Decision trees play an important role as our weak classifier. They serve as the basic method.

    +

    +Decision trees play an important role as our weak classifier. They serve as the basic method. +











    -

    Tossing coins

    -

    The simplest case is a so-called voting ensemble. To illustrate this, +

    Tossing coins

    + +

    +The simplest case is a so-called voting ensemble. To illustrate this, think of yourself tossing coins with a biased outcome of 51 per cent for heads and 49% for tails. With only few tosses, you may not clearly see this distribution for heads and tails. However, after some thousands of tosses, there will be a clear majority of heads. With 2000 tosses you should see approximately 1020 heads and 980 tails. -

    -

    We can then state that the outcome is a clear majority of heads. If +

    +We can then state that the outcome is a clear majority of heads. If you do this ten thousand times, it is easy to see that there is a 97% likelihood of a majority of heads. -

    -

    Another example would be to collect all polls before an +

    +Another example would be to collect all polls before an election. Different polls may show different likelihoods for a candidate winning with say a majority of the popular vote. The majority vote would then consist in many polls indicating that this candidate will actually win. -

    -

    The example here shows how we can implement the coin tossing case, +

    +The example here shows how we can implement the coin tossing case, clealry demostrating that after some tosses we see the law of large numbers kicking in. -

    +











    -

    Standard imports first

    +

    Standard imports first

    + +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     from IPython.display import Image 
     from pydot import graph_from_dot_data
     import pandas as pd
    @@ -2383,32 +1896,15 @@ DATA_ID = "
     
     def save_fig(fig_id):
         plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Simple Voting Example, head or tail

    + +

    Simple Voting Example, head or tail

    +

    -

    -
    -
    -
    -
    -
    # Common imports
    +
    # Common imports
     import numpy as np
     import matplotlib
     import matplotlib.pyplot as plt
    @@ -2430,34 +1926,18 @@ plt.legend(loc=
     plt.axis([0, 10000, 0.42, 0.58])
     save_fig("votingsimple")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Using the Voting Classifier

    -

    We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.

    +

    Using the Voting Classifier

    + +

    +We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn. +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -2499,33 +1979,16 @@ voting_clf.fit(X_train, y_train)
         clf.fit(X_train, y_train)
         y_pred = clf.predict(X_test)
         print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Voting and Bagging

    +

    Voting and Bagging

    + +

    -

    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    +
    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)
    @@ -2543,51 +2006,21 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='hard')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    log_clf = LogisticRegression(random_state=42)
    +
    log_clf = LogisticRegression(random_state=42)
     rnd_clf = RandomForestClassifier(random_state=42)
     svm_clf = SVC(probability=True, random_state=42)
     
    @@ -2595,76 +2028,49 @@ voting_clf = VotingClassifier(
         estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
         voting='soft')
     voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    +
    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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Random forests

    -

    Random forests provide an improvement over bagged trees by way of a -small tweak that decorrelates the trees. -

    +

    Random forests

    -

    As in bagging, we build a +

    +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. -

    +use only one of those \( m \) predictors. -

    A fresh sample of \( m \) predictors is +

    +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 +

    +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. -

    +a majority of the available predictors. -

    The reason for this is rather clever. Suppose that there is one very +

    +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 @@ -2676,36 +2082,41 @@ lead to as large of a reduction in variance as averaging many uncorrelated quantities. In particular, this means that bagging will not lead to a substantial reduction in variance over a single tree in this setting. -

    +











    -

    Random Forest Algorithm

    -

    The algorithm described here can be applied to both classification and regression problems.

    -

    We will grow of forest of say \( B \) trees.

    +

    Random Forest Algorithm

    +The algorithm described here can be applied to both classification and regression problems. + +

    +We will grow of forest of say \( B \) trees. +

    1. For \( b=1:B \)
    2. +
      • Draw a bootstrap sample from the training data organized in our \( \boldsymbol{X} \) matrix.
      • We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
      • +
        1. we select \( m \le p \) variables at random from the \( p \) predictors/features
        2. pick the best split point among the \( m \) features using for example the CART algorithm and create a new node
        3. split the node into daughter nodes
        +
      +
    3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
    +









    -

    Random Forests Compared with other Methods on the Cancer Data

    + +

    Random Forests Compared with other Methods on the Cancer Data

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -2771,374 +2182,362 @@ skplt.metrics.<
     plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    Recall that the cumulative gains curve shows the percentage of the +

    +

    +Recall that the cumulative gains curve shows the percentage of the overall number of cases in a given category gained by targeting a percentage of the total number of cases. -

    -

    Similarly, the receiver operating characteristic curve, or ROC curve, +

    +Similarly, the receiver operating characteristic curve, or ROC curve, displays the diagnostic ability of a binary classifier system as its discrimination threshold is varied. It plots the true positive rate against the false positive rate. -

    +











    -

    Compare Bagging on Trees with Random Forests

    + +

    Compare Bagging on Trees with Random Forests

    +

    -

    -
    -
    -
    -
    -
    bag_clf = BaggingClassifier(
    +
    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)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +
    +

    + -

    -
    -
    -
    -
    -
    bag_clf.fit(X_train, y_train)
    +
    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) 
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Boosting, a Bird's Eye View

    -

    The basic idea is to combine weak classifiers in order to create a good +

    Boosting, a Bird's Eye View

    + +

    +The basic idea is to combine weak classifiers in order to create a good classifier. With a weak classifier we often intend a classifier which produces results which are only slightly better than we would get by random guesses. -

    -

    This is done by applying in an iterative way a weak (or a standard +

    +This is done by applying in an iterative way a weak (or a standard classifier like decision trees) to modify the data. In each iteration we emphasize those observations which are misclassified by weighting them with a factor. -

    +











    -

    What is boosting? Additive Modelling/Iterative Fitting

    -

    Boosting is a way of fitting an additive expansion in a set of +

    What is boosting? Additive Modelling/Iterative Fitting

    + +

    +Boosting is a way of fitting an additive expansion in a set of elementary basis functions like for example some simple polynomials. Assume for example that we have a function -

    $$ f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ -

    where \( \beta_m \) are the expansion parameters to be determined in a +

    +where \( \beta_m \) are the expansion parameters to be determined in a minimization process and \( b(x;\gamma_m) \) are some simple functions of the multivariable parameter \( x \) which is characterized by the parameters \( \gamma_m \). -

    -

    As an example, consider the Sigmoid function we used in logistic +

    +As an example, consider the Sigmoid function we used in logistic regression. In that case, we can translate the function \( b(x;\gamma_m) \) into the Sigmoid function -

    $$ \sigma(t) = \frac{1}{1+\exp{(-t)}}, $$ -

    where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and +

    +where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and \( \gamma_1 \) were determined by the Logistic Regression fitting algorithm. -

    -

    As another example, consider the cost function we defined for linear regression

    +

    +As another example, consider the cost function we defined for linear regression $$ C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    In this case the function \( f(x) \) was replaced by the design matrix +

    +In this case the function \( f(x) \) was replaced by the design matrix \( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can simply invert a matrix and obtain the parameters \( \beta \) by -

    $$ \boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

    In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).

    +

    +In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \). +











    -

    Iterative Fitting, Regression and Squared-error Cost Function

    -

    The way we proceed is as follows (here we specialize to the squared-error cost function)

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    + +

    +The way we proceed is as follows (here we specialize to the squared-error cost function)

    1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
    2. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    3. For \( m=1:M \) +
      1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
      2. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
      3. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
      +
    -

    We could use any of the algorithms we have discussed till now. If we + +We could use any of the algorithms we have discussed till now. If we use trees, \( \gamma \) parameterizes the split variables and split points at the internal nodes, and the predictions at the terminal nodes. -

    +











    -

    Squared-Error Example and Iterative Fitting

    -

    To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.

    +

    Squared-Error Example and Iterative Fitting

    -

    For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \).

    +

    +To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. -

    This means that for every iteration \( m \), we need to optimize

    +

    +For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). + +

    +This means that for every iteration \( m \), we need to optimize $$ (\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. $$ -

    We start our iteration by simply setting \( f_0(x)=0 \). +

    +We start our iteration by simply setting \( f_0(x)=0 \). Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain -

    $$ \frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, $$ -

    and

    +and $$ \frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. $$ -

    We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)

    +We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) $$ \gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, $$ -

    which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have

    +which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have $$ \beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, $$ -

    which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting -for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. -

    +

    +which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting +for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. -

    The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as -\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). -

    +

    +The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as +\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). +











    -

    Iterative Fitting, Classification and AdaBoost

    -

    Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +

    Iterative Fitting, Classification and AdaBoost

    + +

    +Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values \( \{-1,1\} \). -

    -

    The error rate of the training sample is then

    +

    +The error rate of the training sample is then $$ \mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). $$ -

    The iterative procedure starts with defining a weak classifier whose +

    +The iterative procedure starts with defining a weak classifier whose error rate is barely better than random guessing. The iterative procedure in boosting is to sequentially apply a weak classification algorithm to repeatedly modified versions of the data producing a sequence of weak classifiers \( G_m(x) \). -

    -

    Here we will express our function \( f(x) \) in terms of \( G(x) \). That is

    +

    +Here we will express our function \( f(x) \) in terms of \( G(x) \). That is $$ f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ -

    will be a function of

    +will be a function of $$ G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). $$ - +











    -

    Adaptive Boosting, AdaBoost

    -

    In our iterative procedure we define thus

    +

    Adaptive Boosting, AdaBoost

    + +

    +In our iterative procedure we define thus $$ f_m(x) = f_{m-1}(x)+\beta_mG_m(x). $$ -

    The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the +

    +The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the exponential cost/loss function defined as -

    $$ C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. $$ -

    We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. +

    +We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. This is normally done in two steps. Let us however first rewrite the cost function as -

    $$ C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, $$ -

    where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

    +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \). +











    -

    Building up AdaBoost

    -

    First, for any \( \beta > 0 \), we optimize \( G \) by setting

    +

    Building up AdaBoost

    + +

    +First, for any \( \beta > 0 \), we optimize \( G \) by setting $$ G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), $$ -

    which is the classifier that minimizes the weighted error rate in predicting \( y \).

    +which is the classifier that minimizes the weighted error rate in predicting \( y \). -

    We can do this by rewriting

    +

    +We can do this by rewriting $$ \exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, $$ -

    which can be rewritten as

    +which can be rewritten as $$ (\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, $$ -

    which leads to

    +which leads to $$ \beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, $$ -

    where we have redefined the error as

    +where we have redefined the error as $$ \mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, $$ -

    which leads to an update of

    +which leads to an update of $$ f_m(x) = f_{m-1}(x) +\beta_m G_m(x). $$ -

    This leads to the new weights

    +This leads to the new weights $$ w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} $$ - +











    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    -

    The algorithm here is rather straightforward. Assume that our weak +

    Adaptive boosting: AdaBoost, Basic Algorithm

    + +

    +The algorithm here is rather straightforward. Assume that our weak classifier is a decision tree and we consider a binary set of outputs with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of observations. Our design matrix is given in terms of the feature/predictor vectors \( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a -classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). -

    +classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). -

    We have already defined the misclassification error \( \mathrm{err} \) as

    +

    +We have already defined the misclassification error \( \mathrm{err} \) as $$ \mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), $$ -

    where the function \( I() \) is one if we misclassify and zero if we classify correctly.

    +where the function \( I() \) is one if we misclassify and zero if we classify correctly. +











    -

    Basic Steps of AdaBoost

    -

    With the above definitions we are now ready to set up the algorithm for AdaBoost. +

    Basic Steps of AdaBoost

    + +

    +With the above definitions we are now ready to set up the algorithm for AdaBoost. The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. -

    +
    1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
    2. We rewrite the misclassification error as
    + $$ \mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, $$ +
    1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. +
      1. Fit then a given classifier to the training set using the weights \( w_i \).
      2. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
      3. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
      4. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
      +
    2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
    -

    For the iterations with \( m \le 2 \) the weights are modified + +For the iterations with \( m \le 2 \) the weights are modified individually at each steps. The observations which were misclassified at iteration \( m-1 \) have a weight which is larger than those which were classified properly. As this proceeds, the observations which were difficult to classifiy correctly are given a larger influence. Each new classification step \( m \) is then forced to concentrate on those observations that are missed in the previous iterations. -

    +











    -

    AdaBoost Examples

    -

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.

    +

    AdaBoost Examples

    +

    +Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. + +

    -

    -
    -
    -
    -
    -
    from sklearn.ensemble import AdaBoostClassifier
    +
    from sklearn.ensemble import AdaBoostClassifier
     
     ada_clf = AdaBoostClassifier(
         DecisionTreeClassifier(max_depth=1), n_estimators=200,
    @@ -3159,115 +2558,114 @@ skplt.metrics.<
     plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    -

    Gradient boosting is again a similar technique to Adaptive boosting, +

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    + +

    +Gradient boosting is again a similar technique to Adaptive boosting, it combines so-called weak classifiers or regressors into a strong method via a series of iterations. -

    -

    In order to understand the method, let us illustrate its basics by +

    +In order to understand the method, let us illustrate its basics by bringing back the essential steps in linear regression, where our cost function was the least squares function. -

    +











    -

    The Squared-Error again! Steepest Descent

    -

    We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize +

    The Squared-Error again! Steepest Descent

    + +

    +We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize This means that for every iteration, we need to optimize -

    $$ (\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as

    +

    +We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as $$ f_M(x) = \sum_{m=0}^M h_m(x). $$ -

    In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as

    +

    +In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as $$ g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. $$ -

    With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that +

    +With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). -

    -

    Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have

    +

    +Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have $$ (\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. $$ - +











    -

    Steepest Descent Example

    -

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that

    +

    Steepest Descent Example

    + +

    +Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that $$ f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. $$ -

    We can then proceed and compute

    +We can then proceed and compute $$ g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, $$ -

    and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting.

    +and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting. +











    -

    Gradient Boosting, algorithm

    -

    Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, +

    Gradient Boosting, algorithm

    + +

    +Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, so we do not learn a function that can generalize. However, we can modify the algorithm by -fitting a weak learner to approximate the negative gradient signal. -

    +fitting a weak learner to approximate the negative gradient signal. -

    Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function

    +

    +Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function $$ C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -

    The way we proceed in an iterative fashion is to

    +

    +The way we proceed in an iterative fashion is to +

    1. Initialize our estimate \( f_0(x) \).
    2. For \( m=1:M \), we +
      1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
      2. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      3. update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);
      +
    3. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    +









    -

    Gradient Boosting, Examples of Regression

    + +

    Gradient Boosting, Examples of Regression

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     from sklearn.ensemble import GradientBoostingRegressor
    @@ -3313,32 +2711,15 @@ plt.plot(polydegree, variance, label.legend()
     save_fig("gdregression")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Gradient Boosting, Classification Example

    + +

    Gradient Boosting, Classification Example

    +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -3378,51 +2759,37 @@ plt.show()
     skplt.metrics.plot_cumulative_gain(y_test, y_probas)
     save_fig("gdclassiffiercgain")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    XGBoost: Extreme Gradient Boosting

    -

    XGBoost or Extreme Gradient +

    XGBoost: Extreme Gradient Boosting

    + +

    +XGBoost or Extreme Gradient Boosting, is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting that solve many data science problems in a fast and accurate way. See the article by Chen and Guestrin. -

    -

    The authors design and build a highly scalable end-to-end tree +

    +The authors design and build a highly scalable end-to-end tree boosting system. It has a theoretically justified weighted quantile sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. -

    -

    It is now the algorithm which wins essentially all ML competitions!!!

    +

    +It is now the algorithm which wins essentially all ML competitions!!! +











    -

    Regression Case

    +

    Regression Case

    + +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import train_test_split
     import xgboost as xgb
    @@ -3468,34 +2835,18 @@ plt.plot(polydegree, bias, label.plot(polydegree, variance, label='Variance')
     plt.legend()
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - +
    +











    -

    Xgboost on the Cancer Data

    -

    As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.

    +

    Xgboost on the Cancer Data

    + +

    +As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. +

    -

    -
    -
    -
    -
    -
    import matplotlib.pyplot as plt
    +
    import matplotlib.pyplot as plt
     import numpy as np
     from sklearn.model_selection import  train_test_split 
     from sklearn.datasets import load_breast_cancer
    @@ -3546,26 +2897,18 @@ xgb.plot_importance(xg_clf)
     plt.rcParams['figure.figsize'] = [5, 5]
     save_fig("xgparams")
     plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - +
    +

    + +

    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    + + + diff --git a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz index b424739dd..1b3d5b1f4 100644 Binary files a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz and b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz differ diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb index 6a20f05e4..887022d0d 100644 --- a/doc/pub/week45/ipynb/week45.ipynb +++ b/doc/pub/week45/ipynb/week45.ipynb @@ -2,38 +2,20 @@ "cells": [ { "cell_type": "markdown", - "id": "999587fc", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "f3ea736a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ + "\n", "# Week 45: Decisions Trees, Random Forests, Bagging and Boosting\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: **Nov 9, 2021**\n", + "Date: **Nov 10, 2021**\n", + "\n", + "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", "\n", - "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" - ] - }, - { - "cell_type": "markdown", - "id": "f4a62cf4", - "metadata": { - "editable": true - }, - "source": [ "## Overview of week 45\n", "\n", "* Thursday: Basics of Decision Trees, Bagging and Voting\n", @@ -46,20 +28,18 @@ "\n", "[Video on boosting methods by Hastie](https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai).\n", "\n", + "\n", + "\n", "**Reading.**\n", "\n", - "1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion." - ] - }, - { - "cell_type": "markdown", - "id": "7d7e0a30", - "metadata": { - "editable": true - }, - "source": [ + "1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion.\n", + "\n", + "\n", + "\n", + "\n", "## Decision trees, overarching aims\n", "\n", + "\n", "We start here with the most basic algorithm, the so-called decision\n", "tree. With this basic algorithm we can in turn build more complex\n", "networks, spanning from homogeneous and heterogenous forests (bagging,\n", @@ -70,6 +50,7 @@ "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", @@ -79,16 +60,8 @@ "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**." - ] - }, - { - "cell_type": "markdown", - "id": "f448055c", - "metadata": { - "editable": true - }, - "source": [ + "where we then finally end up in so called **leaf nodes**. \n", + "\n", "## Basics of a tree\n", "\n", "A decision tree is typically divided into a **root node**, the **interior nodes**,\n", @@ -99,58 +72,35 @@ "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." - ] - }, - { - "cell_type": "markdown", - "id": "0cacfbd6", - "metadata": { - "editable": true - }, - "source": [ + "(class) of unseen query instances.\n", + "\n", "## A Sketch of a Tree, Regression problem\n", "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "09cac93a", - "metadata": { - "editable": true - }, - "source": [ + "\n", + "\n", + "\n", + "\n", "## A Sketch of a Tree, Classification problem\n", "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "9e7e3a96", - "metadata": { - "editable": true - }, - "source": [ + "\n", + "\n", + "\n", + "\n", "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n", "\n", "\n", "\n", "\n", - "

    Figure 1:

    \n", + "

    \n", + "\n", + "\n", "\n", "\n", - "This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using **Scikit-Learn**'s decision tree classifier. Here we have used the so-called **gini** index (see below) to split the various branches." - ] - }, - { - "cell_type": "markdown", - "id": "260a1d3f", - "metadata": { - "editable": true - }, - "source": [ + "\n", + "This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using **Scikit-Learn**'s decision tree classifier. Here we have used the so-called **gini** index (see below) to split the various branches.\n", + "\n", + "\n", + "\n", "## General Features\n", "\n", "The overarching approach to decision trees is a top-down approach.\n", @@ -164,18 +114,12 @@ "* 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." - ] - }, - { - "cell_type": "markdown", - "id": "71e35330", - "metadata": { - "editable": true - }, - "source": [ + "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", @@ -187,26 +131,20 @@ "\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!" - ] - }, - { - "cell_type": "markdown", - "id": "c999b0f7", - "metadata": { - "editable": true - }, - "source": [ + "Then we are essentially done!\n", + "\n", + "\n", + "\n", + "\n", + "\n", "## Decision trees and Regression" ] }, { "cell_type": "code", "execution_count": 1, - "id": "d3154072", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -304,10 +242,7 @@ }, { "cell_type": "markdown", - "id": "f38fb41a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Building a tree, regression\n", "\n", @@ -326,10 +261,7 @@ }, { "cell_type": "markdown", - "id": "3f153956", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\sum_{j=1}^J\\sum_{i\\in R_j}(y_i-\\overline{y}_{R_j})^2,\n", @@ -338,22 +270,11 @@ }, { "cell_type": "markdown", - "id": "be1e684e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $\\overline{y}_{R_j}$ is the mean response for the training observations \n", - "within box $j$." - ] - }, - { - "cell_type": "markdown", - "id": "69f23ebf", - "metadata": { - "editable": true - }, - "source": [ + "within box $j$. \n", + "\n", "## A top-down approach, recursive binary splitting\n", "\n", "Unfortunately, it is computationally infeasible to consider every\n", @@ -366,16 +287,8 @@ "further down on the tree. It is greedy because at each step of the\n", "tree-building process, the best split is made at that particular step,\n", "rather than looking ahead and picking a split that will lead to a\n", - "better tree in some future step." - ] - }, - { - "cell_type": "markdown", - "id": "0c7546ee", - "metadata": { - "editable": true - }, - "source": [ + "better tree in some future step.\n", + "\n", "## Making a tree\n", "\n", "In order to implement the recursive binary splitting we start by selecting\n", @@ -384,10 +297,7 @@ }, { "cell_type": "markdown", - "id": "901c465d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\left\\{X\\vert x_j < s\\right\\},\n", @@ -396,20 +306,14 @@ }, { "cell_type": "markdown", - "id": "f193d5dc", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", - "id": "5b6fee06", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\left\\{X\\vert x_j \\geq s\\right\\},\n", @@ -418,20 +322,14 @@ }, { "cell_type": "markdown", - "id": "fb7f787a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "so that we obtain the lowest MSE, that is" ] }, { "cell_type": "markdown", - "id": "76179adf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\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,\n", @@ -440,10 +338,7 @@ }, { "cell_type": "markdown", - "id": "6c8ec2b3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which we want to minimize by considering all predictors\n", "$x_1,x_2,\\dots,x_p$. We consider also all possible values of $s$ for\n", @@ -468,16 +363,9 @@ "have three regions. Again, we look to split one of these three regions\n", "further, so as to minimize the MSE. The process continues until a\n", "stopping criterion is reached; for instance, we may continue until no\n", - "region contains more than five observations." - ] - }, - { - "cell_type": "markdown", - "id": "ee74a1ea", - "metadata": { - "editable": true - }, - "source": [ + "region contains more than five observations.\n", + "\n", + "\n", "## Pruning the tree\n", "\n", "The above procedure is rather straightforward, but leads often to\n", @@ -492,16 +380,8 @@ "we consider a sequence of trees indexed by a nonnegative tuning\n", "parameter $\\alpha$.\n", "\n", - "Read more at the following [Scikit-Learn link on pruning](https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py)." - ] - }, - { - "cell_type": "markdown", - "id": "6ab80129", - "metadata": { - "editable": true - }, - "source": [ + "Read more at the following [Scikit-Learn link on pruning](https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py).\n", + "\n", "## Cost complexity pruning\n", "\n", "For each value of $\\alpha$ there corresponds a subtree $T \\in T_0$ such that" @@ -509,10 +389,7 @@ }, { "cell_type": "markdown", - "id": "4fb3b414", - "metadata": { - "editable": true - }, + "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", @@ -521,10 +398,7 @@ }, { "cell_type": "markdown", - "id": "4a53cd13", - "metadata": { - "editable": true - }, + "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", @@ -539,25 +413,20 @@ "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$." - ] - }, - { - "cell_type": "markdown", - "id": "d4972eb3", - "metadata": { - "editable": true - }, - "source": [ + "subtree corresponding to $\\alpha$. \n", + "\n", + "\n", "## Schematic Regression Procedure\n", "\n", "**Building a Regression Tree.**\n", "\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", @@ -570,16 +439,12 @@ "\n", " * Finally we average the results for each value of $\\alpha$, and pick $\\alpha$ to minimize the average error.\n", "\n", - "4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$." - ] - }, - { - "cell_type": "markdown", - "id": "fa21cd89", - "metadata": { - "editable": true - }, - "source": [ + "\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", @@ -593,16 +458,8 @@ "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." - ] - }, - { - "cell_type": "markdown", - "id": "ed9e140f", - "metadata": { - "editable": true - }, - "source": [ + "fall into that region. \n", + "\n", "## Growing a classification tree\n", "\n", "The task of growing a\n", @@ -620,16 +477,9 @@ "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." - ] - }, - { - "cell_type": "markdown", - "id": "8339299a", - "metadata": { - "editable": true - }, - "source": [ + "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", @@ -644,22 +494,16 @@ }, { "cell_type": "markdown", - "id": "5a01e8b0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", - "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i=k).\n", + "p_{mk} = \\frac{1}{N_m}\\sum_{i\\in R_m}I(y_i=k).\n", "$$" ] }, { "cell_type": "markdown", - "id": "3b46b1a0", - "metadata": { - "editable": true - }, + "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", @@ -669,32 +513,23 @@ }, { "cell_type": "markdown", - "id": "bf8cf60e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", - "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n", + "\\frac{1}{N_m}\\sum_{i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "91bb9314", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "* Gini index $g$" ] }, { "cell_type": "markdown", - "id": "21041ba3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "g = \\sum_{k=1}^K p_{mk}(1-p_{mk}).\n", @@ -703,20 +538,14 @@ }, { "cell_type": "markdown", - "id": "27f57a10", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "* Information entropy or just entropy $s$" ] }, { "cell_type": "markdown", - "id": "28610811", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n", @@ -725,10 +554,7 @@ }, { "cell_type": "markdown", - "id": "448db121", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Visualizing the Tree, Classification" ] @@ -736,10 +562,8 @@ { "cell_type": "code", "execution_count": 2, - "id": "daa33ec4", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -780,10 +604,7 @@ }, { "cell_type": "markdown", - "id": "c35660d4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Visualizing the Tree, The Moons" ] @@ -791,10 +612,8 @@ { "cell_type": "code", "execution_count": 3, - "id": "20d3782d", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -826,10 +645,7 @@ }, { "cell_type": "markdown", - "id": "4b50c098", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Other ways of visualizing the trees\n", "\n", @@ -839,10 +655,8 @@ { "cell_type": "code", "execution_count": 4, - "id": "df24658e", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -857,10 +671,7 @@ }, { "cell_type": "markdown", - "id": "88327e54", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Printing out as text\n", "\n", @@ -871,10 +682,8 @@ { "cell_type": "code", "execution_count": 5, - "id": "cabfc0eb", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -890,10 +699,7 @@ }, { "cell_type": "markdown", - "id": "f9b97781", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Algorithms for Setting up Decision Trees\n", "\n", @@ -905,16 +711,8 @@ "We discuss both algorithms with applications here. The popular library\n", "**Scikit-Learn** uses the CART algorithm. For classification problems\n", "you can use either the **gini** index or the **entropy** to split a tree\n", - "in two branches." - ] - }, - { - "cell_type": "markdown", - "id": "6d158b95", - "metadata": { - "editable": true - }, - "source": [ + "in two branches.\n", + "\n", "## The CART algorithm for Classification\n", "\n", "For classification, the CART algorithm splits the data set in two subsets using a single feature $k$ and a threshold $t_k$.\n", @@ -927,10 +725,7 @@ }, { "cell_type": "markdown", - "id": "3916a0a9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n", @@ -939,10 +734,7 @@ }, { "cell_type": "markdown", - "id": "35e64400", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $G_{\\mathrm{left/right}}$ measures the impurity of the left/right subset and $m_{\\mathrm{left/right}}$\n", " is the number of instances in the left/right subset\n", @@ -951,16 +743,8 @@ "and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the\n", "$max\\_depth$ hyperparameter), or if it cannot find a split that will reduce impurity. A few other\n", "hyperparameters control additional stopping conditions such as the $min\\_samples\\_split$,\n", - "$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$." - ] - }, - { - "cell_type": "markdown", - "id": "6b6f2758", - "metadata": { - "editable": true - }, - "source": [ + "$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$.\n", + "\n", "## The CART algorithm for Regression\n", "\n", "The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the\n", @@ -969,10 +753,7 @@ }, { "cell_type": "markdown", - "id": "56a085e6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}\\mathrm{MSE}_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}\\mathrm{MSE}_{\\mathrm{right}}.\n", @@ -981,20 +762,14 @@ }, { "cell_type": "markdown", - "id": "fa6f435c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Here the MSE for a specific node is defined as" ] }, { "cell_type": "markdown", - "id": "8afa690b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n", @@ -1003,20 +778,14 @@ }, { "cell_type": "markdown", - "id": "1b9c7d84", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "with" ] }, { "cell_type": "markdown", - "id": "1af13ff9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n", @@ -1025,24 +794,14 @@ }, { "cell_type": "markdown", - "id": "aa4dc553", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "the mean value of all observations in a specific node.\n", "\n", "Without any regularization, the regression task for decision trees, \n", - "just like for classification tasks, is prone to overfitting." - ] - }, - { - "cell_type": "markdown", - "id": "aa1afc4e", - "metadata": { - "editable": true - }, - "source": [ + "just like for classification tasks, is prone to overfitting.\n", + "\n", + "\n", "## Computing the Gini index\n", "\n", "The example we will look at is a classical one in many Machine\n", @@ -1057,7 +816,7 @@ "humidity and weak and strong for wind.\n", "\n", "The table here summarizes the various attributes and\n", - "\n", + "
    \n", "\n", "\n", "\n", @@ -1077,26 +836,16 @@ "\n", "\n", "\n", - "
    Day Outlook Temperature Humidity Wind Ride
    13 Overcast Hot Normal Weak 1
    14 Rain Mild High Strong 0
    " - ] - }, - { - "cell_type": "markdown", - "id": "391b026f", - "metadata": { - "editable": true - }, - "source": [ + "\n", + "\n", "## Simple Python Code to read in Data and perform Classification" ] }, { "cell_type": "code", "execution_count": 6, - "id": "5d786a97", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1171,10 +920,7 @@ }, { "cell_type": "markdown", - "id": "2ed48016", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Computing the Gini Factor\n", "\n", @@ -1189,10 +935,8 @@ { "cell_type": "code", "execution_count": 7, - "id": "a3b26fd1", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1260,10 +1004,7 @@ }, { "cell_type": "markdown", - "id": "2896b4f4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Entropy and the ID3 algorithm\n", "\n", @@ -1294,26 +1035,17 @@ "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." - ] - }, - { - "cell_type": "markdown", - "id": "fea0e5e6", - "metadata": { - "editable": true - }, - "source": [ + "attributes at each step while growing the tree.\n", + "\n", + "\n", "## Cancer Data again now with Decision Trees and other Methods" ] }, { "cell_type": "code", "execution_count": 8, - "id": "1dbc948a", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1362,10 +1094,7 @@ }, { "cell_type": "markdown", - "id": "7b0d35e1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Another example, the moons again" ] @@ -1373,10 +1102,8 @@ { "cell_type": "code", "execution_count": 9, - "id": "ef709f87", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1448,10 +1175,7 @@ }, { "cell_type": "markdown", - "id": "e7a8b237", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Playing around with regions" ] @@ -1459,10 +1183,8 @@ { "cell_type": "code", "execution_count": 10, - "id": "c5be70d1", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1490,10 +1212,7 @@ }, { "cell_type": "markdown", - "id": "0c4d5dab", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Regression trees" ] @@ -1501,10 +1220,8 @@ { "cell_type": "code", "execution_count": 11, - "id": "0963d7fc", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1519,10 +1236,8 @@ { "cell_type": "code", "execution_count": 12, - "id": "689f738f", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1534,10 +1249,7 @@ }, { "cell_type": "markdown", - "id": "f476fc1b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Final regressor code" ] @@ -1545,10 +1257,8 @@ { "cell_type": "code", "execution_count": 13, - "id": "ec98869a", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1595,10 +1305,8 @@ { "cell_type": "code", "execution_count": 14, - "id": "ae89b603", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1634,10 +1342,7 @@ }, { "cell_type": "markdown", - "id": "f4c99932", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Pros and cons of trees, pros\n", "\n", @@ -1653,16 +1358,8 @@ "\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)" - ] - }, - { - "cell_type": "markdown", - "id": "bcc7fb3d", - "metadata": { - "editable": true - }, - "source": [ + "* 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", @@ -1681,16 +1378,9 @@ "\n", "However, by aggregating many decision trees, using methods like\n", "bagging, random forests, and boosting, the predictive performance of\n", - "trees can be substantially improved." - ] - }, - { - "cell_type": "markdown", - "id": "029c3b45", - "metadata": { - "editable": true - }, - "source": [ + "trees can be substantially improved.\n", + "\n", + "\n", "## Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n", "\n", "As stated above and seen in many of the examples discussed here about\n", @@ -1712,32 +1402,22 @@ "\n", "4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n", "\n", - "We discuss these methods here." - ] - }, - { - "cell_type": "markdown", - "id": "597ecf99", - "metadata": { - "editable": true - }, - "source": [ + "We discuss these methods here.\n", + "\n", + "\n", "## An Overview of Ensemble Methods\n", "\n", "\n", "\n", "\n", - "

    Figure 1:

    \n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "34ccd8a6", - "metadata": { - "editable": true - }, - "source": [ + "

    \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", "## Bagging\n", "\n", "The **plain** decision trees suffer from high\n", @@ -1750,16 +1430,9 @@ "\n", "**Bootstrap aggregation**, or just **bagging**, is a\n", "general-purpose procedure for reducing the variance of a statistical\n", - "learning method." - ] - }, - { - "cell_type": "markdown", - "id": "60285855", - "metadata": { - "editable": true - }, - "source": [ + "learning method. \n", + "\n", + "\n", "## More bagging\n", "\n", "Bagging typically results in improved accuracy\n", @@ -1782,26 +1455,16 @@ "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." - ] - }, - { - "cell_type": "markdown", - "id": "da86704c", - "metadata": { - "editable": true - }, - "source": [ + "predictor, averaged over all $B$ trees.\n", + "\n", "## Simple Voting Example, head or tail" ] }, { "cell_type": "code", "execution_count": 15, - "id": "86f01d7b", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1822,10 +1485,7 @@ }, { "cell_type": "markdown", - "id": "66aa1558", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Using the Voting Classifier" ] @@ -1833,10 +1493,8 @@ { "cell_type": "code", "execution_count": 16, - "id": "1782fb88", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1887,10 +1545,7 @@ }, { "cell_type": "markdown", - "id": "f5aa4b7b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Please, not the moons again! Voting and Bagging" ] @@ -1898,10 +1553,8 @@ { "cell_type": "code", "execution_count": 17, - "id": "3c1a494b", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1928,10 +1581,8 @@ { "cell_type": "code", "execution_count": 18, - "id": "15cc6ef1", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1946,10 +1597,8 @@ { "cell_type": "code", "execution_count": 19, - "id": "d5380589", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1966,10 +1615,8 @@ { "cell_type": "code", "execution_count": 20, - "id": "2630974e", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1983,10 +1630,7 @@ }, { "cell_type": "markdown", - "id": "4bb8f29b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Bagging Examples" ] @@ -1994,10 +1638,8 @@ { "cell_type": "code", "execution_count": 21, - "id": "47d6424f", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2014,10 +1656,8 @@ { "cell_type": "code", "execution_count": 22, - "id": "554b7c3e", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2028,10 +1668,8 @@ { "cell_type": "code", "execution_count": 23, - "id": "5cdabae8", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2044,10 +1682,8 @@ { "cell_type": "code", "execution_count": 24, - "id": "511564a7", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2082,10 +1718,7 @@ }, { "cell_type": "markdown", - "id": "2179d349", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Making your own Bootstrap: Changing the Level of the Decision Tree\n", "\n", @@ -2096,10 +1729,8 @@ { "cell_type": "code", "execution_count": 25, - "id": "42afc36e", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2165,10 +1796,7 @@ }, { "cell_type": "markdown", - "id": "5b790359", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Why Voting?\n", "\n", @@ -2184,16 +1812,8 @@ "In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in\n", "each iteration. \n", "\n", - "Decision trees play an important role as our weak classifier. They serve as the basic method." - ] - }, - { - "cell_type": "markdown", - "id": "c3c7a9fd", - "metadata": { - "editable": true - }, - "source": [ + "Decision trees play an important role as our weak classifier. They serve as the basic method. \n", + "\n", "## Tossing coins\n", "\n", "The simplest case is a so-called voting ensemble. To illustrate this,\n", @@ -2215,26 +1835,16 @@ "\n", "The example here shows how we can implement the coin tossing case,\n", "clealry demostrating that after some tosses we see the [law of large](https://en.wikipedia.org/wiki/Law_of_large_numbers)\n", - "numbers kicking in." - ] - }, - { - "cell_type": "markdown", - "id": "50fc15a0", - "metadata": { - "editable": true - }, - "source": [ + "numbers kicking in.\n", + "\n", "## Standard imports first" ] }, { "cell_type": "code", "execution_count": 26, - "id": "c0b99f8c", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2279,10 +1889,7 @@ }, { "cell_type": "markdown", - "id": "69f8628e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Simple Voting Example, head or tail" ] @@ -2290,10 +1897,8 @@ { "cell_type": "code", "execution_count": 27, - "id": "805d4227", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2324,10 +1929,7 @@ }, { "cell_type": "markdown", - "id": "49717d4a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Using the Voting Classifier\n", "\n", @@ -2337,10 +1939,8 @@ { "cell_type": "code", "execution_count": 28, - "id": "34a0cc41", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2390,10 +1990,7 @@ }, { "cell_type": "markdown", - "id": "452d0656", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Voting and Bagging" ] @@ -2401,10 +1998,8 @@ { "cell_type": "code", "execution_count": 29, - "id": "de6fd29b", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2431,10 +2026,8 @@ { "cell_type": "code", "execution_count": 30, - "id": "37edc304", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2449,10 +2042,8 @@ { "cell_type": "code", "execution_count": 31, - "id": "e1f00841", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2469,10 +2060,8 @@ { "cell_type": "code", "execution_count": 32, - "id": "08dced6b", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2486,10 +2075,7 @@ }, { "cell_type": "markdown", - "id": "0ed0228e", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Random forests\n", "\n", @@ -2509,10 +2095,7 @@ }, { "cell_type": "markdown", - "id": "bc05ef74", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "m\\approx \\sqrt{p}.\n", @@ -2521,10 +2104,7 @@ }, { "cell_type": "markdown", - "id": "ffb4b144", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "In building a random forest, at\n", "each split in the tree, the algorithm is not even allowed to consider\n", @@ -2541,16 +2121,9 @@ "lead to as large of a reduction in variance as averaging many\n", "uncorrelated quantities. In particular, this means that bagging will\n", "not lead to a substantial reduction in variance over a single tree in\n", - "this setting." - ] - }, - { - "cell_type": "markdown", - "id": "c75cd923", - "metadata": { - "editable": true - }, - "source": [ + "this setting.\n", + "\n", + "\n", "## Random Forest Algorithm\n", "The algorithm described here can be applied to both classification and regression problems.\n", "\n", @@ -2567,26 +2140,18 @@ "\n", "3. split the node into daughter nodes\n", "\n", - "4. Output then the ensemble of trees $\\{T_b\\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem." - ] - }, - { - "cell_type": "markdown", - "id": "2e732ead", - "metadata": { - "editable": true - }, - "source": [ + "\n", + "\n", + "4. Output then the ensemble of trees $\\{T_b\\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem. \n", + "\n", "## Random Forests Compared with other Methods on the Cancer Data" ] }, { "cell_type": "code", "execution_count": 33, - "id": "befbdbd7", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2660,10 +2225,7 @@ }, { "cell_type": "markdown", - "id": "9173c1f7", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "Recall that the cumulative gains curve shows the percentage of the\n", "overall number of cases in a given category *gained* by targeting a\n", @@ -2671,26 +2233,17 @@ "\n", "Similarly, the receiver operating characteristic curve, or ROC curve,\n", "displays the diagnostic ability of a binary classifier system as its\n", - "discrimination threshold is varied. It plots the true positive rate against the false positive rate." - ] - }, - { - "cell_type": "markdown", - "id": "9cb41a55", - "metadata": { - "editable": true - }, - "source": [ + "discrimination threshold is varied. It plots the true positive rate against the false positive rate.\n", + "\n", + "\n", "## Compare Bagging on Trees with Random Forests" ] }, { "cell_type": "code", "execution_count": 34, - "id": "d83311e2", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2702,10 +2255,8 @@ { "cell_type": "code", "execution_count": 35, - "id": "8cd7ddc3", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2720,10 +2271,7 @@ }, { "cell_type": "markdown", - "id": "27c06676", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Boosting, a Bird's Eye View\n", "\n", @@ -2735,16 +2283,9 @@ "This is done by applying in an iterative way a weak (or a standard\n", "classifier like decision trees) to modify the data. In each iteration\n", "we emphasize those observations which are misclassified by weighting\n", - "them with a factor." - ] - }, - { - "cell_type": "markdown", - "id": "42ba5198", - "metadata": { - "editable": true - }, - "source": [ + "them with a factor.\n", + "\n", + "\n", "## What is boosting? Additive Modelling/Iterative Fitting\n", "\n", "Boosting is a way of fitting an additive expansion in a set of\n", @@ -2754,10 +2295,7 @@ }, { "cell_type": "markdown", - "id": "7d10fac1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", @@ -2766,10 +2304,7 @@ }, { "cell_type": "markdown", - "id": "9e3039f9", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $\\beta_m$ are the expansion parameters to be determined in a\n", "minimization process and $b(x;\\gamma_m)$ are some simple functions of\n", @@ -2783,10 +2318,7 @@ }, { "cell_type": "markdown", - "id": "afc02aa3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n", @@ -2795,10 +2327,7 @@ }, { "cell_type": "markdown", - "id": "a614ac0d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where $t=\\gamma_0+\\gamma_1 x$ and the parameters $\\gamma_0$ and\n", "$\\gamma_1$ were determined by the Logistic Regression fitting\n", @@ -2809,10 +2338,7 @@ }, { "cell_type": "markdown", - "id": "a8df1b75", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -2821,10 +2347,7 @@ }, { "cell_type": "markdown", - "id": "f5fc30cf", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "In this case the function $f(x)$ was replaced by the design matrix\n", "$\\boldsymbol{X}$ and the unknown linear regression parameters $\\boldsymbol{\\beta}$,\n", @@ -2834,10 +2357,7 @@ }, { "cell_type": "markdown", - "id": "c7fe95ae", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", @@ -2846,21 +2366,11 @@ }, { "cell_type": "markdown", - "id": "2c6f0083", - "metadata": { - "editable": true - }, - "source": [ - "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$." - ] - }, - { - "cell_type": "markdown", - "id": "b73d8c2d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ + "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$.\n", + "\n", + "\n", "## Iterative Fitting, Regression and Squared-error Cost Function\n", "\n", "The way we proceed is as follows (here we specialize to the squared-error cost function)\n", @@ -2877,18 +2387,12 @@ "\n", "c. Determine then the new values $f_m(x)=f_{m-1}(x) +\\beta_m b(x;\\gamma_m)$\n", "\n", + "\n", "We could use any of the algorithms we have discussed till now. If we\n", "use trees, $\\gamma$ parameterizes the split variables and split points\n", - "at the internal nodes, and the predictions at the terminal nodes." - ] - }, - { - "cell_type": "markdown", - "id": "5c6f971b", - "metadata": { - "editable": true - }, - "source": [ + "at the internal nodes, and the predictions at the terminal nodes.\n", + "\n", + "\n", "## Squared-Error Example and Iterative Fitting\n", "\n", "To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.\n", @@ -2900,10 +2404,7 @@ }, { "cell_type": "markdown", - "id": "e0ed27b3", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(\\beta_m,\\gamma_m) = \\mathrm{argmin}_{\\beta,\\lambda}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2=\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta(1+\\gamma x_i))^2.\n", @@ -2912,10 +2413,7 @@ }, { "cell_type": "markdown", - "id": "fc9f5f4f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We start our iteration by simply setting $f_0(x)=0$. \n", "Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain" @@ -2923,10 +2421,7 @@ }, { "cell_type": "markdown", - "id": "02c2ec22", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n", @@ -2935,20 +2430,14 @@ }, { "cell_type": "markdown", - "id": "e2288bd2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", - "id": "98153a85", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n", @@ -2957,20 +2446,14 @@ }, { "cell_type": "markdown", - "id": "c39e24a0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We can then rewrite these equations as (defining $\\boldsymbol{w}=\\boldsymbol{e}+\\gamma \\boldsymbol{x})$ with $\\boldsymbol{e}$ being the unit vector)" ] }, { "cell_type": "markdown", - "id": "afdfb641", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n", @@ -2979,20 +2462,14 @@ }, { "cell_type": "markdown", - "id": "3039d39b", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have" ] }, { "cell_type": "markdown", - "id": "2ce0aa48", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n", @@ -3001,25 +2478,16 @@ }, { "cell_type": "markdown", - "id": "119b9640", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which leads to $\\gamma =(\\boldsymbol{x}^T\\boldsymbol{y}-\\beta\\boldsymbol{x}^T\\boldsymbol{e})/(\\beta\\boldsymbol{x}^T\\boldsymbol{x})$. Inserting\n", "for $\\beta$ gives us an equation for $\\gamma$. This is a non-linear equation in the unknown $\\gamma$ and has to be solved numerically. \n", "\n", "The solution to these two equations gives us in turn $\\beta_1$ and $\\gamma_1$ leading to the new expression for $f_1(x)$ as\n", - "$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$." - ] - }, - { - "cell_type": "markdown", - "id": "419822da", - "metadata": { - "editable": true - }, - "source": [ + "$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$. \n", + "\n", + "\n", + "\n", "## Iterative Fitting, Classification and AdaBoost\n", "\n", "Let us consider a binary classification problem with two outcomes $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n", @@ -3031,10 +2499,7 @@ }, { "cell_type": "markdown", - "id": "1430356a", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n", @@ -3043,10 +2508,7 @@ }, { "cell_type": "markdown", - "id": "c3a81493", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The iterative procedure starts with defining a weak classifier whose\n", "error rate is barely better than random guessing. The iterative\n", @@ -3059,10 +2521,7 @@ }, { "cell_type": "markdown", - "id": "190028df", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", @@ -3071,20 +2530,14 @@ }, { "cell_type": "markdown", - "id": "bbbca2ac", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "will be a function of" ] }, { "cell_type": "markdown", - "id": "7aee5d30", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n", @@ -3093,10 +2546,7 @@ }, { "cell_type": "markdown", - "id": "16cc7ab6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Adaptive Boosting, AdaBoost\n", "\n", @@ -3105,10 +2555,7 @@ }, { "cell_type": "markdown", - "id": "0e525c09", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n", @@ -3117,10 +2564,7 @@ }, { "cell_type": "markdown", - "id": "df0326b4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the\n", "exponential cost/loss function defined as" @@ -3128,10 +2572,7 @@ }, { "cell_type": "markdown", - "id": "07d19584", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}\\exp{(-y_i(f_{m-1}(x_i)+\\beta G(x_i))}.\n", @@ -3140,10 +2581,7 @@ }, { "cell_type": "markdown", - "id": "76774593", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We optimize $\\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.\n", "This is normally done in two steps. Let us however first rewrite the cost function as" @@ -3151,10 +2589,7 @@ }, { "cell_type": "markdown", - "id": "bb66a839", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n", @@ -3163,21 +2598,10 @@ }, { "cell_type": "markdown", - "id": "bcd0b507", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$." - ] - }, - { - "cell_type": "markdown", - "id": "0c203949", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ + "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$.\n", + "\n", "## Building up AdaBoost\n", "\n", "First, for any $\\beta > 0$, we optimize $G$ by setting" @@ -3185,10 +2609,7 @@ }, { "cell_type": "markdown", - "id": "415377f0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n", @@ -3197,10 +2618,7 @@ }, { "cell_type": "markdown", - "id": "daaca279", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which is the classifier that minimizes the weighted error rate in predicting $y$.\n", "\n", @@ -3209,10 +2627,7 @@ }, { "cell_type": "markdown", - "id": "f7bfba93", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\exp{-(\\beta)}\\sum_{y_i=G(x_i)}w_i^m+\\exp{(\\beta)}\\sum_{y_i\\ne G(x_i)}w_i^m,\n", @@ -3221,20 +2636,14 @@ }, { "cell_type": "markdown", - "id": "4f6a2f84", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which can be rewritten as" ] }, { "cell_type": "markdown", - "id": "6858be89", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(\\exp{(\\beta)}-\\exp{-(\\beta)})\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i))+\\exp{(-\\beta)}\\sum_{i=0}^{n-1}w_i^m=0,\n", @@ -3243,20 +2652,14 @@ }, { "cell_type": "markdown", - "id": "eecfcfb5", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which leads to" ] }, { "cell_type": "markdown", - "id": "cd73a579", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n", @@ -3265,20 +2668,14 @@ }, { "cell_type": "markdown", - "id": "33302d95", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "where we have redefined the error as" ] }, { "cell_type": "markdown", - "id": "ce21db0f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathrm{\\overline{err}}_m=\\frac{1}{n}\\frac{\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i)}{\\sum_{i=0}^{n-1}w_i^m},\n", @@ -3287,20 +2684,14 @@ }, { "cell_type": "markdown", - "id": "1fd9965f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "which leads to an update of" ] }, { "cell_type": "markdown", - "id": "2a092b92", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n", @@ -3309,20 +2700,14 @@ }, { "cell_type": "markdown", - "id": "1553ca38", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "This leads to the new weights" ] }, { "cell_type": "markdown", - "id": "60bd5373", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n", @@ -3331,10 +2716,7 @@ }, { "cell_type": "markdown", - "id": "eace9c52", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Adaptive boosting: AdaBoost, Basic Algorithm\n", "\n", @@ -3351,10 +2733,7 @@ }, { "cell_type": "markdown", - "id": "8cb0caec", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n", @@ -3363,21 +2742,10 @@ }, { "cell_type": "markdown", - "id": "4545fb70", - "metadata": { - "editable": true - }, - "source": [ - "where the function $I()$ is one if we misclassify and zero if we classify correctly." - ] - }, - { - "cell_type": "markdown", - "id": "c8c0b69c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ + "where the function $I()$ is one if we misclassify and zero if we classify correctly. \n", + "\n", "## Basic Steps of AdaBoost\n", "\n", "With the above definitions we are now ready to set up the algorithm for AdaBoost.\n", @@ -3389,10 +2757,7 @@ }, { "cell_type": "markdown", - "id": "9a715091", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "\\mathrm{\\overline{err}}_m=\\frac{\\sum_{i=0}^{n-1}w_i^m I(y_i\\ne G(x_i))}{\\sum_{i=0}^{n-1}w_i},\n", @@ -3401,10 +2766,7 @@ }, { "cell_type": "markdown", - "id": "ebec62af", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "1. Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.\n", "\n", @@ -3416,6 +2778,7 @@ "\n", "d. Set the new weights to $w_i = w_i\\times \\exp{(\\alpha_m I(y_i\\ne G(x_i)}$.\n", "\n", + "\n", "5. Compute the new classifier $G(x)= \\sum_{i=0}^{n-1}\\alpha_m I(y_i\\ne G(x_i)$.\n", "\n", "For the iterations with $m \\le 2$ the weights are modified\n", @@ -3424,16 +2787,10 @@ "classified properly. As this proceeds, the observations which were\n", "difficult to classifiy correctly are given a larger influence. Each\n", "new classification step $m$ is then forced to concentrate on those\n", - "observations that are missed in the previous iterations." - ] - }, - { - "cell_type": "markdown", - "id": "6df3a47f", - "metadata": { - "editable": true - }, - "source": [ + "observations that are missed in the previous iterations.\n", + "\n", + "\n", + "\n", "## AdaBoost Examples\n", "\n", "Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here." @@ -3442,10 +2799,8 @@ { "cell_type": "code", "execution_count": 36, - "id": "a762adfc", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3474,10 +2829,7 @@ }, { "cell_type": "markdown", - "id": "38d12d89", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent\n", "\n", @@ -3487,16 +2839,8 @@ "\n", "In order to understand the method, let us illustrate its basics by\n", "bringing back the essential steps in linear regression, where our cost\n", - "function was the least squares function." - ] - }, - { - "cell_type": "markdown", - "id": "1b792064", - "metadata": { - "editable": true - }, - "source": [ + "function was the least squares function.\n", + "\n", "## The Squared-Error again! Steepest Descent\n", "\n", "We start again with our cost function ${\\cal C}(\\boldsymbol{y}m\\boldsymbol{f})=\\sum_{i=0}^{n-1}{\\cal L}(y_i, f(x_i))$ where we want to minimize\n", @@ -3505,10 +2849,7 @@ }, { "cell_type": "markdown", - "id": "beaf036c", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(\\hat{\\boldsymbol{f}}) = \\mathrm{argmin}_{\\boldsymbol{f}}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -3517,20 +2858,14 @@ }, { "cell_type": "markdown", - "id": "702b65a0", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as" ] }, { "cell_type": "markdown", - "id": "2652a1da", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f_M(x) = \\sum_{m=0}^M h_m(x).\n", @@ -3539,20 +2874,14 @@ }, { "cell_type": "markdown", - "id": "be287ca2", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "In the steepest decent approach we approximate $h_m(x) = -\\rho_m g_m(x)$, where $\\rho_m$ is a scalar and $g_m(x)$ the gradient defined as" ] }, { "cell_type": "markdown", - "id": "ff3901b6", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "g_m(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{m-1}(x_i)}.\n", @@ -3561,10 +2890,7 @@ }, { "cell_type": "markdown", - "id": "5228f5fd", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "With the new gradient we can update $f_m(x) = f_{m-1}(x) -\\rho_m g_m(x)$. Using the above squared-error function we see that\n", "the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.\n", @@ -3574,10 +2900,7 @@ }, { "cell_type": "markdown", - "id": "1e30448f", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "(\\rho_1) = \\mathrm{argmin}_{\\rho}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i+2\\rho y_i)^2.\n", @@ -3586,10 +2909,7 @@ }, { "cell_type": "markdown", - "id": "5bd43cc1", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Steepest Descent Example\n", "\n", @@ -3598,10 +2918,7 @@ }, { "cell_type": "markdown", - "id": "acaae452", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n", @@ -3610,20 +2927,14 @@ }, { "cell_type": "markdown", - "id": "022645ac", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "We can then proceed and compute" ] }, { "cell_type": "markdown", - "id": "8e6bbfb4", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "g_2(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,\n", @@ -3632,21 +2943,10 @@ }, { "cell_type": "markdown", - "id": "66ce0709", - "metadata": { - "editable": true - }, - "source": [ - "and find a new value for $\\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called **gradient boosting**." - ] - }, - { - "cell_type": "markdown", - "id": "8ac79309", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ + "and find a new value for $\\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called **gradient boosting**. \n", + "\n", "## Gradient Boosting, algorithm\n", "\n", "Steepest descent is however not much used, since it only optimizes $f$ at a fixed set of $n$ points,\n", @@ -3658,10 +2958,7 @@ }, { "cell_type": "markdown", - "id": "d562f162", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -3670,10 +2967,7 @@ }, { "cell_type": "markdown", - "id": "9e609544", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "The way we proceed in an iterative fashion is to\n", "1. Initialize our estimate $f_0(x)$.\n", @@ -3686,26 +2980,17 @@ "\n", "c. update the estimate $f_m(x) = f_{m-1}(x)+h_m(u_m,x)$;\n", "\n", - "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$." - ] - }, - { - "cell_type": "markdown", - "id": "eced6bdc", - "metadata": { - "editable": true - }, - "source": [ + "\n", + "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$.\n", + "\n", "## Gradient Boosting, Examples of Regression" ] }, { "cell_type": "code", "execution_count": 37, - "id": "613e05cd", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3759,10 +3044,7 @@ }, { "cell_type": "markdown", - "id": "77c76d85", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Gradient Boosting, Classification Example" ] @@ -3770,10 +3052,8 @@ { "cell_type": "code", "execution_count": 38, - "id": "af5a3843", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3821,13 +3101,11 @@ }, { "cell_type": "markdown", - "id": "0ca37c1d", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## XGBoost: Extreme Gradient Boosting\n", "\n", + "\n", "[XGBoost](https://github.com/dmlc/xgboost) or Extreme Gradient\n", "Boosting, is an optimized distributed gradient boosting library\n", "designed to be highly efficient, flexible and portable. It implements\n", @@ -3839,26 +3117,16 @@ "boosting system. It has a theoretically justified weighted quantile\n", "sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.\n", "\n", - "It is now the algorithm which wins essentially all ML competitions!!!" - ] - }, - { - "cell_type": "markdown", - "id": "b2dd3360", - "metadata": { - "editable": true - }, - "source": [ + "It is now the algorithm which wins essentially all ML competitions!!!\n", + "\n", "## Regression Case" ] }, { "cell_type": "code", "execution_count": 39, - "id": "4bf9f894", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3912,10 +3180,7 @@ }, { "cell_type": "markdown", - "id": "00b1f1af", - "metadata": { - "editable": true - }, + "metadata": {}, "source": [ "## Xgboost on the Cancer Data\n", "\n", @@ -3925,10 +3190,8 @@ { "cell_type": "code", "execution_count": 40, - "id": "4454900b", "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3989,5 +3252,5 @@ ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 5 + "nbformat_minor": 4 } diff --git a/doc/src/week45/week45.do.txt b/doc/src/week45/week45.do.txt index f7dc247d1..3bc775cc3 100644 --- a/doc/src/week45/week45.do.txt +++ b/doc/src/week45/week45.do.txt @@ -412,7 +412,7 @@ 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). +p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). \] !et @@ -422,7 +422,7 @@ $m$. The three most common ways of splitting a node are given by * Misclassification error !bt \[ -p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +\frac{1}{N_m}\sum_{i\in R_m}I(y_i\ne k) = 1-p_{mk}. \] !et * Gini index $g$