diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index 252635078..025808c71 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 + - + + + @@ -279,6 +239,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 -
+ +
[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

+<<<<<<< HEAD

Nov 11, 2021

+======= +

+

Nov 10, 2021

+>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
- +

Read »

@@ -424,22 +470,33 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • +<<<<<<< HEAD
  • 77
  • +======= +
  • 71
  • +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
  • »
  • +
    + + +
    © 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 8f732d65e..9714977be 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 + - + + + @@ -279,6 +239,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.
    @@ -408,6 +453,7 @@ MathJax.Hub.Config({
    +

      @@ -424,22 +470,33 @@ MathJax.Hub.Config({
    • 10
    • 11
    • ...
    • +<<<<<<< HEAD
    • 77
    • +======= +
    • 71
    • +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    • »
    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs002.html b/doc/pub/week45/html/._week45-bs002.html index feb9df8a6..55e0efce5 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 + - + + + @@ -279,6 +239,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 7a7c2ff35..bd97f4cee 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 + - + + + @@ -279,6 +239,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 18a10b3a4..b368a0c9f 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 + - + + + @@ -279,6 +239,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 3afd7dc2a..5daa7cca4 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 + - + + + @@ -279,6 +239,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 7ee1c26a4..86a109cb9 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 + - + + + @@ -279,6 +239,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 6ab60427f..cfd6b1430 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 + - + + + @@ -279,6 +239,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 7a7ecd6b9..99f3b7004 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 + - + + + @@ -279,6 +239,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. @@ -393,8 +433,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 484578e8e..3987087f8 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 + - + + + @@ -279,6 +239,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
    @@ -477,22 +513,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 febd641a5..05be07a7d 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 + - + + + @@ -279,6 +239,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 2482df322..6df2274d9 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 + - + + + @@ -279,6 +239,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 bfab7f82a..ab52d4564 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 + - + + + @@ -279,6 +239,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 @@ -427,8 +468,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 179f46072..83d60b029 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 + - + + + @@ -279,6 +239,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 74a90546d..4f21438c7 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 + - + + + @@ -279,6 +239,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 322d67bee..327feeff7 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 + - + + + @@ -279,6 +239,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 40dab185a..7e6eda7a1 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 + - + + + @@ -279,6 +239,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 @@ -394,9 +435,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 fdb751808..05910ef25 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 + - + + + @@ -279,6 +239,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 @@ -393,15 +434,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 9d40d1b5b..94ddb34de 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 + - + + + @@ -279,6 +239,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\ne k'} p_{mk}p_{mk'}=\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 59c975c7d..62e45965e 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Gini Index?Coefficient/Impurity

    The Gini index \( g \) gives us the degree of probability of a specific @@ -395,6 +435,48 @@ variable that is wrongly classified.

    It favors binary splitting.

    +======= + +

    Visualizing the Tree, Classification

    +

    + + +

    import os
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.model_selection import train_test_split
    +from sklearn.metrics import confusion_matrix
    +from sklearn.tree import export_graphviz
    +
    +from IPython.display import Image 
    +from pydot import graph_from_dot_data
    +import pandas as pd
    +import numpy as np
    +
    +
    +cancer = load_breast_cancer()
    +X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
    +print(X)
    +y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
    +y = pd.get_dummies(y)
    +print(y)
    +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
    +tree_clf = DecisionTreeClassifier(max_depth=5)
    +tree_clf.fit(X_train, y_train)
    +
    +export_graphviz(
    +    tree_clf,
    +    out_file="DataFiles/cancer.dot",
    +    feature_names=cancer.feature_names,
    +    class_names=cancer.target_names,
    +    rounded=True,
    +    filled=True
    +)
    +cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
    +os.system(cmd)
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs020.html b/doc/pub/week45/html/._week45-bs020.html index c912487ea..acf9a1933 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Why binary split?

    It is custom to split to a tree uising binary splits. The reason is @@ -389,6 +429,39 @@ insufficient data at the next level down. Multiway splits can be achieved by a series of binary split and this is normally preferred.

    +======= + +

    Visualizing the Tree, The Moons

    +

    + + +

    # Common imports
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.datasets import make_moons
    +from sklearn.tree import export_graphviz
    +from pydot import graph_from_dot_data
    +import pandas as pd
    +import os
    +
    +np.random.seed(42)
    +X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
    +X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
    +tree_clf = DecisionTreeClassifier(max_depth=5)
    +tree_clf.fit(X_train, y_train)
    +
    +export_graphviz(
    +    tree_clf,
    +    out_file="DataFiles/moons.dot",
    +    rounded=True,
    +    filled=True
    +)
    +cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
    +os.system(cmd)
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs021.html b/doc/pub/week45/html/._week45-bs021.html index 2b38a20ae..93d8b0346 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Visualizing the Tree, Classification

    @@ -438,6 +478,26 @@ 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. + +

    + + +

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

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs022.html b/doc/pub/week45/html/._week45-bs022.html index c6ac2761b..10fa81d06 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Visualizing the Tree, The Moons

    @@ -429,6 +469,28 @@ os.system(cmd)
    +======= + +

    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.tree import DecisionTreeClassifier
    +from sklearn.tree import export_text
    +iris = load_iris()
    +decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
    +decision_tree = decision_tree.fit(iris.data, iris.target)
    +r = export_text(decision_tree, feature_names=iris['feature_names'])
    +print(r)
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs023.html b/doc/pub/week45/html/._week45-bs023.html index 75091d0f8..f17c7414a 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    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.

    @@ -414,7 +454,25 @@ tree.plot_tree(tree_clf)
    +======= +

    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. +
    3. The ID3 algorithm based on the computation of the information gain for classification
    4. +
    + +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. +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs024.html b/doc/pub/week45/html/._week45-bs024.html index 1452ac0c3..e6ab404e9 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Printing out as text

    Alternatively, the tree can also be exported in textual format with the function exporttext. @@ -417,7 +457,34 @@ r = export_text(decision_tree, feature_names

    +======= +

    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? +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}} \) + 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 +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 \). +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs025.html b/doc/pub/week45/html/._week45-bs025.html index df8806f75..c1d481348 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Algorithms for Setting up Decision Trees

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

    @@ -393,7 +433,35 @@ MathJax.Hub.Config({ you can use either the gini index or the entropy to split a tree in two branches.

    +======= +

    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 +$$ +\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, +$$ + +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. + +

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

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs026.html b/doc/pub/week45/html/._week45-bs026.html index bbb597ea1..30843ee64 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    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 \). @@ -406,6 +446,52 @@ hyperparameters control additional stopping conditions such as the \( min\_sampl \( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \).

    +======= + +

    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 +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +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 + +

    +
    + + + + + + + + + + + + + + + + + + + + +
    Day Outlook Temperature Humidity Wind Ride
    1 Sunny Hot High Weak 0
    2 Sunny Hot High Strong 1
    3 Overcast Hot High Weak 1
    4 Rain Mild High Weak 1
    5 Rain Cool Normal Weak 1
    6 Rain Cool Normal Strong 0
    7 Overcast Cool Normal Strong 1
    8 Sunny Mild High Weak 0
    9 Sunny Cool Normal Weak 1
    10 Rain Mild Normal Weak 1
    11 Sunny Mild Normal Strong 1
    12 Overcast Mild High Strong 1
    13 Overcast Hot Normal Weak 1
    14 Rain Mild High Strong 0
    +
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs027.html b/doc/pub/week45/html/._week45-bs027.html index 60f071db6..1b43019c9 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    The CART algorithm for Regression

    +======= + +

    Simple Python Code to read in Data and perform Classification

    + +

    + + +

    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.model_selection import train_test_split
    +from sklearn.tree import export_graphviz
    +from sklearn.preprocessing import StandardScaler, OneHotEncoder
    +from sklearn.compose import ColumnTransformer
    +from IPython.display import Image 
    +from pydot import graph_from_dot_data
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
     
     

    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 @@ -400,12 +474,48 @@ $$ \overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, $$ +<<<<<<< HEAD

    the mean value of all observations in a specific node.

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

    +======= +infile = open(data_path("rideclass.csv"),'r') + +# Read the experimental data with Pandas +from IPython.display import display +ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride')) +ridedata = pd.DataFrame(ridedata) + +# Features and targets +X = ridedata.loc[:, ridedata.columns != 'Ride'].values +y = ridedata.loc[:, ridedata.columns == 'Ride'].values + +# Create the encoder. +encoder = OneHotEncoder(handle_unknown="ignore") +# Assume for simplicity all features are categorical. +encoder.fit(X) +# Apply the encoder. +X = encoder.transform(X) +print(X) +# Then do a Classification tree +tree_clf = DecisionTreeClassifier(max_depth=2) +tree_clf.fit(X, y) +print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y))) +#transfer to a decision tree graph +export_graphviz( + tree_clf, + out_file="DataFiles/ride.dot", + rounded=True, + filled=True +) +cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png' +os.system(cmd) +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs028.html b/doc/pub/week45/html/._week45-bs028.html index c776bb855..5e03fe109 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Computing the Gini index

    The example we will look at is a classical one in many Machine @@ -422,6 +462,85 @@ humidity and weak and strong for wind.

    +======= + +

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

    + + +

    # 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:
    +		if row[index] < value:
    +			left.append(row)
    +		else:
    +			right.append(row)
    +	return left, right
    + 
    +# Calculate the Gini index for a split dataset
    +def gini_index(groups, classes):
    +	# count all samples at split point
    +	n_instances = float(sum([len(group) for group in groups]))
    +	# sum weighted Gini index for each group
    +	gini = 0.0
    +	for group in groups:
    +		size = float(len(group))
    +		# avoid divide by zero
    +		if size == 0:
    +			continue
    +		score = 0.0
    +		# score the group based on the score for each class
    +		for class_val in classes:
    +			p = [row[-1] for row in group].count(class_val) / size
    +			score += p * p
    +		# weight the group score by its relative size
    +		gini += (1.0 - score) * (size / n_instances)
    +	return gini
    +
    +# Select the best split point for a dataset
    +def get_split(dataset):
    +	class_values = list(set(row[-1] for row in dataset))
    +	b_index, b_value, b_score, b_groups = 999, 999, 999, None
    +	for index in range(len(dataset[0])-1):
    +		for row in dataset:
    +			groups = test_split(index, row[index], dataset)
    +			gini = gini_index(groups, class_values)
    +			print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
    +			if gini < b_score:
    +				b_index, b_value, b_score, b_groups = index, row[index], gini, groups
    +	return {'index':b_index, 'value':b_value, 'groups':b_groups}
    + 
    +dataset = [[0,0,0,0,0],
    +            [0,0,0,1,1],
    +            [1,0,0,0,1],
    +            [2,1,0,0,1],
    +            [2,2,1,0,1],
    +            [2,2,1,1,0],
    +            [1,2,1,1,1],
    +            [0,1,0,0,0],
    +            [0,2,1,0,1],
    +            [2,1,1,0,1],
    +            [0,1,1,1,1],
    +            [1,1,0,1,1],
    +            [1,0,1,0,1],
    +            [2,1,0,1,0]]
    +
    +split = get_split(dataset)
    +print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs029.html b/doc/pub/week45/html/._week45-bs029.html index b97e9d93e..8ae00d502 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Simple Python Code to read in Data and perform Classification

    @@ -472,7 +512,43 @@ os.system(cmd)
    +======= +

    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. +
    3. The best attribute is selected and used as the test at the root node of the tree.
    4. +
    5. A descendant of the root node is then created for each possible value of this attribute.
    6. +
    7. Training examples are sorted to the appropriate descendant node.
    8. +
    9. 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.
    10. +
    11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
    12. +
    + +The ID3 algorithm selects which attribute to test at each node in the +tree. + +

    +We would like to select the attribute that is most useful for classifying +examples. + +

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

    +Information gain measures how well a given attribute separates the +training examples according to their target classification. + +

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

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs030.html b/doc/pub/week45/html/._week45-bs030.html index 783a0e2f2..8b1798617 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Computing the Gini Factor

    The above functions (gini, entropy and misclassification error) are @@ -427,6 +467,20 @@ algorithm ID3. # weight the group score by its relative size gini += (1.0 - score) * (size / n_instances) return gini +======= + +

    Cancer Data again now with Decision Trees and other Methods

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.svm import SVC
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.tree import DecisionTreeClassifier
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
     
     # Select the best split point for a dataset
     def get_split(dataset):
    @@ -456,6 +510,7 @@ dataset = [[01,0,1,0,1],
                 [2,1,0,1,0]]
     
    +<<<<<<< HEAD
     split = get_split(dataset)
     print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
     
    @@ -474,6 +529,40 @@ split = get_split(dataset)
    +======= +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) +print(X_train.shape) +print(X_test.shape) +# Logistic Regression +logreg = LogisticRegression(solver='lbfgs') +logreg.fit(X_train, y_train) +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) +# Support vector machine +svm = SVC(gamma='auto', C=100) +svm.fit(X_train, y_train) +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) +# Decision Trees +deep_tree_clf = DecisionTreeClassifier(max_depth=None) +deep_tree_clf.fit(X_train, y_train) +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) +#now scale the data +from sklearn.preprocessing import StandardScaler +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) +# Logistic Regression +logreg.fit(X_train_scaled, y_train) +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +# Support Vector Machine +svm.fit(X_train_scaled, y_train) +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +# Decision Trees +deep_tree_clf.fit(X_train_scaled, y_train) +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs031.html b/doc/pub/week45/html/._week45-bs031.html index 4a1c53669..db0865921 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Entropy and the ID3 algorithm

    +======= + +

    Another example, the moons again

    +

    + + +

    from __future__ import division, print_function, unicode_literals
    +
    +# Common imports
    +import numpy as np
    +import os
    +
    +# to make this notebook's output stable across runs
    +np.random.seed(42)
    +
    +# To plot pretty figures
    +import matplotlib
    +import matplotlib.pyplot as plt
    +from matplotlib.colors import ListedColormap
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
     
     

    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? @@ -409,10 +472,47 @@ examples. training examples according to their target classification.

    +<<<<<<< HEAD

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

    +======= +def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True): + x1s = np.linspace(axes[0], axes[1], 100) + x2s = np.linspace(axes[2], axes[3], 100) + x1, x2 = np.meshgrid(x1s, x2s) + X_new = np.c_[x1.ravel(), x2.ravel()] + y_pred = clf.predict(X_new).reshape(x1.shape) + custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) + plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) + if not iris: + custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) + plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) + if plot_training: + plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa") + plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor") + plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica") + plt.axis(axes) + if iris: + plt.xlabel("Petal length", fontsize=14) + plt.ylabel("Petal width", fontsize=14) + else: + plt.xlabel(r"$x_1$", fontsize=18) + plt.ylabel(r"$x_2$", fontsize=18, rotation=0) + if legend: + plt.legend(loc="lower right", fontsize=14) +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False) +plt.title("No restrictions", fontsize=16) +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() +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs032.html b/doc/pub/week45/html/._week45-bs032.html index 7107b4fb7..3ace1cc84 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Cancer Data again now with Decision Trees and other Methods

    @@ -396,10 +436,30 @@ MathJax.Hub.Config({ from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier +======= + +

    Playing around with regions

    +

    + + +

    np.random.seed(6)
    +Xs = np.random.rand(100, 2) - 0.5
    +ys = (Xs[:, 0] > 0).astype(np.float32) * 2
    +
    +angle = np.pi/4
    +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
    +Xsr = Xs.dot(rotation_matrix)
    +
    +tree_clf_s = DecisionTreeClassifier(random_state=42)
    +tree_clf_s.fit(Xs, ys)
    +tree_clf_sr = DecisionTreeClassifier(random_state=42)
    +tree_clf_sr.fit(Xsr, ys)
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
     
     # Load the data
     cancer = load_breast_cancer()
     
    +<<<<<<< HEAD
     X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
     print(X_train.shape)
     print(X_test.shape)
    @@ -446,6 +506,11 @@ deep_tree_clf.fit(X_train_scaled, y_train)
     
    +======= +plt.show() +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs033.html b/doc/pub/week45/html/._week45-bs033.html index fc73c7e5e..1b9e1dee0 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Another example, the moons again

    @@ -469,6 +509,29 @@ plt.show()
    +======= + +

    Regression trees

    +

    + + +

    # 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
    +
    +tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg.fit(X, y)
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs034.html b/doc/pub/week45/html/._week45-bs034.html index 7b61702f2..2b413cc86 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Playing around with regions

    @@ -392,6 +432,14 @@ MathJax.Hub.Config({
    np.random.seed(6)
     Xs = np.random.rand(100, 2) - 0.5
     ys = (Xs[:, 0] > 0).astype(np.float32) * 2
    +=======
    +
    +

    Final regressor code

    +

    + + +

    from sklearn.tree import DecisionTreeRegressor
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
     
     angle = np.pi/4
     rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
    @@ -404,27 +452,59 @@ tree_clf_sr.fit(Xsr, ys)
     
     plt.figure(figsize=(11, 4))
     plt.subplot(121)
    +<<<<<<< HEAD
     plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    +=======
    +plot_regression_predictions(tree_reg1, X, y)
    +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    +    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
    +plt.text(0.21, 0.65, "Depth=0", fontsize=15)
    +plt.text(0.01, 0.2, "Depth=1", fontsize=13)
    +plt.text(0.65, 0.8, "Depth=1", fontsize=13)
    +plt.legend(loc="upper center", fontsize=18)
    +plt.title("max_depth=2", fontsize=14)
    +
    +plt.subplot(122)
    +plot_regression_predictions(tree_reg2, X, y, ylabel=None)
    +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    +    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
    +for split in (0.0458, 0.1298, 0.2873, 0.9040):
    +    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
    +plt.text(0.3, 0.5, "Depth=2", fontsize=13)
    +plt.title("max_depth=3", fontsize=14)
    +
    +plt.show()
    +
    +

    + + +

    tree_reg1 = DecisionTreeRegressor(random_state=42)
    +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
    +tree_reg1.fit(X, y)
    +tree_reg2.fit(X, y)
    +
    +x1 = np.linspace(0, 1, 500).reshape(-1, 1)
    +y_pred1 = tree_reg1.predict(x1)
    +y_pred2 = tree_reg2.predict(x1)
    +
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plt.plot(X, y, "b.")
    +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
    +plt.axis([0, 1, -0.2, 1.1])
    +plt.xlabel("$x_1$", fontsize=18)
    +plt.ylabel("$y$", fontsize=18, rotation=0)
    +plt.legend(loc="upper center", fontsize=18)
    +plt.title("No restrictions", fontsize=14)
    +
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
     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-bs035.html b/doc/pub/week45/html/._week45-bs035.html index 65a5bb826..d853ed29c 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Regression trees

    @@ -434,6 +474,21 @@ tree_reg.fit(X, y)
    +======= + +

    Pros and cons of trees, pros

    + + + +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs036.html b/doc/pub/week45/html/._week45-bs036.html index 5f16c62bb..f8d49f1d3 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Final regressor code

    @@ -489,7 +529,26 @@ plt.show()
    +======= +

    Disadvantages

    + + + +However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs037.html b/doc/pub/week45/html/._week45-bs037.html index 5b20749c2..b329c6c76 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Pros and cons of trees, pros

    +======= + +

    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 +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. +
    3. Bagging and Pasting
    4. +
    5. Random forests
    6. +
    7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
    8. +
    + +We discuss these methods here. +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs038.html b/doc/pub/week45/html/._week45-bs038.html index 159a1ae3b..db1422cee 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Disadvantages

    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs039.html b/doc/pub/week45/html/._week45-bs039.html index 43a24aefc..10f349672 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    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 @@ -395,6 +435,24 @@ 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

    +======= + +

    Bagging

    + +

    +The plain decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of \( n \) to \( p \) is moderately large. + +

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

    1. Voting classifiers
    2. @@ -404,6 +462,7 @@ try to explain here. These are

    We discuss these methods here.

    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs040.html b/doc/pub/week45/html/._week45-bs040.html index 9f4f59be1..2916cbaed 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    An Overview of Ensemble Methods



    @@ -388,7 +428,36 @@ MathJax.Hub.Config({



    +======= +

    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 +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all \( B \) possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all \( B \) trees. +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs041.html b/doc/pub/week45/html/._week45-bs041.html index e25f90088..939df4279 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Bagging

    The plain decision trees suffer from high @@ -396,7 +436,70 @@ of \( n \) to \( p \) is moderately large. general-purpose procedure for reducing the variance of a statistical learning method.

    +======= +

    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 numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.tree import DecisionTreeRegressor
    +
    +n = 1000
    +n_boostraps = 100
    +maxdepth = 10
    +
    +# Make data set.
    +x = np.linspace(-3, 3, n).reshape(-1, 1)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    +error = np.zeros(maxdepth)
    +bias = np.zeros(maxdepth)
    +variance = np.zeros(maxdepth)
    +polydegree = np.zeros(maxdepth)
    +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    +
    +# we produce a simple tree first as benchmark, no scaling
    +simpletree = DecisionTreeRegressor(max_depth=3) 
    +simpletree.fit(X_train, y_train)
    +simpleprediction = simpletree.predict(X_test)
    +for degree in range(1,maxdepth):
    +    model = DecisionTreeRegressor(max_depth=degree) 
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train, y_train)
    +        model.fit(x_, y_)
    +        y_pred[:, i] = model.predict(X_test)#.ravel()
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    + 
    +mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
    +print(mse_simpletree)
    +plt.xlim(1,maxdepth)
    +plt.plot(polydegree, error, label='MSE')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +save_fig("baggingboot")
    +plt.show()
    +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs042.html b/doc/pub/week45/html/._week45-bs042.html index fa0a4b9ea..9e46cead7 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    More bagging

    Bagging typically results in improved accuracy @@ -406,7 +446,30 @@ 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.

    +======= +

    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. +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. +In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in +each iteration. + +

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

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs043.html b/doc/pub/week45/html/._week45-bs043.html index 02cd16ab9..9b978cb41 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Simple Voting Example, head or tail

    @@ -416,8 +456,37 @@ plt.show()
    +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e +

    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 +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 +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, +clealry demostrating that after some tosses we see the law of large +numbers kicking in. + +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs044.html b/doc/pub/week45/html/._week45-bs044.html index 52e0db5c0..97a14ae63 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Using the Voting Classifier

    @@ -446,8 +486,53 @@ voting_clf.fit(X_train, y_train)
    +======= +

    Standard imports first

    +

    + + +

    # Common imports
    +from IPython.display import Image 
    +from pydot import graph_from_dot_data
    +import pandas as pd
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.model_selection import train_test_split
    +from sklearn.tree import export_graphviz
    +from sklearn.preprocessing import StandardScaler, OneHotEncoder
    +from sklearn.compose import ColumnTransformer
    +from IPython.display import Image 
    +from pydot import graph_from_dot_data
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs045.html b/doc/pub/week45/html/._week45-bs045.html index 049b79eb1..d57e44548 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Please, not the moons again! Voting and Bagging

    @@ -501,6 +541,37 @@ voting_clf.fit(X_train, y_train)
    +======= + +

    Simple Voting Example, head or tail

    +

    + + +

    # Common imports
    +import numpy as np
    +import matplotlib
    +import matplotlib.pyplot as plt
    +from matplotlib.colors import ListedColormap
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
    +
    +heads_proba = 0.51
    +coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
    +cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
    +plt.figure(figsize=(8,3.5))
    +plt.plot(cumulative_heads_ratio)
    +plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
    +plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
    +plt.xlabel("Number of coin tosses")
    +plt.ylabel("Heads ratio")
    +plt.legend(loc="lower right")
    +plt.axis([0, 10000, 0.42, 0.58])
    +save_fig("votingsimple")
    +plt.show()
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs046.html b/doc/pub/week45/html/._week45-bs046.html index 23757c40f..357ae147d 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Bagging Examples

    @@ -503,7 +543,60 @@ 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. +

    + + +

    from sklearn.model_selection import train_test_split
    +from sklearn.datasets import make_moons
    +
    +X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    +
    +from sklearn.ensemble import RandomForestClassifier
    +from sklearn.ensemble import VotingClassifier
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.svm import SVC
    +
    +log_clf = LogisticRegression(solver="liblinear", random_state=42)
    +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    +svm_clf = SVC(gamma="auto", random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='hard')
    +
    +voting_clf.fit(X_train, y_train)
    +
    +from sklearn.metrics import accuracy_score
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    +
    +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(solver="liblinear", random_state=42)
    +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    +svm_clf = SVC(gamma="auto", probability=True, random_state=42)
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='soft')
    +voting_clf.fit(X_train, y_train)
    +
    +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))
    +
    +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs047.html b/doc/pub/week45/html/._week45-bs047.html index d85cf401a..05900efd8 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    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 @@ -465,7 +505,66 @@ plt.show()

    +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e +

    Voting and Bagging

    + +

    + + +

    from sklearn.model_selection import train_test_split
    +from sklearn.datasets import make_moons
    +
    +X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    +from sklearn.ensemble import RandomForestClassifier
    +from sklearn.ensemble import VotingClassifier
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.svm import SVC
    +
    +log_clf = LogisticRegression(random_state=42)
    +rnd_clf = RandomForestClassifier(random_state=42)
    +svm_clf = SVC(random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='hard')
    +voting_clf.fit(X_train, y_train)
    +
    +

    + + +

    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)
    +rnd_clf = RandomForestClassifier(random_state=42)
    +svm_clf = SVC(probability=True, random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='soft')
    +voting_clf.fit(X_train, y_train)
    +
    +

    + + +

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

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs048.html b/doc/pub/week45/html/._week45-bs048.html index eccb05695..8002e960b 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Why Voting?

    The idea behind boosting, and voting as well can be phrased as follows: @@ -399,7 +439,51 @@ each iteration.

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

    +======= +

    Random forests

    + +

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

    +As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of \( m \) predictors is chosen as split +candidates from the full set of \( p \) predictors. The split is allowed to +use only one of those \( m \) predictors. + +

    +A fresh sample of \( m \) predictors is +taken at each split, and typically we choose + +$$ +m\approx \sqrt{p}. +$$ +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    +In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. + +

    +The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quantities. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs049.html b/doc/pub/week45/html/._week45-bs049.html index d8f8d2f90..280ad11ac 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Tossing coins

    The simplest case is a so-called voting ensemble. To illustrate this, @@ -407,6 +447,32 @@ actually win. clealry demostrating that after some tosses we see the law of large numbers kicking in.

    +======= + +

    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. + + + +
    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.
    4. +
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    @@ -433,22 +499,33 @@ numbers kicking in.

  • 58
  • 59
  • ...
  • +<<<<<<< HEAD
  • 77
  • +======= +
  • 71
  • +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
  • »
  • +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs050.html b/doc/pub/week45/html/._week45-bs050.html index 744a291f4..eed09dda2 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Standard imports first

    @@ -441,8 +481,91 @@ DATA_ID = "
    +======= + +

    Random Forests Compared with other Methods on the Cancer Data

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.svm import SVC
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.ensemble import BaggingClassifier
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +# Support vector machine
    +svm = SVC(gamma='auto', C=100)
    +svm.fit(X_train, y_train)
    +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
    +# Decision Trees
    +deep_tree_clf = DecisionTreeClassifier(max_depth=None)
    +deep_tree_clf.fit(X_train, y_train)
    +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +# Logistic Regression
    +logreg.fit(X_train_scaled, y_train)
    +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Support Vector Machine
    +svm.fit(X_train_scaled, y_train)
    +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Decision Trees
    +deep_tree_clf.fit(X_train_scaled, y_train)
    +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
     
     
    +from sklearn.ensemble import RandomForestClassifier
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +# Data set not specificied
    +#Instantiate the model with 500 trees and entropy as splitting criteria
    +Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
    +Random_Forest_model.fit(X_train_scaled, y_train)
    +#Cross validation
    +accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
    +print(accuracy)
    +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
    +
    +
    +import scikitplot as skplt
    +y_pred = Random_Forest_model.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = Random_Forest_model.predict_proba(X_test_scaled)
    +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 +overall number of cases in a given category gained by targeting a +percentage of the total number of cases. +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    +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-bs051.html b/doc/pub/week45/html/._week45-bs051.html index 05c6d94e2..2ae6114b7 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Simple Voting Example, head or tail

    @@ -427,6 +467,29 @@ plt.show()
    +======= + +

    Compare Bagging on Trees with Random Forests

    +

    + + +

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

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs052.html b/doc/pub/week45/html/._week45-bs052.html index 13c8d9f4e..64b32573d 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    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.

    @@ -448,7 +488,24 @@ voting_clf.fit(X_train, y_train)
    +======= +

    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 +classifier like decision trees) to modify the data. In each iteration +we emphasize those observations which are misclassified by weighting +them with a factor. +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs053.html b/doc/pub/week45/html/._week45-bs053.html index 74c2cd1da..b19e628c3 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Voting and Bagging

    @@ -501,6 +541,59 @@ voting_clf.fit(X_train, y_train)
    +======= + +

    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 +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 +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 +\( \gamma_1 \) were determined by the Logistic Regression fitting +algorithm. + +

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

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs054.html b/doc/pub/week45/html/._week45-bs054.html index 7f3e2c1c0..b9149bfe8 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Random forests

    Random forests provide an improvement over bagged trees by way of a @@ -421,7 +461,32 @@ uncorrelated quantities. In particular, this means that bagging will not lead to a substantial reduction in variance over a single tree in this setting.

    +======= +

    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. +
    3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    4. +
    5. 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. +
      3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
      4. +
      5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
      6. +
      + +
    + +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. +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs055.html b/doc/pub/week45/html/._week45-bs055.html index ab7e04c4c..c7ca41281 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Random Forest Algorithm

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

    +======= + +

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

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

      @@ -399,6 +446,47 @@ MathJax.Hub.Config({
    1. 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.

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

    +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-bs056.html b/doc/pub/week45/html/._week45-bs056.html index 1217d56aa..ed9b61d6f 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Random Forests Compared with other Methods on the Cancer Data

    @@ -479,7 +519,42 @@ percentage of the total number of cases. 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.

    +======= +

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

    +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 +$$ +G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). +$$ + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs057.html b/doc/pub/week45/html/._week45-bs057.html index 6882f8261..49a28d98e 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Compare Bagging on Trees with Random Forests

    @@ -433,7 +473,35 @@ np.sum(y_pred =
    +======= +

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

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs058.html b/doc/pub/week45/html/._week45-bs058.html index 860564d73..349d3fdf0 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Boosting, a Bird's Eye View

    The basic idea is to combine weak classifiers in order to create a good @@ -394,7 +434,51 @@ classifier like decision trees) to modify the data. In each iteration we emphasize those observations which are misclassified by weighting them with a factor.

    +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e +

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

    +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 +$$ +(\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 +$$ +\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +$$ + +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 +$$ +f_m(x) = f_{m-1}(x) +\beta_m G_m(x). +$$ + +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-bs059.html b/doc/pub/week45/html/._week45-bs059.html index 2b4935623..250b012b5 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    What is boosting? Additive Modelling/Iterative Fitting

    Boosting is a way of fitting an additive expansion in a set of @@ -427,7 +467,29 @@ $$ $$

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

    +======= +

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

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

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs060.html b/doc/pub/week45/html/._week45-bs060.html index 04bdee513..d54fece52 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Iterative Fitting, Regression and Squared-error Cost Function

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

    @@ -400,6 +440,47 @@ use trees, \( \gamma \) parameterizes the split variables and split points at the internal nodes, and the predictions at the terminal nodes.

    +======= + +

    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. +
    3. We rewrite the misclassification error as
    4. +
    + +$$ +\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. +
      3. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
      4. +
      5. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
      6. +
      7. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
      8. +
      + +
    2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
    3. +
    + +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. + +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs061.html b/doc/pub/week45/html/._week45-bs061.html index 086c161ee..9fe3b4a83 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    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.

    @@ -422,7 +462,40 @@ for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equa

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

    +======= +

    AdaBoost Examples

    + +

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

    + + +

    from sklearn.ensemble import AdaBoostClassifier
    +
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    +ada_clf.fit(X_train, y_train)
    +
    +from sklearn.ensemble import AdaBoostClassifier
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    +
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    +ada_clf.fit(X_train_scaled, y_train)
    +y_pred = ada_clf.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = ada_clf.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +plt.show()
    +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs062.html b/doc/pub/week45/html/._week45-bs062.html index 60fa19b7e..6647244f2 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    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 @@ -410,8 +450,22 @@ $$ $$ G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). $$ +======= +

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

    +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-bs063.html b/doc/pub/week45/html/._week45-bs063.html index aa752abb6..a17258f71 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Adaptive Boosting, AdaBoost

    In our iterative procedure we define thus

    @@ -404,7 +444,42 @@ 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))} \).

    +======= +

    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 +$$ +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 +$$ +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)}. +$$ +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    +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 +$$ +(\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-bs064.html b/doc/pub/week45/html/._week45-bs064.html index 756b47746..b9d63b4de 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Building up AdaBoost

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

    @@ -420,7 +460,25 @@ $$ w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} $$ +======= +

    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 +$$ +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. +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs065.html b/doc/pub/week45/html/._week45-bs065.html index 8ff00a146..311ac16d9 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Adaptive boosting: AdaBoost, Basic Algorithm

    The algorithm here is rather straightforward. Assume that our weak @@ -398,6 +438,37 @@ $$ $$

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

    +======= + +

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

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

      +
    1. Initialize our estimate \( f_0(x) \).
    2. +
    3. 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. +
      3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      4. +
      5. update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);
      6. +
      + +
    4. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    5. +
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    @@ -419,27 +490,37 @@ $$

  • 69
  • 70
  • 71
  • +<<<<<<< HEAD
  • 72
  • 73
  • 74
  • 75
  • ...
  • 77
  • +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
  • »
  • +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs066.html b/doc/pub/week45/html/._week45-bs066.html index 90853d627..5b4d8a9e9 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Basic Steps of AdaBoost

    With the above definitions we are now ready to set up the algorithm for AdaBoost. @@ -412,7 +452,61 @@ 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.

    +======= +

    Gradient Boosting, Examples of Regression

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.ensemble import GradientBoostingRegressor
    +from sklearn.preprocessing import StandardScaler
    +import scikitplot as skplt
    +from sklearn.metrics import mean_squared_error
    +
    +n = 100
    +maxdegree = 6
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    +
    +# Make data set.
    +x = np.linspace(-3, 3, n).reshape(-1, 1)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    +
    +error = np.zeros(maxdegree)
    +bias = np.zeros(maxdegree)
    +variance = np.zeros(maxdegree)
    +polydegree = np.zeros(maxdegree)
    +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +
    +for degree in range(1,maxdegree):
    +    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
    +    model.fit(X_train_scaled,y_train)
    +    y_pred = model.predict(X_test_scaled)
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
    +    variance[degree] = np.mean( np.var(y_pred) )
    +    print('Max depth:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.xlim(1,maxdegree-1)
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +save_fig("gdregression")
    +plt.show()
    +
    +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs067.html b/doc/pub/week45/html/._week45-bs067.html index fa9475778..f8e26b8e3 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    AdaBoost Examples

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

    @@ -427,8 +467,55 @@ plt.show()
    +======= +

    Gradient Boosting, Classification Example

    +

    + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +import scikitplot as skplt
    +from sklearn.ensemble import GradientBoostingClassifier
    +from sklearn.model_selection import cross_validate
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    +
    +gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
    +gd_clf.fit(X_train_scaled, y_train)
    +#Cross validation
    +accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
    +print(accuracy)
    +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
    +
    +import scikitplot as skplt
    +y_pred = gd_clf.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +save_fig("gdclassiffierconfusion")
    +plt.show()
    +y_probas = gd_clf.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +save_fig("gdclassiffierroc")
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +save_fig("gdclassiffiercgain")
    +plt.show()
    +
    +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs068.html b/doc/pub/week45/html/._week45-bs068.html index c3e989cec..aca83912e 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    Gradient boosting is again a similar technique to Adaptive boosting, @@ -392,7 +432,28 @@ method via a series of iterations. bringing back the essential steps in linear regression, where our cost function was the least squares function.

    +======= +

    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 +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!!! +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs069.html b/doc/pub/week45/html/._week45-bs069.html index 999bf153d..eec7dc714 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    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 @@ -411,6 +451,62 @@ $$ $$ +======= + +

    Regression Case

    + +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +import xgboost as xgb
    +from sklearn.preprocessing import StandardScaler
    +import scikitplot as skplt
    +from sklearn.metrics import mean_squared_error
    +
    +n = 100
    +maxdegree = 6
    +
    +# Make data set.
    +x = np.linspace(-3, 3, n).reshape(-1, 1)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    +
    +error = np.zeros(maxdegree)
    +bias = np.zeros(maxdegree)
    +variance = np.zeros(maxdegree)
    +polydegree = np.zeros(maxdegree)
    +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +
    +for degree in range(maxdegree):
    +    model =  xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
    +
    +    model.fit(X_train_scaled,y_train)
    +    y_pred = model.predict(X_test_scaled)
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
    +    variance[degree] = np.mean( np.var(y_pred) )
    +    print('Max depth:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.xlim(1,maxdegree-1)
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs070.html b/doc/pub/week45/html/._week45-bs070.html index 0ba4d3fa6..204637df3 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 + - + + + @@ -279,6 +239,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Steepest Descent Example

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

    @@ -394,6 +434,69 @@ g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_ $$

    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.

    +======= + +

    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 numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +import scikitplot as skplt
    +import xgboost as xgb
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +
    +xg_clf = xgb.XGBClassifier()
    +xg_clf.fit(X_train_scaled,y_train)
    +
    +y_test = xg_clf.predict(X_test_scaled)
    +
    +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
    +
    +import scikitplot as skplt
    +y_pred = xg_clf.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +save_fig("xdclassiffierconfusion")
    +plt.show()
    +y_probas = xg_clf.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +save_fig("xdclassiffierroc")
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +save_fig("gdclassiffiercgain")
    +plt.show()
    +
    +
    +xgb.plot_tree(xg_clf,num_trees=0)
    +plt.rcParams['figure.figsize'] = [50, 10]
    +save_fig("xgtree")
    +plt.show()
    +
    +xgb.plot_importance(xg_clf)
    +plt.rcParams['figure.figsize'] = [5, 5]
    +save_fig("xgparams")
    +plt.show()
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    @@ -410,6 +513,7 @@ $$

  • 69
  • 70
  • 71
  • +<<<<<<< HEAD
  • 72
  • 73
  • 74
  • @@ -417,20 +521,29 @@ $$
  • 76
  • 77
  • »
  • +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs071.html b/doc/pub/week45/html/._week45-bs071.html index ab5675a7f..b90350362 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 + - + + + @@ -279,6 +246,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Gradient Boosting, algorithm

    Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, @@ -404,6 +455,55 @@ $$

  • The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
  • +======= + +

    Gradient Boosting, Classification Example

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +import scikitplot as skplt
    +from sklearn.ensemble import GradientBoostingClassifier
    +from sklearn.model_selection import cross_validate
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +
    +gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
    +gd_clf.fit(X_train_scaled, y_train)
    +#Cross validation
    +accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
    +print(accuracy)
    +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
    +
    +import scikitplot as skplt
    +y_pred = gd_clf.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +save_fig("gdclassiffierconfusion")
    +plt.show()
    +y_probas = gd_clf.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +save_fig("gdclassiffierroc")
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +save_fig("gdclassiffiercgain")
    +plt.show()
    +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    +
    + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs072.html b/doc/pub/week45/html/._week45-bs072.html index 2d937465b..14d644037 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 + - + + + @@ -279,6 +246,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Gradient Boosting, Examples of Regression

    @@ -450,7 +501,28 @@ plt.show()
    +======= +

    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 +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!!! +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e + +

    + + + +
    + + + diff --git a/doc/pub/week45/html/._week45-bs073.html b/doc/pub/week45/html/._week45-bs073.html index 63e0716e8..1f3caf5f4 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 + - + + + @@ -279,6 +246,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    Gradient Boosting, Classification Example

    +======= + +

    Regression Case

    + +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e -

    -
    -
    -
    -
    -
    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
    @@ -429,22 +481,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-bs074.html b/doc/pub/week45/html/._week45-bs074.html index 41ed4a5b8..b2955d856 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 + - + + + @@ -279,6 +246,8 @@ MathJax.Hub.Config({ + + +
    +

     

     

     

    + +<<<<<<< HEAD

    XGBoost: Extreme Gradient Boosting

    +======= + +

    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 numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +import scikitplot as skplt
    +import xgboost as xgb
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +
    +xg_clf = xgb.XGBClassifier()
    +xg_clf.fit(X_train_scaled,y_train)
    +
    +y_test = xg_clf.predict(X_test_scaled)
    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
     
     

    XGBoost or Extreme Gradient Boosting, is an optimized distributed gradient boosting library @@ -391,12 +477,40 @@ 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.

    +<<<<<<< HEAD

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

    +======= +import scikitplot as skplt +y_pred = xg_clf.predict(X_test_scaled) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +save_fig("xdclassiffierconfusion") +plt.show() +y_probas = xg_clf.predict_proba(X_test_scaled) +skplt.metrics.plot_roc(y_test, y_probas) +save_fig("xdclassiffierroc") +plt.show() +skplt.metrics.plot_cumulative_gain(y_test, y_probas) +save_fig("gdclassiffiercgain") +plt.show() + + +xgb.plot_tree(xg_clf,num_trees=0) +plt.rcParams['figure.figsize'] = [50, 10] +save_fig("xgtree") +plt.show() + +xgb.plot_importance(xg_clf) +plt.rcParams['figure.figsize'] = [5, 5] +save_fig("xgparams") +plt.show() +
    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e

    @@ -418,18 +532,25 @@ sketch for efficient proposal calculation. It introduces a novel sparsity-aware

  • »
  • +
    + + +
    + + + diff --git a/doc/pub/week45/html/week45-bs.html b/doc/pub/week45/html/week45-bs.html index 252635078..025808c71 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 + - + + + @@ -279,6 +239,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 -
    + +
    [1] Department of Physics, University of Oslo
    +
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    +<<<<<<< HEAD

    Nov 11, 2021

    +======= +

    +

    Nov 10, 2021

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    - +

    Read »

    @@ -424,22 +470,33 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • +<<<<<<< HEAD
  • 77
  • +======= +
  • 71
  • +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
  • »
  • +
    + + +
    © 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 51dcfe0a6..55fe8c689 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 ); + + + @@ -306,122 +259,150 @@ 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 -
    + +
    [1] Department of Physics, University of Oslo
    +
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    +<<<<<<< HEAD

    Nov 11, 2021

    +======= +

    +

    Nov 10, 2021

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    - +











    -

    Overview of week 45

    + +

    Overview of week 45

    + -
    -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.
    • @@ -429,16 +410,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. @@ -446,18 +429,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
    @@ -495,7 +477,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
    @@ -545,102 +527,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 @@ -649,83 +625,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 @@ -736,13 +724,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 @@ -752,60 +742,67 @@ 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\ne k'} p_{mk}p_{mk'}=\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}}. $$ - +











    +<<<<<<< HEAD

    Gini Index?Coefficient/Impurity

    The Gini index \( g \) gives us the degree of probability of a specific @@ -831,14 +828,14 @@ achieved by a series of binary split and this is normally preferred.









    Visualizing the Tree, Classification

    +======= + +

    Visualizing the Tree, Classification

    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e -

    -
    -
    -
    -
    -
    import os
    +
    import os
     from sklearn.datasets import load_breast_cancer
     from sklearn.tree import DecisionTreeClassifier
     from sklearn.model_selection import train_test_split
    @@ -871,32 +868,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
    @@ -920,72 +900,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()
    @@ -993,92 +940,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 @@ -1088,10 +1030,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 +

    @@ -1112,18 +1054,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
    @@ -1190,41 +1129,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:
    @@ -1284,28 +1207,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. @@ -1315,34 +1225,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
    @@ -1383,32 +1292,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
    @@ -1472,32 +1364,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
     
    @@ -1517,86 +1392,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)
    @@ -1634,26 +1460,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)
    @@ -1681,24 +1492,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)
    • @@ -1709,8 +1507,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
    • @@ -1721,26 +1521,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. @@ -1748,45 +1550,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 @@ -1801,382 +1608,28 @@ 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

    - -
    -
    -
    -
    -
    -
    heads_proba = 0.51
    -coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
    -cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
    -plt.figure(figsize=(8,3.5))
    -plt.plot(cumulative_heads_ratio)
    -plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
    -plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
    -plt.xlabel("Number of coin tosses")
    -plt.ylabel("Heads ratio")
    -plt.legend(loc="lower right")
    -plt.axis([0, 10000, 0.42, 0.58])
    -save_fig("votingsimple")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

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

    - -









    -

    Using the Voting Classifier

    - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -from sklearn.datasets import make_moons
    -
    -X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    -X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    -
    -from sklearn.ensemble import RandomForestClassifier
    -from sklearn.ensemble import VotingClassifier
    -from sklearn.linear_model import LogisticRegression
    -from sklearn.svm import SVC
    -
    -log_clf = LogisticRegression(solver="liblinear", random_state=42)
    -rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    -svm_clf = SVC(gamma="auto", random_state=42)
    -
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='hard')
    -
    -voting_clf.fit(X_train, y_train)
    -
    -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(solver="liblinear", random_state=42)
    -rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    -svm_clf = SVC(gamma="auto", probability=True, random_state=42)
    -
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='soft')
    -voting_clf.fit(X_train, y_train)
    -
    -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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Please, not the moons again! Voting and Bagging

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -from sklearn.datasets import make_moons
    -
    -X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    -X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    -from sklearn.ensemble import RandomForestClassifier
    -from sklearn.ensemble import VotingClassifier
    -from sklearn.linear_model import LogisticRegression
    -from sklearn.svm import SVC
    -
    -log_clf = LogisticRegression(random_state=42)
    -rnd_clf = RandomForestClassifier(random_state=42)
    -svm_clf = SVC(random_state=42)
    -
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='hard')
    -voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    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)
    -rnd_clf = RandomForestClassifier(random_state=42)
    -svm_clf = SVC(probability=True, random_state=42)
    -
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='soft')
    -voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    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

    - - - -
    -
    -
    -
    -
    -
    from sklearn.ensemble import BaggingClassifier
    -from sklearn.tree import DecisionTreeClassifier
    -
    -bag_clf = BaggingClassifier(
    -    DecisionTreeClassifier(random_state=42), n_estimators=500,
    -    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
    -bag_clf.fit(X_train, y_train)
    -y_pred = bag_clf.predict(X_test)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    -print(accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    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
    -
    -def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
    -    x1s = np.linspace(axes[0], axes[1], 100)
    -    x2s = np.linspace(axes[2], axes[3], 100)
    -    x1, x2 = np.meshgrid(x1s, x2s)
    -    X_new = np.c_[x1.ravel(), x2.ravel()]
    -    y_pred = clf.predict(X_new).reshape(x1.shape)
    -    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    -    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    -    if contour:
    -        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    -        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    -    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
    -    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
    -    plt.axis(axes)
    -    plt.xlabel(r"$x_1$", fontsize=18)
    -    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    -plt.figure(figsize=(11,4))
    -plt.subplot(121)
    -plot_decision_boundary(tree_clf, X, y)
    -plt.title("Decision Tree", fontsize=14)
    -plt.subplot(122)
    -plot_decision_boundary(bag_clf, X, y)
    -plt.title("Decision Trees with Bagging", fontsize=14)
    -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 +

    +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
     from sklearn.utils import resample
     from sklearn.tree import DecisionTreeRegressor
     
    -n = 100
    +n = 1000
     n_boostraps = 100
    -maxdepth = 8
    +maxdepth = 10
     
     # Make data set.
     x = np.linspace(-3, 3, n).reshape(-1, 1)
    @@ -2187,23 +1640,17 @@ variance = np.zeros(maxdepth)
     polydegree = np.zeros(maxdepth)
     X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
     
    -from sklearn.preprocessing import StandardScaler
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -
    -# we produce a simple tree first as benchmark
    +# we produce a simple tree first as benchmark, no scaling
     simpletree = DecisionTreeRegressor(max_depth=3) 
    -simpletree.fit(X_train_scaled, y_train)
    -simpleprediction = simpletree.predict(X_test_scaled)
    +simpletree.fit(X_train, y_train)
    +simpleprediction = simpletree.predict(X_test)
     for degree in range(1,maxdepth):
         model = DecisionTreeRegressor(max_depth=degree) 
         y_pred = np.empty((y_test.shape[0], n_boostraps))
         for i in range(n_boostraps):
    -        x_, y_ = resample(X_train_scaled, y_train)
    +        x_, y_ = resample(X_train, y_train)
             model.fit(x_, y_)
    -        y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
    +        y_pred[:, i] = model.predict(X_test)#.ravel()
     
         polydegree[degree] = degree
         error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    @@ -2215,7 +1662,7 @@ simpleprediction = simpletree.predict(X_test_scaled)
         print('Var:', variance[degree])
         print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
      
    -mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)
    +mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
     print(mse_simpletree)
     plt.xlim(1,maxdepth)
     plt.plot(polydegree, error, label='MSE')
    @@ -2224,81 +1671,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
    @@ -2335,32 +1770,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
    @@ -2382,34 +1800,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)
    @@ -2451,33 +1853,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)
    @@ -2495,51 +1880,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)
     
    @@ -2547,76 +1902,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 @@ -2628,36 +1956,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
    @@ -2723,374 +2056,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,
    @@ -3111,115 +2432,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
    @@ -3265,32 +2585,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
    @@ -3330,51 +2633,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
    @@ -3420,34 +2709,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
    @@ -3498,26 +2771,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 59127c9bb..c1df18d71 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 + + + + @@ -383,122 +264,150 @@ 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 -
    + +
    [1] Department of Physics, University of Oslo
    +
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    +<<<<<<< HEAD

    Nov 11, 2021

    +======= +

    +

    Nov 10, 2021

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e
    - +











    -

    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.
    • @@ -506,16 +415,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. @@ -523,18 +434,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
    @@ -622,102 +532,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 @@ -726,83 +630,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 @@ -813,13 +729,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 @@ -829,60 +747,67 @@ 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\ne k'} p_{mk}p_{mk'}=\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}}. $$ - +











    +<<<<<<< HEAD

    Gini Index?Coefficient/Impurity

    The Gini index \( g \) gives us the degree of probability of a specific @@ -908,14 +833,14 @@ achieved by a series of binary split and this is normally preferred.









    Visualizing the Tree, Classification

    +======= + +

    Visualizing the Tree, Classification

    +

    +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e -

    -
    -
    -
    -
    -
    import os
    +
    import os
     from sklearn.datasets import load_breast_cancer
     from sklearn.tree import DecisionTreeClassifier
     from sklearn.model_selection import train_test_split
    @@ -948,32 +873,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
    @@ -997,72 +905,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()
    @@ -1070,92 +945,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 @@ -1165,10 +1035,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 +

    @@ -1189,18 +1059,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
    @@ -1267,41 +1134,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:
    @@ -1361,28 +1212,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. @@ -1392,34 +1230,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
    @@ -1460,32 +1297,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
    @@ -1549,32 +1369,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
     
    @@ -1594,86 +1397,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)
    @@ -1711,26 +1465,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)
    @@ -1758,24 +1497,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)
    • @@ -1786,8 +1512,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
    • @@ -1798,26 +1526,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. @@ -1825,45 +1555,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 @@ -1878,382 +1613,28 @@ 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

    - -
    -
    -
    -
    -
    -
    heads_proba = 0.51
    -coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
    -cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
    -plt.figure(figsize=(8,3.5))
    -plt.plot(cumulative_heads_ratio)
    -plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
    -plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
    -plt.xlabel("Number of coin tosses")
    -plt.ylabel("Heads ratio")
    -plt.legend(loc="lower right")
    -plt.axis([0, 10000, 0.42, 0.58])
    -save_fig("votingsimple")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

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

    - -









    -

    Using the Voting Classifier

    - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -from sklearn.datasets import make_moons
    -
    -X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    -X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    -
    -from sklearn.ensemble import RandomForestClassifier
    -from sklearn.ensemble import VotingClassifier
    -from sklearn.linear_model import LogisticRegression
    -from sklearn.svm import SVC
    -
    -log_clf = LogisticRegression(solver="liblinear", random_state=42)
    -rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    -svm_clf = SVC(gamma="auto", random_state=42)
    -
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='hard')
    -
    -voting_clf.fit(X_train, y_train)
    -
    -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(solver="liblinear", random_state=42)
    -rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    -svm_clf = SVC(gamma="auto", probability=True, random_state=42)
    -
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='soft')
    -voting_clf.fit(X_train, y_train)
    -
    -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))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Please, not the moons again! Voting and Bagging

    - - - -
    -
    -
    -
    -
    -
    from sklearn.model_selection import train_test_split
    -from sklearn.datasets import make_moons
    -
    -X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    -X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    -from sklearn.ensemble import RandomForestClassifier
    -from sklearn.ensemble import VotingClassifier
    -from sklearn.linear_model import LogisticRegression
    -from sklearn.svm import SVC
    -
    -log_clf = LogisticRegression(random_state=42)
    -rnd_clf = RandomForestClassifier(random_state=42)
    -svm_clf = SVC(random_state=42)
    -
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='hard')
    -voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    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)
    -rnd_clf = RandomForestClassifier(random_state=42)
    -svm_clf = SVC(probability=True, random_state=42)
    -
    -voting_clf = VotingClassifier(
    -    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    -    voting='soft')
    -voting_clf.fit(X_train, y_train)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    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

    - - - -
    -
    -
    -
    -
    -
    from sklearn.ensemble import BaggingClassifier
    -from sklearn.tree import DecisionTreeClassifier
    -
    -bag_clf = BaggingClassifier(
    -    DecisionTreeClassifier(random_state=42), n_estimators=500,
    -    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
    -bag_clf.fit(X_train, y_train)
    -y_pred = bag_clf.predict(X_test)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    from sklearn.metrics import accuracy_score
    -print(accuracy_score(y_test, y_pred))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    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
    -
    -def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
    -    x1s = np.linspace(axes[0], axes[1], 100)
    -    x2s = np.linspace(axes[2], axes[3], 100)
    -    x1, x2 = np.meshgrid(x1s, x2s)
    -    X_new = np.c_[x1.ravel(), x2.ravel()]
    -    y_pred = clf.predict(X_new).reshape(x1.shape)
    -    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    -    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    -    if contour:
    -        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    -        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    -    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
    -    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
    -    plt.axis(axes)
    -    plt.xlabel(r"$x_1$", fontsize=18)
    -    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    -plt.figure(figsize=(11,4))
    -plt.subplot(121)
    -plot_decision_boundary(tree_clf, X, y)
    -plt.title("Decision Tree", fontsize=14)
    -plt.subplot(122)
    -plot_decision_boundary(bag_clf, X, y)
    -plt.title("Decision Trees with Bagging", fontsize=14)
    -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 +

    +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
     from sklearn.utils import resample
     from sklearn.tree import DecisionTreeRegressor
     
    -n = 100
    +n = 1000
     n_boostraps = 100
    -maxdepth = 8
    +maxdepth = 10
     
     # Make data set.
     x = np.linspace(-3, 3, n).reshape(-1, 1)
    @@ -2264,23 +1645,17 @@ variance = np.<
     polydegree = np.zeros(maxdepth)
     X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
     
    -from sklearn.preprocessing import StandardScaler
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -
    -# we produce a simple tree first as benchmark
    +# we produce a simple tree first as benchmark, no scaling
     simpletree = DecisionTreeRegressor(max_depth=3) 
    -simpletree.fit(X_train_scaled, y_train)
    -simpleprediction = simpletree.predict(X_test_scaled)
    +simpletree.fit(X_train, y_train)
    +simpleprediction = simpletree.predict(X_test)
     for degree in range(1,maxdepth):
         model = DecisionTreeRegressor(max_depth=degree) 
         y_pred = np.empty((y_test.shape[0], n_boostraps))
         for i in range(n_boostraps):
    -        x_, y_ = resample(X_train_scaled, y_train)
    +        x_, y_ = resample(X_train, y_train)
             model.fit(x_, y_)
    -        y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
    +        y_pred[:, i] = model.predict(X_test)#.ravel()
     
         polydegree[degree] = degree
         error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    @@ -2292,7 +1667,7 @@ simpleprediction = simpletreeprint('Var:', variance[degree])
         print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
      
    -mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)
    +mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
     print(mse_simpletree)
     plt.xlim(1,maxdepth)
     plt.plot(polydegree, error, label='MSE')
    @@ -2301,81 +1676,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
    @@ -2412,32 +1775,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
    @@ -2459,34 +1805,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)
    @@ -2528,33 +1858,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)
    @@ -2572,51 +1885,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)
     
    @@ -2624,76 +1907,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 @@ -2705,36 +1961,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
    @@ -2800,374 +2061,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,
    @@ -3188,115 +2437,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
    @@ -3342,32 +2590,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
    @@ -3407,51 +2638,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
    @@ -3497,34 +2714,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
    @@ -3575,26 +2776,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/Results/FigureFiles/votingsimple.png b/doc/pub/week45/ipynb/Results/FigureFiles/votingsimple.png index 564ba322c..30ec67491 100644 Binary files a/doc/pub/week45/ipynb/Results/FigureFiles/votingsimple.png and b/doc/pub/week45/ipynb/Results/FigureFiles/votingsimple.png differ diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb index 31069eb13..9cd96210c 100644 --- a/doc/pub/week45/ipynb/week45.ipynb +++ b/doc/pub/week45/ipynb/week45.ipynb @@ -2,6 +2,7 @@ "cells": [ { "cell_type": "markdown", +<<<<<<< HEAD "id": "5029effd", "metadata": { "editable": true @@ -18,10 +19,17 @@ "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", +<<<<<<< HEAD "Date: **Nov 11, 2021**\n", "\n", "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" @@ -34,6 +42,14 @@ "editable": true }, "source": [ +======= + "Date: **Nov 10, 2021**\n", + "\n", + "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Overview of week 45\n", "\n", "* Thursday: Basics of Decision Trees, Bagging and Voting\n", @@ -46,8 +62,11 @@ "\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", +<<<<<<< HEAD "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." ] }, @@ -58,8 +77,16 @@ "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", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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 +97,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,6 +107,7 @@ "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", +<<<<<<< HEAD "where we then finally end up in so called **leaf nodes**." ] }, @@ -89,6 +118,10 @@ "editable": true }, "source": [ +======= + "where we then finally end up in so called **leaf nodes**. \n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Basics of a tree\n", "\n", "A decision tree is typically divided into a **root node**, the **interior nodes**,\n", @@ -99,6 +132,7 @@ "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", +<<<<<<< HEAD "(class) of unseen query instances." ] }, @@ -133,14 +167,33 @@ "editable": true }, "source": [ +======= + "(class) of unseen query instances.\n", + "\n", + "## A Sketch of a Tree, Regression problem\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## A Sketch of a Tree, Classification problem\n", + "\n", + "\n", + "\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n", "\n", "\n", "\n", "\n", - "

    Figure 1:

    \n", + "

    \n", + "\n", + "\n", "\n", "\n", +<<<<<<< HEAD "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." ] }, @@ -151,6 +204,13 @@ "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", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## General Features\n", "\n", "The overarching approach to decision trees is a top-down approach.\n", @@ -164,6 +224,7 @@ "* 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", +<<<<<<< HEAD "node." ] }, @@ -174,8 +235,14 @@ "editable": true }, "source": [ +======= + "node.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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,6 +254,7 @@ "\n", "4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n", "\n", +<<<<<<< HEAD "Then we are essentially done!" ] }, @@ -197,16 +265,26 @@ "editable": true }, "source": [ +======= + "Then we are essentially done!\n", + "\n", + "\n", + "\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Decision trees and Regression" ] }, { "cell_type": "code", "execution_count": 1, +<<<<<<< HEAD "id": "fcfdb3ca", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -304,10 +382,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "d06f81d0", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Building a tree, regression\n", "\n", @@ -326,10 +408,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "30987ca1", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\sum_{j=1}^J\\sum_{i\\in R_j}(y_i-\\overline{y}_{R_j})^2,\n", @@ -338,6 +424,7 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "973f1d0b", "metadata": { "editable": true @@ -354,6 +441,13 @@ "editable": true }, "source": [ +======= + "metadata": {}, + "source": [ + "where $\\overline{y}_{R_j}$ is the mean response for the training observations \n", + "within box $j$. \n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## A top-down approach, recursive binary splitting\n", "\n", "Unfortunately, it is computationally infeasible to consider every\n", @@ -366,6 +460,7 @@ "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", +<<<<<<< HEAD "better tree in some future step." ] }, @@ -376,6 +471,10 @@ "editable": true }, "source": [ +======= + "better tree in some future step.\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Making a tree\n", "\n", "In order to implement the recursive binary splitting we start by selecting\n", @@ -384,10 +483,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "f43f1d0c", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\left\\{X\\vert x_j < s\\right\\},\n", @@ -396,20 +499,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "5a522921", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "and" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "61aac4b3", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\left\\{X\\vert x_j \\geq s\\right\\},\n", @@ -418,20 +529,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "0ff01949", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "so that we obtain the lowest MSE, that is" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "1fae0428", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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 +559,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "92da3ee2", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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,6 +591,7 @@ "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", +<<<<<<< HEAD "region contains more than five observations." ] }, @@ -478,6 +602,11 @@ "editable": true }, "source": [ +======= + "region contains more than five observations.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Pruning the tree\n", "\n", "The above procedure is rather straightforward, but leads often to\n", @@ -492,6 +621,7 @@ "we consider a sequence of trees indexed by a nonnegative tuning\n", "parameter $\\alpha$.\n", "\n", +<<<<<<< HEAD "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)." ] }, @@ -502,6 +632,10 @@ "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", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Cost complexity pruning\n", "\n", "For each value of $\\alpha$ there corresponds a subtree $T \\in T_0$ such that" @@ -509,10 +643,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "c8edb67c", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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 +659,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "4e7213ce", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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,11 +681,13 @@ "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", +<<<<<<< HEAD "subtree corresponding to $\\alpha$." ] }, @@ -554,10 +698,16 @@ "editable": true }, "source": [ +======= + "subtree corresponding to $\\alpha$. \n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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,6 +720,7 @@ "\n", " * Finally we average the results for each value of $\\alpha$, and pick $\\alpha$ to minimize the average error.\n", "\n", +<<<<<<< HEAD "4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$." ] }, @@ -580,6 +731,14 @@ "editable": true }, "source": [ +======= + "\n", + "4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$.\n", + "\n", + "\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## A Classification Tree\n", "\n", "A classification tree is very similar to a regression tree, except\n", @@ -593,6 +752,7 @@ "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", +<<<<<<< HEAD "fall into that region." ] }, @@ -603,6 +763,10 @@ "editable": true }, "source": [ +======= + "fall into that region. \n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Growing a classification tree\n", "\n", "The task of growing a\n", @@ -620,6 +784,7 @@ "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", +<<<<<<< HEAD "than is the classification error rate." ] }, @@ -630,6 +795,11 @@ "editable": true }, "source": [ +======= + "than is the classification error rate. \n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Classification tree, how to split nodes\n", "\n", "If our targets are the outcome of a classification process that takes\n", @@ -644,22 +814,30 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "f7caed93", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", +<<<<<<< HEAD "id": "f810cd2b", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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 +847,44 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "a99accde", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", +<<<<<<< HEAD "id": "70f12422", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "* Gini index $g$" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "2c764a1f", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "g = \\sum_{k\\ne k'} p_{mk}p_{mk'}=\\sum_{k=1}^K p_{mk}(1-p_{mk}).\n", @@ -703,20 +893,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "36ce64fd", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "* Information entropy or just entropy $s$" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "c7cdc315", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n", @@ -725,6 +923,7 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "6f9b611a", "metadata": { "editable": true @@ -766,6 +965,9 @@ "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Visualizing the Tree, Classification" ] @@ -773,10 +975,12 @@ { "cell_type": "code", "execution_count": 2, +<<<<<<< HEAD "id": "4b5e8fd0", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -817,10 +1021,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "2a7a2bc3", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Visualizing the Tree, The Moons" ] @@ -828,10 +1036,12 @@ { "cell_type": "code", "execution_count": 3, +<<<<<<< HEAD "id": "404b6b46", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -863,10 +1073,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "fa63b030", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Other ways of visualizing the trees\n", "\n", @@ -876,10 +1090,12 @@ { "cell_type": "code", "execution_count": 4, +<<<<<<< HEAD "id": "e18305d7", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -894,10 +1110,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "d3c9b005", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Printing out as text\n", "\n", @@ -908,10 +1128,12 @@ { "cell_type": "code", "execution_count": 5, +<<<<<<< HEAD "id": "b975a14b", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -927,10 +1149,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "99f98c77", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Algorithms for Setting up Decision Trees\n", "\n", @@ -942,6 +1168,7 @@ "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", +<<<<<<< HEAD "in two branches." ] }, @@ -952,6 +1179,10 @@ "editable": true }, "source": [ +======= + "in two branches.\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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", @@ -964,10 +1195,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "e413c33c", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n", @@ -976,10 +1211,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "942dab79", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -988,6 +1227,7 @@ "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", +<<<<<<< HEAD "$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$." ] }, @@ -998,6 +1238,10 @@ "editable": true }, "source": [ +======= + "$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$.\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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", @@ -1006,10 +1250,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "f9d1aa8e", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -1018,20 +1266,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "26b91b6f", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "Here the MSE for a specific node is defined as" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "7ce65e73", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n", @@ -1040,20 +1296,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "396e79d5", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "with" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "396f74b5", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n", @@ -1062,14 +1326,19 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "4cbe3954", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "the mean value of all observations in a specific node.\n", "\n", "Without any regularization, the regression task for decision trees, \n", +<<<<<<< HEAD "just like for classification tasks, is prone to overfitting." ] }, @@ -1080,6 +1349,11 @@ "editable": true }, "source": [ +======= + "just like for classification tasks, is prone to overfitting.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Computing the Gini index\n", "\n", "The example we will look at is a classical one in many Machine\n", @@ -1094,7 +1368,7 @@ "humidity and weak and strong for wind.\n", "\n", "The table here summarizes the various attributes and\n", - "\n", + "
    \n", "\n", "\n", "\n", @@ -1114,6 +1388,7 @@ "\n", "\n", "\n", +<<<<<<< HEAD "
    Day Outlook Temperature Humidity Wind Ride
    13 Overcast Hot Normal Weak 1
    14 Rain Mild High Strong 0
    " ] }, @@ -1124,16 +1399,22 @@ "editable": true }, "source": [ +======= + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Simple Python Code to read in Data and perform Classification" ] }, { "cell_type": "code", "execution_count": 6, +<<<<<<< HEAD "id": "ddcfa964", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1208,10 +1489,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "f8a112fa", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Computing the Gini Factor\n", "\n", @@ -1226,10 +1511,12 @@ { "cell_type": "code", "execution_count": 7, +<<<<<<< HEAD "id": "bd14f8fd", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1297,10 +1584,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "b02c63b6", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Entropy and the ID3 algorithm\n", "\n", @@ -1331,6 +1622,7 @@ "training examples according to their target classification.\n", "\n", "The ID3 algorithm uses this information gain measure to select among the candidate\n", +<<<<<<< HEAD "attributes at each step while growing the tree." ] }, @@ -1341,16 +1633,23 @@ "editable": true }, "source": [ +======= + "attributes at each step while growing the tree.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Cancer Data again now with Decision Trees and other Methods" ] }, { "cell_type": "code", "execution_count": 8, +<<<<<<< HEAD "id": "37fe4589", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1399,10 +1698,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "7f22a1b7", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Another example, the moons again" ] @@ -1410,10 +1713,12 @@ { "cell_type": "code", "execution_count": 9, +<<<<<<< HEAD "id": "319313ce", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1485,10 +1790,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "db1e37fc", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Playing around with regions" ] @@ -1496,10 +1805,12 @@ { "cell_type": "code", "execution_count": 10, +<<<<<<< HEAD "id": "3cb94475", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1527,10 +1838,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "e93f2813", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Regression trees" ] @@ -1538,10 +1853,12 @@ { "cell_type": "code", "execution_count": 11, +<<<<<<< HEAD "id": "87026915", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1556,10 +1873,12 @@ { "cell_type": "code", "execution_count": 12, +<<<<<<< HEAD "id": "9237d8d5", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1571,10 +1890,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "ee857f99", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Final regressor code" ] @@ -1582,10 +1905,12 @@ { "cell_type": "code", "execution_count": 13, +<<<<<<< HEAD "id": "379a7a94", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1632,10 +1957,12 @@ { "cell_type": "code", "execution_count": 14, +<<<<<<< HEAD "id": "4030920d", +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -1671,10 +1998,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "18f7ece2", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Pros and cons of trees, pros\n", "\n", @@ -1690,6 +2021,7 @@ "\n", "* Can model interactions between the different descriptive features\n", "\n", +<<<<<<< HEAD "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)" ] }, @@ -1700,6 +2032,10 @@ "editable": true }, "source": [ +======= + "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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", @@ -1718,6 +2054,7 @@ "\n", "However, by aggregating many decision trees, using methods like\n", "bagging, random forests, and boosting, the predictive performance of\n", +<<<<<<< HEAD "trees can be substantially improved." ] }, @@ -1728,6 +2065,11 @@ "editable": true }, "source": [ +======= + "trees can be substantially improved.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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", @@ -1749,6 +2091,7 @@ "\n", "4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n", "\n", +<<<<<<< HEAD "We discuss these methods here." ] }, @@ -1759,11 +2102,17 @@ "editable": true }, "source": [ +======= + "We discuss these methods here.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## An Overview of Ensemble Methods\n", "\n", "\n", "\n", "\n", +<<<<<<< HEAD "

    Figure 1:

    \n", "" ] @@ -1775,6 +2124,16 @@ "editable": true }, "source": [ +======= + "

    \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Bagging\n", "\n", "The **plain** decision trees suffer from high\n", @@ -1787,6 +2146,7 @@ "\n", "**Bootstrap aggregation**, or just **bagging**, is a\n", "general-purpose procedure for reducing the variance of a statistical\n", +<<<<<<< HEAD "learning method." ] }, @@ -1797,6 +2157,11 @@ "editable": true }, "source": [ +======= + "learning method. \n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## More bagging\n", "\n", "Bagging typically results in improved accuracy\n", @@ -1819,6 +2184,7 @@ "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", +<<<<<<< HEAD "predictor, averaged over all $B$ trees." ] }, @@ -1895,20 +2261,13 @@ "voting_clf = VotingClassifier(\n", " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", " voting='hard')\n", +======= + "predictor, averaged over all $B$ trees.\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "\n", - "voting_clf.fit(X_train, y_train)\n", "\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", - " clf.fit(X_train, y_train)\n", - " y_pred = clf.predict(X_test)\n", - " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))\n", - "\n", - "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n", - "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n", - "svm_clf = SVC(gamma=\"auto\", probability=True, random_state=42)\n", "\n", +<<<<<<< HEAD "voting_clf = VotingClassifier(\n", " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", " voting='soft')\n", @@ -2124,6 +2483,8 @@ "editable": true }, "source": [ +======= +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Making your own Bootstrap: Changing the Level of the Decision Tree\n", "\n", "Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with\n", @@ -2132,11 +2493,14 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 25, "id": "a87db197", +======= + "execution_count": 15, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2148,9 +2512,9 @@ "from sklearn.utils import resample\n", "from sklearn.tree import DecisionTreeRegressor\n", "\n", - "n = 100\n", + "n = 1000\n", "n_boostraps = 100\n", - "maxdepth = 8\n", + "maxdepth = 10\n", "\n", "# Make data set.\n", "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", @@ -2161,23 +2525,17 @@ "polydegree = np.zeros(maxdepth)\n", "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", "\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "# we produce a simple tree first as benchmark\n", + "# we produce a simple tree first as benchmark, no scaling\n", "simpletree = DecisionTreeRegressor(max_depth=3) \n", - "simpletree.fit(X_train_scaled, y_train)\n", - "simpleprediction = simpletree.predict(X_test_scaled)\n", + "simpletree.fit(X_train, y_train)\n", + "simpleprediction = simpletree.predict(X_test)\n", "for degree in range(1,maxdepth):\n", " model = DecisionTreeRegressor(max_depth=degree) \n", " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", " for i in range(n_boostraps):\n", - " x_, y_ = resample(X_train_scaled, y_train)\n", + " x_, y_ = resample(X_train, y_train)\n", " model.fit(x_, y_)\n", - " y_pred[:, i] = model.predict(X_test_scaled)#.ravel()\n", + " y_pred[:, i] = model.predict(X_test)#.ravel()\n", "\n", " polydegree[degree] = degree\n", " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", @@ -2189,7 +2547,7 @@ " print('Var:', variance[degree])\n", " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", " \n", - "mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)\n", + "mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))\n", "print(mse_simpletree)\n", "plt.xlim(1,maxdepth)\n", "plt.plot(polydegree, error, label='MSE')\n", @@ -2202,10 +2560,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "bd224b9b", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Why Voting?\n", "\n", @@ -2221,6 +2583,7 @@ "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", +<<<<<<< HEAD "Decision trees play an important role as our weak classifier. They serve as the basic method." ] }, @@ -2231,6 +2594,10 @@ "editable": true }, "source": [ +======= + "Decision trees play an important role as our weak classifier. They serve as the basic method. \n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Tossing coins\n", "\n", "The simplest case is a so-called voting ensemble. To illustrate this,\n", @@ -2252,6 +2619,7 @@ "\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", +<<<<<<< HEAD "numbers kicking in." ] }, @@ -2262,16 +2630,23 @@ "editable": true }, "source": [ +======= + "numbers kicking in.\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Standard imports first" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 26, "id": "46fedf6a", +======= + "execution_count": 16, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2316,21 +2691,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "c5b88629", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Simple Voting Example, head or tail" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 27, "id": "cd753289", +======= + "execution_count": 17, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2361,10 +2743,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "ff2c01f5", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Using the Voting Classifier\n", "\n", @@ -2373,11 +2759,14 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 28, "id": "5d722d0a", +======= + "execution_count": 18, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2427,21 +2816,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "8882a66e", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Voting and Bagging" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 29, "id": "23939bf2", +======= + "execution_count": 19, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2467,11 +2863,14 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 30, "id": "41bc3004", +======= + "execution_count": 20, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2485,11 +2884,14 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 31, "id": "9d3397a2", +======= + "execution_count": 21, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2505,11 +2907,14 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 32, "id": "6087fac8", +======= + "execution_count": 22, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2523,10 +2928,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "94e1f957", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Random forests\n", "\n", @@ -2546,10 +2955,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "1431c18a", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "m\\approx \\sqrt{p}.\n", @@ -2558,10 +2971,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "2a5dfd06", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "In building a random forest, at\n", "each split in the tree, the algorithm is not even allowed to consider\n", @@ -2578,6 +2995,7 @@ "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", +<<<<<<< HEAD "this setting." ] }, @@ -2588,6 +3006,11 @@ "editable": true }, "source": [ +======= + "this setting.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Random Forest Algorithm\n", "The algorithm described here can be applied to both classification and regression problems.\n", "\n", @@ -2604,6 +3027,7 @@ "\n", "3. split the node into daughter nodes\n", "\n", +<<<<<<< HEAD "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." ] }, @@ -2614,16 +3038,25 @@ "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", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Random Forests Compared with other Methods on the Cancer Data" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 33, "id": "cf7ad4d8", +======= + "execution_count": 23, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2697,10 +3130,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "322bcada", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -2708,6 +3145,7 @@ "\n", "Similarly, the receiver operating characteristic curve, or ROC curve,\n", "displays the diagnostic ability of a binary classifier system as its\n", +<<<<<<< HEAD "discrimination threshold is varied. It plots the true positive rate against the false positive rate." ] }, @@ -2718,16 +3156,24 @@ "editable": true }, "source": [ +======= + "discrimination threshold is varied. It plots the true positive rate against the false positive rate.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Compare Bagging on Trees with Random Forests" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 34, "id": "729bb490", +======= + "execution_count": 24, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2738,11 +3184,14 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 35, "id": "8e9c400f", +======= + "execution_count": 25, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -2757,10 +3206,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "dd160607", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Boosting, a Bird's Eye View\n", "\n", @@ -2772,6 +3225,7 @@ "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", +<<<<<<< HEAD "them with a factor." ] }, @@ -2782,6 +3236,11 @@ "editable": true }, "source": [ +======= + "them with a factor.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## What is boosting? Additive Modelling/Iterative Fitting\n", "\n", "Boosting is a way of fitting an additive expansion in a set of\n", @@ -2791,10 +3250,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "99742488", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", @@ -2803,10 +3266,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "29864b76", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -2820,10 +3287,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "55dfbae1", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n", @@ -2832,10 +3303,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "7a5153b5", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -2846,10 +3321,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "b5fe05e5", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -2858,10 +3337,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "843358e0", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -2871,10 +3354,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "2b42fc98", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", @@ -2883,6 +3370,7 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "fa243046", "metadata": { "editable": true @@ -2897,7 +3385,13 @@ "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -2914,8 +3408,10 @@ "\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", +<<<<<<< HEAD "at the internal nodes, and the predictions at the terminal nodes." ] }, @@ -2926,6 +3422,11 @@ "editable": true }, "source": [ +======= + "at the internal nodes, and the predictions at the terminal nodes.\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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", @@ -2937,10 +3438,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "76855445", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -2949,10 +3454,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "d6fc39ce", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "We start our iteration by simply setting $f_0(x)=0$. \n", "Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain" @@ -2960,10 +3469,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "f4ab9329", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n", @@ -2972,20 +3485,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "63fdbf59", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "and" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "95ed39a8", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n", @@ -2994,20 +3515,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "9ad3b524", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", +<<<<<<< HEAD "id": "a4bb913d", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n", @@ -3016,20 +3545,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "5731b88a", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "05cb71a7", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n", @@ -3038,15 +3575,20 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "cebf470f", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", +<<<<<<< HEAD "$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$." ] }, @@ -3057,6 +3599,12 @@ "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", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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", @@ -3068,10 +3616,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "714ea4ee", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n", @@ -3080,10 +3632,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "3f3eafcf", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "The iterative procedure starts with defining a weak classifier whose\n", "error rate is barely better than random guessing. The iterative\n", @@ -3096,10 +3652,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "889882d2", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", @@ -3108,20 +3668,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "0f1b8941", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "will be a function of" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "a3bb1f79", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n", @@ -3130,10 +3698,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "88df6c57", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Adaptive Boosting, AdaBoost\n", "\n", @@ -3142,10 +3714,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "3c9d9ac3", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n", @@ -3154,10 +3730,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "f1f95d4a", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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" @@ -3165,10 +3745,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "43f589be", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3177,10 +3761,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "d96eaaee", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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" @@ -3188,10 +3776,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "8b948bbb", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n", @@ -3200,6 +3792,7 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "3f3cc06e", "metadata": { "editable": true @@ -3214,7 +3807,12 @@ "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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" @@ -3222,10 +3820,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "1ade6746", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n", @@ -3234,10 +3836,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "a4bbc019", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "which is the classifier that minimizes the weighted error rate in predicting $y$.\n", "\n", @@ -3246,10 +3852,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "4fd3dea0", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3258,20 +3868,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "ca658077", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "which can be rewritten as" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "b9829b00", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3280,20 +3898,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "d744ecab", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "which leads to" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "35adfc8e", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n", @@ -3302,20 +3928,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "1705faa0", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "where we have redefined the error as" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "267b593c", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3324,20 +3958,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "e484405e", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "which leads to an update of" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "ffdf57ea", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n", @@ -3346,20 +3988,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "d59e62b1", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "This leads to the new weights" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "87a66ea2", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n", @@ -3368,10 +4018,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "5f13a75a", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Adaptive boosting: AdaBoost, Basic Algorithm\n", "\n", @@ -3388,10 +4042,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "8a00cea3", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n", @@ -3400,6 +4058,7 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "d9a59dc0", "metadata": { "editable": true @@ -3414,7 +4073,12 @@ "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3426,10 +4090,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "69942aec", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3438,10 +4106,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "e9ec97a5", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3453,6 +4125,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", @@ -3461,6 +4134,7 @@ "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", +<<<<<<< HEAD "observations that are missed in the previous iterations." ] }, @@ -3471,6 +4145,12 @@ "editable": true }, "source": [ +======= + "observations that are missed in the previous iterations.\n", + "\n", + "\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## AdaBoost Examples\n", "\n", "Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here." @@ -3478,11 +4158,14 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 36, "id": "f790730a", +======= + "execution_count": 26, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3511,10 +4194,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "1d164a72", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent\n", "\n", @@ -3524,6 +4211,7 @@ "\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", +<<<<<<< HEAD "function was the least squares function." ] }, @@ -3534,6 +4222,10 @@ "editable": true }, "source": [ +======= + "function was the least squares function.\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## 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", @@ -3542,10 +4234,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "9fe0e925", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "(\\hat{\\boldsymbol{f}}) = \\mathrm{argmin}_{\\boldsymbol{f}}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -3554,20 +4250,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "93d443b7", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "ff0a341f", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "f_M(x) = \\sum_{m=0}^M h_m(x).\n", @@ -3576,20 +4280,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "7a54de9d", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", +<<<<<<< HEAD "id": "f7b3ed21", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3598,10 +4310,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "d76a3b92", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3611,10 +4327,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "7ebc7787", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "(\\rho_1) = \\mathrm{argmin}_{\\rho}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i+2\\rho y_i)^2.\n", @@ -3623,10 +4343,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "81f21ab2", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Steepest Descent Example\n", "\n", @@ -3635,10 +4359,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "c3b3e85b", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n", @@ -3647,20 +4375,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "75c9d363", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "We can then proceed and compute" ] }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "ec040a0c", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3669,6 +4405,7 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "1c51f8d8", "metadata": { "editable": true @@ -3683,7 +4420,12 @@ "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3695,10 +4437,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "b90f8570", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -3707,10 +4453,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "8b448fbd", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "The way we proceed in an iterative fashion is to\n", "1. Initialize our estimate $f_0(x)$.\n", @@ -3723,6 +4473,7 @@ "\n", "c. update the estimate $f_m(x) = f_{m-1}(x)+h_m(u_m,x)$;\n", "\n", +<<<<<<< HEAD "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$." ] }, @@ -3733,16 +4484,24 @@ "editable": true }, "source": [ +======= + "\n", + "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$.\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Gradient Boosting, Examples of Regression" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 37, "id": "fa49f235", +======= + "execution_count": 27, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3796,21 +4555,28 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "98586a10", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Gradient Boosting, Classification Example" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 38, "id": "d21bf444", +======= + "execution_count": 28, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3858,13 +4624,18 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "e0d676e3", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "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", @@ -3876,6 +4647,7 @@ "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", +<<<<<<< HEAD "It is now the algorithm which wins essentially all ML competitions!!!" ] }, @@ -3886,16 +4658,23 @@ "editable": true }, "source": [ +======= + "It is now the algorithm which wins essentially all ML competitions!!!\n", + "\n", +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "## Regression Case" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 39, "id": "b375c6ca", +======= + "execution_count": 29, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -3949,10 +4728,14 @@ }, { "cell_type": "markdown", +<<<<<<< HEAD "id": "761ccc1e", "metadata": { "editable": true }, +======= + "metadata": {}, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "source": [ "## Xgboost on the Cancer Data\n", "\n", @@ -3961,11 +4744,14 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 40, "id": "0673208c", +======= + "execution_count": 30, +>>>>>>> 0e5076dfbfc8cf7946a5cec60d742ecccdbbcd3e "metadata": { - "collapsed": false, - "editable": true + "collapsed": false }, "outputs": [], "source": [ @@ -4026,5 +4812,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 40c801067..8cc5502a5 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$ @@ -1172,184 +1172,6 @@ the context of bagging classification trees, we can add up the total amount that the Gini index is decreased by splits over a given predictor, averaged over all $B$ trees. -!split -===== Simple Voting Example, head or tail ===== -!bc pycod -heads_proba = 0.51 -coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32) -cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1) -plt.figure(figsize=(8,3.5)) -plt.plot(cumulative_heads_ratio) -plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%") -plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%") -plt.xlabel("Number of coin tosses") -plt.ylabel("Heads ratio") -plt.legend(loc="lower right") -plt.axis([0, 10000, 0.42, 0.58]) -save_fig("votingsimple") -plt.show() - -!ec - -!split -===== Using the Voting Classifier ===== -!bc pycod -from sklearn.model_selection import train_test_split -from sklearn.datasets import make_moons - -X, y = make_moons(n_samples=500, noise=0.30, random_state=42) -X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) - -from sklearn.ensemble import RandomForestClassifier -from sklearn.ensemble import VotingClassifier -from sklearn.linear_model import LogisticRegression -from sklearn.svm import SVC - -log_clf = LogisticRegression(solver="liblinear", random_state=42) -rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42) -svm_clf = SVC(gamma="auto", random_state=42) - -voting_clf = VotingClassifier( - estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], - voting='hard') - -voting_clf.fit(X_train, y_train) - -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(solver="liblinear", random_state=42) -rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42) -svm_clf = SVC(gamma="auto", probability=True, random_state=42) - -voting_clf = VotingClassifier( - estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], - voting='soft') -voting_clf.fit(X_train, y_train) - -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)) - -!ec - -!split -===== Please, not the moons again! Voting and Bagging ===== - -!bc pycod -from sklearn.model_selection import train_test_split -from sklearn.datasets import make_moons - -X, y = make_moons(n_samples=500, noise=0.30, random_state=42) -X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) -from sklearn.ensemble import RandomForestClassifier -from sklearn.ensemble import VotingClassifier -from sklearn.linear_model import LogisticRegression -from sklearn.svm import SVC - -log_clf = LogisticRegression(random_state=42) -rnd_clf = RandomForestClassifier(random_state=42) -svm_clf = SVC(random_state=42) - -voting_clf = VotingClassifier( - estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], - voting='hard') -voting_clf.fit(X_train, y_train) -!ec - -!bc pycod -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)) -!ec - -!bc pycod -log_clf = LogisticRegression(random_state=42) -rnd_clf = RandomForestClassifier(random_state=42) -svm_clf = SVC(probability=True, random_state=42) - -voting_clf = VotingClassifier( - estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], - voting='soft') -voting_clf.fit(X_train, y_train) -!ec - -!bc pycod -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)) -!ec - -!split -===== Bagging Examples ===== - -!bc pycod -from sklearn.ensemble import BaggingClassifier -from sklearn.tree import DecisionTreeClassifier - -bag_clf = BaggingClassifier( - DecisionTreeClassifier(random_state=42), n_estimators=500, - max_samples=100, bootstrap=True, n_jobs=-1, random_state=42) -bag_clf.fit(X_train, y_train) -y_pred = bag_clf.predict(X_test) -!ec - - -!bc pycod -from sklearn.metrics import accuracy_score -print(accuracy_score(y_test, y_pred)) -!ec - -!bc pycod -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)) -!ec - -!bc pycod -from matplotlib.colors import ListedColormap - -def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True): - x1s = np.linspace(axes[0], axes[1], 100) - x2s = np.linspace(axes[2], axes[3], 100) - x1, x2 = np.meshgrid(x1s, x2s) - X_new = np.c_[x1.ravel(), x2.ravel()] - y_pred = clf.predict(X_new).reshape(x1.shape) - custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) - plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) - if contour: - custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) - plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) - plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha) - plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha) - plt.axis(axes) - plt.xlabel(r"$x_1$", fontsize=18) - plt.ylabel(r"$x_2$", fontsize=18, rotation=0) -plt.figure(figsize=(11,4)) -plt.subplot(121) -plot_decision_boundary(tree_clf, X, y) -plt.title("Decision Tree", fontsize=14) -plt.subplot(122) -plot_decision_boundary(bag_clf, X, y) -plt.title("Decision Trees with Bagging", fontsize=14) -save_fig("baggingtree") -plt.show() -!ec - !split @@ -1366,9 +1188,9 @@ from sklearn.pipeline import make_pipeline from sklearn.utils import resample from sklearn.tree import DecisionTreeRegressor -n = 100 +n = 1000 n_boostraps = 100 -maxdepth = 8 +maxdepth = 10 # Make data set. x = np.linspace(-3, 3, n).reshape(-1, 1) @@ -1379,23 +1201,17 @@ variance = np.zeros(maxdepth) polydegree = np.zeros(maxdepth) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -from sklearn.preprocessing import StandardScaler -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -# we produce a simple tree first as benchmark +# we produce a simple tree first as benchmark, no scaling simpletree = DecisionTreeRegressor(max_depth=3) -simpletree.fit(X_train_scaled, y_train) -simpleprediction = simpletree.predict(X_test_scaled) +simpletree.fit(X_train, y_train) +simpleprediction = simpletree.predict(X_test) for degree in range(1,maxdepth): model = DecisionTreeRegressor(max_depth=degree) y_pred = np.empty((y_test.shape[0], n_boostraps)) for i in range(n_boostraps): - x_, y_ = resample(X_train_scaled, y_train) + x_, y_ = resample(X_train, y_train) model.fit(x_, y_) - y_pred[:, i] = model.predict(X_test_scaled)#.ravel() + y_pred[:, i] = model.predict(X_test)#.ravel() polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) @@ -1407,7 +1223,7 @@ for degree in range(1,maxdepth): print('Var:', variance[degree]) print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) -mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2) +mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)) print(mse_simpletree) plt.xlim(1,maxdepth) plt.plot(polydegree, error, label='MSE')