diff --git a/doc/HandWrittenNotes/2022/NotesNov42022.pdf b/doc/HandWrittenNotes/2022/NotesNov42022.pdf new file mode 100644 index 000000000..5b47b5c4a Binary files /dev/null and b/doc/HandWrittenNotes/2022/NotesNov42022.pdf differ diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index 99289d9fe..6d1f6c5be 100644 --- a/doc/pub/week45/html/._week45-bs000.html +++ b/doc/pub/week45/html/._week45-bs000.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -409,7 +182,7 @@ MathJax.Hub.Config({
    -

    Aug 23, 2022

    +

    Nov 5, 2022


    @@ -434,7 +207,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs001.html b/doc/pub/week45/html/._week45-bs001.html index dde0d8852..f4626629b 100644 --- a/doc/pub/week45/html/._week45-bs001.html +++ b/doc/pub/week45/html/._week45-bs001.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -394,8 +167,8 @@ MathJax.Hub.Config({

    Overview of week 45

    @@ -412,7 +185,7 @@ MathJax.Hub.Config({
      -
    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.
    2. +
    @@ -434,7 +207,7 @@ MathJax.Hub.Config({
  • 10
  • 11
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs002.html b/doc/pub/week45/html/._week45-bs002.html index 53975cdb9..be2cef016 100644 --- a/doc/pub/week45/html/._week45-bs002.html +++ b/doc/pub/week45/html/._week45-bs002.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,31 +164,18 @@ MathJax.Hub.Config({

     

     

     

    -

    Decision trees, overarching aims

    +

    Boosting, a Bird's Eye View

    -

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

    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.

    -

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

    - -

    The main idea of decision trees -is to find those descriptive features which contain the most -information regarding the target feature and then split the dataset -along the values of these features such that the target feature values -for the resulting underlying datasets are as pure as possible. -

    - -

    The descriptive features which reproduce best the target/output features are normally said -to be the most informative ones. The process of finding the most -informative feature is done until we accomplish a stopping criteria -where we then finally end up in so called leaf nodes. +

    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.

    @@ -435,7 +195,7 @@ where we then finally end up in so called leaf nodes.

  • 11
  • 12
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs003.html b/doc/pub/week45/html/._week45-bs003.html index a34c4b2da..aae25dce3 100644 --- a/doc/pub/week45/html/._week45-bs003.html +++ b/doc/pub/week45/html/._week45-bs003.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,20 +164,53 @@ MathJax.Hub.Config({

     

     

     

    -

    Basics of a tree

    +

    What is boosting? Additive Modelling/Iterative Fitting

    -

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

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

    -

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

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

    +

    diff --git a/doc/pub/week45/html/._week45-bs004.html b/doc/pub/week45/html/._week45-bs004.html index 3cd5a9901..bd5f65968 100644 --- a/doc/pub/week45/html/._week45-bs004.html +++ b/doc/pub/week45/html/._week45-bs004.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,9 +164,24 @@ MathJax.Hub.Config({

     

     

     

    -

    A Sketch of a Tree, Regression problem

    +

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

    @@ -414,7 +202,7 @@ MathJax.Hub.Config({

  • 13
  • 14
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs005.html b/doc/pub/week45/html/._week45-bs005.html index 841e2acbf..54074b9cc 100644 --- a/doc/pub/week45/html/._week45-bs005.html +++ b/doc/pub/week45/html/._week45-bs005.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,9 +164,47 @@ MathJax.Hub.Config({

     

     

     

    -

    A Sketch of a Tree, Classification problem

    +

    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.

    + +

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

    @@ -415,7 +226,7 @@ MathJax.Hub.Config({

  • 14
  • 15
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs006.html b/doc/pub/week45/html/._week45-bs006.html index 922fc2459..3ee2445d1 100644 --- a/doc/pub/week45/html/._week45-bs006.html +++ b/doc/pub/week45/html/._week45-bs006.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,15 +164,36 @@ MathJax.Hub.Config({

     

     

     

    -

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    +

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

    + +

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

    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.

    @@ -422,7 +216,7 @@ MathJax.Hub.Config({

  • 15
  • 16
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs007.html b/doc/pub/week45/html/._week45-bs007.html index ba1f73877..0b17341b8 100644 --- a/doc/pub/week45/html/._week45-bs007.html +++ b/doc/pub/week45/html/._week45-bs007.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,19 +164,29 @@ MathJax.Hub.Config({

     

     

     

    -

    General Features

    +

    Adaptive Boosting, AdaBoost

    -

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

    +

    In our iterative procedure we define thus

    +$$ +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +$$ - -

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

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

    @@ -427,7 +210,7 @@ node.

  • 16
  • 17
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs008.html b/doc/pub/week45/html/._week45-bs008.html index d31aad625..e3ac6adca 100644 --- a/doc/pub/week45/html/._week45-bs008.html +++ b/doc/pub/week45/html/._week45-bs008.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,19 +164,45 @@ MathJax.Hub.Config({

     

     

     

    -

    How do we set it up?

    +

    Building up AdaBoost

    -

    In simplified terms, the process of training a decision tree and -predicting the target features of query instances is as follows: -

    +

    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))} +$$ -
      -
    1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
    2. -
    3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
    4. -
    5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
    6. -
    7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    8. -
    -

    Then we are essentially done!

    @@ -428,7 +227,7 @@ predicting the target features of query instances is as follows:

  • 17
  • 18
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs009.html b/doc/pub/week45/html/._week45-bs009.html index 705f6fbe3..e986e422d 100644 --- a/doc/pub/week45/html/._week45-bs009.html +++ b/doc/pub/week45/html/._week45-bs009.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,117 +164,23 @@ MathJax.Hub.Config({

     

     

     

    -

    Decision trees and Regression

    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    - -
    -
    -
    -
    -
    -
    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    +

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

    -steps=250 - -distance=0 -x=0 -distance_list=[] -steps_list=[] -while x<steps: - distance+=np.random.randint(-1,2) - distance_list.append(distance) - x+=1 - steps_list.append(x) -plt.plot(steps_list,distance_list, color='green', label="Random Walk Data") - -steps_list=np.asarray(steps_list) -distance_list=np.asarray(distance_list) - -X=steps_list[:,np.newaxis] - -#Polynomial fits - -#Degree 2 -poly_features=PolynomialFeatures(degree=2, include_bias=False) -X_poly=poly_features.fit_transform(X) - -lin_reg=LinearRegression() -poly_fit=lin_reg.fit(X_poly,distance_list) -b=lin_reg.coef_ -c=lin_reg.intercept_ -print ("2nd degree coefficients:") -print ("zero power: ",c) -print ("first power: ", b[0]) -print ("second power: ",b[1]) - -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 -plt.plot(z, z_mod, color='r', label="2nd Degree Fit") -plt.title("Polynomial Regression") - -plt.xlabel("Steps") -plt.ylabel("Distance") - -#Degree 10 -poly_features10=PolynomialFeatures(degree=10, include_bias=False) -X_poly10=poly_features10.fit_transform(X) - -poly_fit10=lin_reg.fit(X_poly10,distance_list) - -y_plot=poly_fit10.predict(X_poly10) -plt.plot(X, y_plot, color='black', label="10th Degree Fit") - -plt.legend() -plt.show() - - -#Decision Tree Regression -from sklearn.tree import DecisionTreeRegressor -regr_1=DecisionTreeRegressor(max_depth=2) -regr_2=DecisionTreeRegressor(max_depth=5) -regr_3=DecisionTreeRegressor(max_depth=7) -regr_1.fit(X, distance_list) -regr_2.fit(X, distance_list) -regr_3.fit(X, distance_list) - -X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis] -y_1 = regr_1.predict(X_test) -y_2 = regr_2.predict(X_test) -y_3=regr_3.predict(X_test) - -# Plot the results -plt.figure() -plt.scatter(X, distance_list, s=2.5, c="black", label="data") -plt.plot(X_test, y_1, color="red", - label="max_depth=2", linewidth=2) -plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2) -plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2) - -plt.xlabel("Data") -plt.ylabel("Darget") -plt.title("Decision Tree Regression") -plt.legend() -plt.show() -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

    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.

    @@ -527,7 +206,7 @@ plt.show()

  • 18
  • 19
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs010.html b/doc/pub/week45/html/._week45-bs010.html index 1db65912e..413953c52 100644 --- a/doc/pub/week45/html/._week45-bs010.html +++ b/doc/pub/week45/html/._week45-bs010.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,27 +164,36 @@ MathJax.Hub.Config({

     

     

     

    -

    Building a tree, regression

    +

    Basic Steps of AdaBoost

    -

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

    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 +

    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. +
    $$ -\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +\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}, $$ -

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

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

    @@ -439,7 +221,7 @@ within box \( j \).

  • 19
  • 20
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs011.html b/doc/pub/week45/html/._week45-bs011.html index a4d1b5fd1..2d6cfc8a7 100644 --- a/doc/pub/week45/html/._week45-bs011.html +++ b/doc/pub/week45/html/._week45-bs011.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,21 +164,53 @@ MathJax.Hub.Config({

     

     

     

    -

    A top-down approach, recursive binary splitting

    +

    AdaBoost Examples

    -

    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 -

    +

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

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

    @@ -431,8 +236,6 @@ better tree in some future step.

  • 19
  • 20
  • 21
  • -
  • ...
  • -
  • 79
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs012.html b/doc/pub/week45/html/._week45-bs012.html index 2f44618c0..b164b5da8 100644 --- a/doc/pub/week45/html/._week45-bs012.html +++ b/doc/pub/week45/html/._week45-bs012.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,52 +164,16 @@ MathJax.Hub.Config({

     

     

     

    -

    Making a tree

    +

    Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent

    -

    In order to implement the recursive binary splitting we start by selecting -the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) -

    -$$ -\left\{X\vert x_j < s\right\}, -$$ - -

    and

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

    so that we obtain the lowest MSE, that is

    -$$ -\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, -$$ - -

    which we want to minimize by considering all predictors -\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for -each predictor. These values could be determined by randomly assigned -numbers or by starting at the midpoint and then proceed till we find -an optimal value. +

    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.

    -

    For any \( j \) and \( s \), we define the pair of half-planes where -\( \overline{y}_{R_1} \) is the mean response for the training -observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean -response for the training observations in \( R_2(j,s) \). -

    - -

    Finding the values of \( j \) and \( s \) that minimize the above equation can be -done quite quickly, especially when the number of features \( p \) is not -too large. -

    - -

    Next, we repeat the process, looking -for the best predictor and best cutpoint in order to split the data -further so as to minimize the MSE within each of the resulting -regions. However, this time, instead of splitting the entire predictor -space, we split one of the two previously identified regions. We now -have three regions. Again, we look to split one of these three regions -further, so as to minimize the MSE. The process continues until a -stopping criterion is reached; for instance, we may continue until no -region contains more than five observations. +

    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.

    @@ -462,9 +199,6 @@ region contains more than five observations.

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • ...
  • -
  • 79
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs013.html b/doc/pub/week45/html/._week45-bs013.html index cc72ac5de..e698bd7a0 100644 --- a/doc/pub/week45/html/._week45-bs013.html +++ b/doc/pub/week45/html/._week45-bs013.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -390,24 +163,36 @@ MathJax.Hub.Config({

     

     

     

    - -

    Pruning the tree

    + +

    The Squared-Error again! Steepest Descent

    -

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

    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

    -

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

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

    -

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

    +

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

    @@ -431,10 +216,6 @@ parameter \( \alpha \).

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • 23
  • -
  • ...
  • -
  • 79
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs014.html b/doc/pub/week45/html/._week45-bs014.html index 88408fb6b..9f33fddf0 100644 --- a/doc/pub/week45/html/._week45-bs014.html +++ b/doc/pub/week45/html/._week45-bs014.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,35 +164,19 @@ MathJax.Hub.Config({

     

     

     

    -

    Cost complexity pruning

    +

    Steepest Descent Example

    -

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

    +

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

    $$ -\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. $$ -

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

    +

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

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

    - -

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

    +

    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.

    @@ -442,11 +199,6 @@ subtree corresponding to \( \alpha \).

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • 23
  • -
  • 24
  • -
  • ...
  • -
  • 79
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs015.html b/doc/pub/week45/html/._week45-bs015.html index d2009c726..20d1bb18a 100644 --- a/doc/pub/week45/html/._week45-bs015.html +++ b/doc/pub/week45/html/._week45-bs015.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,27 +164,29 @@ MathJax.Hub.Config({

     

     

     

    -

    Schematic Regression Procedure

    +

    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. 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. -
    3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    4. -
    5. 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:
    6. -
        -
      • 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.
      • -
      -
    7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
    8. +
    9. Initialize our estimate \( f_0(x) \).
    10. +
    11. 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. +
      +
    12. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    -
    -
    - -

    diff --git a/doc/pub/week45/html/._week45-bs016.html b/doc/pub/week45/html/._week45-bs016.html index bfabe467e..2c87de64f 100644 --- a/doc/pub/week45/html/._week45-bs016.html +++ b/doc/pub/week45/html/._week45-bs016.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,21 +164,70 @@ MathJax.Hub.Config({

     

     

     

    -

    A Classification Tree

    +

    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
    +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)
    +
    +for degree in range(1,maxdegree):
    +    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
    +    model.fit(X_train,y_train)
    +    y_pred = model.predict(X_test)
    +    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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    A classification tree is very similar to a regression tree, except -that it is used to predict a qualitative response rather than a -quantitative one. Recall that for a regression tree, the predicted -response for an observation is given by the mean response of the -training observations that belong to the same terminal node. In -contrast, for a classification tree, we predict that each observation -belongs to the most commonly occurring class of training observations -in the region to which it belongs. In interpreting the results of a -classification tree, we are often interested not only in the class -prediction corresponding to a particular terminal node region, but -also in the class proportions among the training observations that -fall into that region. -

    @@ -426,13 +248,6 @@ fall into that region.

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • 23
  • -
  • 24
  • -
  • 25
  • -
  • 26
  • -
  • ...
  • -
  • 79
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs017.html b/doc/pub/week45/html/._week45-bs017.html index 9ff761564..6215df638 100644 --- a/doc/pub/week45/html/._week45-bs017.html +++ b/doc/pub/week45/html/._week45-bs017.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,26 +164,69 @@ MathJax.Hub.Config({

     

     

     

    -

    Growing a classification tree

    +

    Gradient Boosting, Classification Example

    -

    The task of growing a -classification tree is quite similar to the task of growing a -regression tree. Just as in the regression setting, we use recursive -binary splitting to grow a classification tree. However, in the -classification setting, the MSE cannot be used as a criterion for making -the binary splits. A natural alternative to MSE is the classification -error rate. Since we plan to assign an observation in a given region -to the most commonly occurring error rate class of training -observations in that region, the classification error rate is simply -the fraction of the training observations in that region that do not -belong to the most common class. -

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

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

    @@ -430,14 +246,6 @@ than is the classification error rate.

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • 23
  • -
  • 24
  • -
  • 25
  • -
  • 26
  • -
  • 27
  • -
  • ...
  • -
  • 79
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs018.html b/doc/pub/week45/html/._week45-bs018.html index 91a4949b7..4ddc59c93 100644 --- a/doc/pub/week45/html/._week45-bs018.html +++ b/doc/pub/week45/html/._week45-bs018.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,48 +164,22 @@ MathJax.Hub.Config({

     

     

     

    -

    Classification tree, how to split nodes

    +

    XGBoost: Extreme Gradient Boosting

    -

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

    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.

    -

    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 +

    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.

    -$$ -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 -\( m \). The three most common ways of splitting a node are given by -

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

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

    @@ -451,15 +198,6 @@ $$

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • 23
  • -
  • 24
  • -
  • 25
  • -
  • 26
  • -
  • 27
  • -
  • 28
  • -
  • ...
  • -
  • 79
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs019.html b/doc/pub/week45/html/._week45-bs019.html index 9cf90fe45..48190cd86 100644 --- a/doc/pub/week45/html/._week45-bs019.html +++ b/doc/pub/week45/html/._week45-bs019.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,19 +164,71 @@ MathJax.Hub.Config({

     

     

     

    -

    Gini Index (or Coefficient or Impurity)

    +

    Regression Case

    -

    The Gini index \( g \) gives us the degree of probability of a specific -variable that is wrongly classified. -

    -

    It takes values \( g \in [0,1] \),

    -
      -
    1. \( g=0 \) means a pure case where all elements belong to one class only.
    2. -
    3. A value \( g=1 \) means that all elements are randomly distributed across various classes.
    4. -
    5. A value \( g=0.5 \) means that the elements in a node are uniformly distributed across classes.
    6. -
    -

    It favors binary splitting.

    + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +import xgboost as xgb
    +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)
    +
    +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,y_train)
    +    y_pred = model.predict(X_test)
    +    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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    @@ -421,16 +246,6 @@ variable that is wrongly classified.

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • 23
  • -
  • 24
  • -
  • 25
  • -
  • 26
  • -
  • 27
  • -
  • 28
  • -
  • 29
  • -
  • ...
  • -
  • 79
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs020.html b/doc/pub/week45/html/._week45-bs020.html index e8cfabfaf..453dd02f0 100644 --- a/doc/pub/week45/html/._week45-bs020.html +++ b/doc/pub/week45/html/._week45-bs020.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -391,13 +164,82 @@ MathJax.Hub.Config({

     

     

     

    -

    Why binary splits?

    +

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

    It is custom to split to a tree uising binary splits. The reason is -that multiway splits fragment the data too quickly, leaving -insufficient data at the next level down. Multiway splits can be -achieved by a series of binary split and this is normally preferred. -

    @@ -414,18 +256,6 @@ achieved by a series of binary split and this is normally preferred.

  • 19
  • 20
  • 21
  • -
  • 22
  • -
  • 23
  • -
  • 24
  • -
  • 25
  • -
  • 26
  • -
  • 27
  • -
  • 28
  • -
  • 29
  • -
  • 30
  • -
  • ...
  • -
  • 79
  • -
  • »
  • diff --git a/doc/pub/week45/html/week45-bs.html b/doc/pub/week45/html/week45-bs.html index 99289d9fe..6d1f6c5be 100644 --- a/doc/pub/week45/html/week45-bs.html +++ b/doc/pub/week45/html/week45-bs.html @@ -37,175 +37,6 @@ doconce format html week45.do.txt --html_style=bootstrap --pygments_html_style=d
  • Overview of week 45
  • -
  • Decision trees, overarching aims
  • -
  • Basics of a tree
  • -
  • A Sketch of a Tree, Regression problem
  • -
  • A Sketch of a Tree, Classification problem
  • -
  • A typical Decision Tree with its pertinent Jargon, Classification Problem
  • -
  • General Features
  • -
  • How do we set it up?
  • -
  • Decision trees and Regression
  • -
  • Building a tree, regression
  • -
  • A top-down approach, recursive binary splitting
  • -
  • Making a tree
  • -
  • Pruning the tree
  • -
  • Cost complexity pruning
  • -
  • Schematic Regression Procedure
  • -
  • A Classification Tree
  • -
  • Growing a classification tree
  • -
  • Classification tree, how to split nodes
  • -
  • Gini Index (or Coefficient or Impurity)
  • -
  • Why binary splits?
  • -
  • Computing a Tree using the Gini Index
  • -
  • The Table
  • -
  • Computing the various Gini Indices
  • -
  • Computing the various Gini Indices, Hours slept
  • -
  • Computing the various Gini Indices, Hours studied
  • -
  • A possible code using Scikit-Learn
  • -
  • Visualizing Trees, More examples
  • -
  • Visualizing the Tree, The Moons
  • -
  • Other ways of visualizing the trees
  • -
  • Printing out as text
  • -
  • Algorithms for Setting up Decision Trees
  • -
  • The CART algorithm for Classification
  • -
  • The CART algorithm for Regression
  • -
  • Computing the Gini index
  • -
  • Simple Python Code to read in Data and perform Classification
  • -
  • Computing the Gini Factor
  • -
  • Entropy and the ID3 algorithm
  • -
  • Cancer Data again now with Decision Trees and other Methods
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods
  • -
  • An Overview of Ensemble Methods
  • -
  • Bagging
  • -
  • More bagging
  • -
  • Making your own Bootstrap: Changing the Level of the Decision Tree
  • -
  • Why Voting?
  • -
  • Tossing coins
  • -
  • Standard imports first
  • -
  • Simple Voting Example, head or tail
  • -
  • Using the Voting Classifier
  • -
  • Voting and Bagging
  • -
  • Random forests
  • -
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Boosting, a Bird's Eye View
  • -
  • What is boosting? Additive Modelling/Iterative Fitting
  • -
  • Iterative Fitting, Regression and Squared-error Cost Function
  • -
  • Squared-Error Example and Iterative Fitting
  • -
  • Iterative Fitting, Classification and AdaBoost
  • -
  • Adaptive Boosting, AdaBoost
  • -
  • Building up AdaBoost
  • -
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • -
  • Basic Steps of AdaBoost
  • -
  • AdaBoost Examples
  • -
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • -
  • The Squared-Error again! Steepest Descent
  • -
  • Steepest Descent Example
  • -
  • Gradient Boosting, algorithm
  • -
  • Gradient Boosting, Examples of Regression
  • -
  • Gradient Boosting, Classification Example
  • -
  • XGBoost: Extreme Gradient Boosting
  • -
  • Regression Case
  • -
  • Xgboost on the Cancer Data
  • +
  • Boosting, a Bird's Eye View
  • +
  • What is boosting? Additive Modelling/Iterative Fitting
  • +
  • Iterative Fitting, Regression and Squared-error Cost Function
  • +
  • Squared-Error Example and Iterative Fitting
  • +
  • Iterative Fitting, Classification and AdaBoost
  • +
  • Adaptive Boosting, AdaBoost
  • +
  • Building up AdaBoost
  • +
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • +
  • Basic Steps of AdaBoost
  • +
  • AdaBoost Examples
  • +
  • Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
  • +
  • The Squared-Error again! Steepest Descent
  • +
  • Steepest Descent Example
  • +
  • Gradient Boosting, algorithm
  • +
  • Gradient Boosting, Examples of Regression
  • +
  • Gradient Boosting, Classification Example
  • +
  • XGBoost: Extreme Gradient Boosting
  • +
  • Regression Case
  • +
  • Xgboost on the Cancer Data
  • @@ -409,7 +182,7 @@ MathJax.Hub.Config({
    -

    Aug 23, 2022

    +

    Nov 5, 2022


    @@ -434,7 +207,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 79
  • +
  • 21
  • »
  • diff --git a/doc/pub/week45/html/week45-reveal.html b/doc/pub/week45/html/week45-reveal.html index 588fe0da7..9dc7299d6 100644 --- a/doc/pub/week45/html/week45-reveal.html +++ b/doc/pub/week45/html/week45-reveal.html @@ -184,7 +184,7 @@ MathJax.Hub.Config({
    -

    Aug 23, 2022

    +

    Nov 5, 2022


    @@ -198,8 +198,8 @@ MathJax.Hub.Config({

    Overview of week 45

    @@ -216,2359 +216,11 @@ MathJax.Hub.Config({ 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.
    2. +

    -
    -

    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, -classification and regression tasks. -

    - -

    The main idea of decision trees -is to find those descriptive features which contain the most -information regarding the target feature and then split the dataset -along the values of these features such that the target feature values -for the resulting underlying datasets are as pure as possible. -

    - -

    The descriptive features which reproduce best the target/output features are normally said -to be the most informative ones. The process of finding the most -informative feature is done until we accomplish a stopping criteria -where we then finally end up in so called leaf nodes. -

    -
    - -
    -

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

    -
    - -
    -

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

    -
    - -
    -

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

    3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
    4. -

    5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
    6. -

    7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    8. -
    -

    -

    Then we are essentially done!

    -
    - -
    -

    Decision trees and Regression

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    -
    -steps=250
    -
    -distance=0
    -x=0
    -distance_list=[]
    -steps_list=[]
    -while x<steps:
    -    distance+=np.random.randint(-1,2)
    -    distance_list.append(distance)
    -    x+=1
    -    steps_list.append(x)
    -plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
    -
    -steps_list=np.asarray(steps_list)
    -distance_list=np.asarray(distance_list)
    -
    -X=steps_list[:,np.newaxis]
    -
    -#Polynomial fits
    -
    -#Degree 2
    -poly_features=PolynomialFeatures(degree=2, include_bias=False)
    -X_poly=poly_features.fit_transform(X)
    -
    -lin_reg=LinearRegression()
    -poly_fit=lin_reg.fit(X_poly,distance_list)
    -b=lin_reg.coef_
    -c=lin_reg.intercept_
    -print ("2nd degree coefficients:")
    -print ("zero power: ",c)
    -print ("first power: ", b[0])
    -print ("second power: ",b[1])
    -
    -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
    -plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
    -plt.title("Polynomial Regression")
    -
    -plt.xlabel("Steps")
    -plt.ylabel("Distance")
    -
    -#Degree 10
    -poly_features10=PolynomialFeatures(degree=10, include_bias=False)
    -X_poly10=poly_features10.fit_transform(X)
    -
    -poly_fit10=lin_reg.fit(X_poly10,distance_list)
    -
    -y_plot=poly_fit10.predict(X_poly10)
    -plt.plot(X, y_plot, color='black', label="10th Degree Fit")
    -
    -plt.legend()
    -plt.show()
    -
    -
    -#Decision Tree Regression
    -from sklearn.tree import DecisionTreeRegressor
    -regr_1=DecisionTreeRegressor(max_depth=2)
    -regr_2=DecisionTreeRegressor(max_depth=5)
    -regr_3=DecisionTreeRegressor(max_depth=7)
    -regr_1.fit(X, distance_list)
    -regr_2.fit(X, distance_list)
    -regr_3.fit(X, distance_list)
    -
    -X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
    -y_1 = regr_1.predict(X_test)
    -y_2 = regr_2.predict(X_test)
    -y_3=regr_3.predict(X_test)
    -
    -# Plot the results
    -plt.figure()
    -plt.scatter(X, distance_list, s=2.5, c="black", label="data")
    -plt.plot(X_test, y_1, color="red",
    -         label="max_depth=2", linewidth=2)
    -plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
    -plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
    -
    -plt.xlabel("Data")
    -plt.ylabel("Darget")
    -plt.title("Decision Tree Regression")
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

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

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

    -

    How do we construct the regions \( R_1,\dots,R_J \)? In theory, the -regions could have any shape. However, we choose to divide the -predictor space into high-dimensional rectangles, or boxes, for -simplicity and for ease of interpretation of the resulting predictive -model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the -MSE, given by -

    - -

     
    -$$ -\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, -$$ -

     
    - -

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

    -
    - -
    -

    A top-down approach, recursive binary splitting

    - -

    Unfortunately, it is computationally infeasible to consider every -possible partition of the feature space into \( J \) boxes. The common -strategy is to take a top-down approach -

    - -

    The approach is top-down because it begins at the top of the tree (all -observations belong to a single region) and then successively splits -the predictor space; each split is indicated via two new branches -further down on the tree. It is greedy because at each step of the -tree-building process, the best split is made at that particular step, -rather than looking ahead and picking a split that will lead to a -better tree in some future step. -

    -
    - -
    -

    Making a tree

    - -

    In order to implement the recursive binary splitting we start by selecting -the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) -

    -

     
    -$$ -\left\{X\vert x_j < s\right\}, -$$ -

     
    - -

    and

    -

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

     
    - -

    so that we obtain the lowest MSE, that is

    -

     
    -$$ -\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, -$$ -

     
    - -

    which we want to minimize by considering all predictors -\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for -each predictor. These values could be determined by randomly assigned -numbers or by starting at the midpoint and then proceed till we find -an optimal value. -

    - -

    For any \( j \) and \( s \), we define the pair of half-planes where -\( \overline{y}_{R_1} \) is the mean response for the training -observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean -response for the training observations in \( R_2(j,s) \). -

    - -

    Finding the values of \( j \) and \( s \) that minimize the above equation can be -done quite quickly, especially when the number of features \( p \) is not -too large. -

    - -

    Next, we repeat the process, looking -for the best predictor and best cutpoint in order to split the data -further so as to minimize the MSE within each of the resulting -regions. However, this time, instead of splitting the entire predictor -space, we split one of the two previously identified regions. We now -have three regions. Again, we look to split one of these three regions -further, so as to minimize the MSE. The process continues until a -stopping criterion is reached; for instance, we may continue until no -region contains more than five observations. -

    -
    - -
    -

    Pruning the tree

    - -

    The above procedure is rather straightforward, but leads often to -overfitting and unnecessarily large and complicated trees. The basic -idea is to grow a large tree \( T_0 \) and then prune it back in order to -obtain a subtree. A smaller tree with fewer splits (fewer regions) can -lead to smaller variance and better interpretation at the cost of a -little more bias. -

    - -

    The so-called Cost complexity pruning algorithm gives us a -way to do just this. Rather than considering every possible subtree, -we consider a sequence of trees indexed by a nonnegative tuning -parameter \( \alpha \). -

    - -

    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

    -

     
    -$$ -\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, -$$ -

     
    - -

    is as small as possible. Here \( \overline{T} \) is -the number of terminal nodes of the tree \( T \) , \( R_m \) is the -rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. -

    - -

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

    - -

    It turns out that as we increase \( \alpha \) from zero -branches get pruned from the tree in a nested and predictable fashion, -so obtaining the whole sequence of subtrees as a function of \( \alpha \) is -easy. We can select a value of \( \alpha \) using a validation set or using -cross-validation. We then return to the full data set and obtain the -subtree corresponding to \( \alpha \). -

    -
    - -
    -

    Schematic Regression Procedure

    - -
    -Building a Regression Tree -

    - -

      -

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

    3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    4. -

    5. 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:
    6. -
        - -

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

      -

    7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
    8. -
    -
    -
    - -
    -

    A Classification Tree

    - -

    A classification tree is very similar to a regression tree, except -that it is used to predict a qualitative response rather than a -quantitative one. Recall that for a regression tree, the predicted -response for an observation is given by the mean response of the -training observations that belong to the same terminal node. In -contrast, for a classification tree, we predict that each observation -belongs to the most commonly occurring class of training observations -in the region to which it belongs. In interpreting the results of a -classification tree, we are often interested not only in the class -prediction corresponding to a particular terminal node region, but -also in the class proportions among the training observations that -fall into that region. -

    -
    - -
    -

    Growing a classification tree

    - -

    The task of growing a -classification tree is quite similar to the task of growing a -regression tree. Just as in the regression setting, we use recursive -binary splitting to grow a classification tree. However, in the -classification setting, the MSE cannot be used as a criterion for making -the binary splits. A natural alternative to MSE is the classification -error rate. Since we plan to assign an observation in a given region -to the most commonly occurring error rate class of training -observations in that region, the classification error rate is simply -the fraction of the training observations in that region that do not -belong to the most common class. -

    - -

    When building a classification tree, either the Gini index or the -entropy are typically used to evaluate the quality of a particular -split, since these two approaches are more sensitive to node purity -than is the classification error rate. -

    -
    - -
    -

    Classification tree, how to split nodes

    - -

    If our targets are the outcome of a classification process that takes -for example \( k=1,2,\dots,K \) values, the only thing we need to think of -is to set up the splitting criteria for each node. -

    - -

    We define a PDF \( p_{mk} \) that represents the number of observations of -a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent -this likelihood function in terms of the proportion \( I(y_i=k) \) of -observations of this class in the region \( R_m \) as -

    - -

     
    -$$ -p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). -$$ -

     
    - -

    We let \( p_{mk} \) represent the majority class of observations in region -\( m \). The three most common ways of splitting a node are given by -

    - - -

    -

     
    -$$ -\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}}. -$$ -

     
    -

    - -
    -

    Gini Index (or Coefficient or Impurity)

    - -

    The Gini index \( g \) gives us the degree of probability of a specific -variable that is wrongly classified. -

    - -

    It takes values \( g \in [0,1] \),

    -
      -

    1. \( g=0 \) means a pure case where all elements belong to one class only.
    2. -

    3. A value \( g=1 \) means that all elements are randomly distributed across various classes.
    4. -

    5. A value \( g=0.5 \) means that the elements in a node are uniformly distributed across classes.
    6. -
    -

    -

    It favors binary splitting.

    -
    - -
    -

    Why binary splits?

    - -

    It is custom to split to a tree uising binary splits. The reason is -that multiway splits fragment the data too quickly, leaving -insufficient data at the next level down. Multiway splits can be -achieved by a series of binary split and this is normally preferred. -

    -
    - -
    -

    Computing a Tree using the Gini Index

    - -

    Consider the following example with attributes/features and two -possible outcomes (classes) for each attribute. Assume we wish to find some -correlations between the average grade of a student as function of the -number of hours studied and hours slept. We want also to correlate the -grade in a given course with the general trend, whether the students -recently has gotten grades below average or above. -

    - -

    We have three features/attributes

    -
      -

    1. Trend of average grades before present course, classified as either below or above the average grade of the whole class
    2. - -

    3. The number of hours studies, classified again as either higher (more than 3 hours per day) or lower . Here we have used a standard for one \( ECTS \) which is scaled to 25-30 hours of work for a semester which lasts 18 weeks, with 15 weeks of lectures and 3 weeks for exams, assuming a total of 30 ECTS per semester.
    4. -

    5. The number of hours slept as high for more than \( 8 \) hours and below for less than 8 hours of sleep, classified again as either high or low
    6. -

    7. The final grade whether it is above or below average
    8. -
    -
    - -
    -

    The Table

    - - - - - - - - - - - - - - - - - -
    Grade Trend Hours slept Hours Studied Grade
    Above Low High Above
    Below High Low Below
    Above Low High Above
    Above High High Above
    Below Low High Below
    Above Low Low Below
    Below High High Below
    Below Low High Below
    Above Low Low Below
    Above High High Above
    -
    - -
    -

    Computing the various Gini Indices

    - -

    In computations we will translate all classes into numbers. Being -these binary classes, they can easily be split into ones and zeros. -

    - -
    -Gini index for Average trend -

    -

    See handwritten notes for Thursday November 11

    -
    -
    - -
    -

    Computing the various Gini Indices, Hours slept

    - -
    -Gini index for hour slept -

    -

    See handwritten notes for Thursday November 11

    -
    -
    - -
    -

    Computing the various Gini Indices, Hours studied

    - -
    -Gini index for hour studied -

    -

    See handwritten notes for Thursday November 11

    -
    - -

    For final tree, see the above handwritten notes

    -
    - -
    -

    A possible code using Scikit-Learn

    - - - -
    -
    -
    -
    -
    -
    # 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)
    -
    -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')
    -
    -infile = open(data_path("grades.csv"),'r')
    -
    -# Read the experimental data with Pandas
    -from IPython.display import display
    -grades = pd.read_csv(infile,names = ('Trend','Sleep','Studied','Grade'))
    -grades = pd.DataFrame(grades)
    -
    -# Features and targets
    -X = grades.loc[:, grades.columns != 'Grade'].values
    -y = grades.loc[:, grades.columns == 'Grade'].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/grade.dot",
    -    rounded=True,
    -    filled=True
    -)
    -cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'
    -os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Visualizing Trees, More examples

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

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

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

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

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

    -
    - -
    -

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

    -
    - -
    -

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

    -
    - -
    -

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

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

    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']))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

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

    -
    - -
    -

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

    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
    -
    -
    -from sklearn.svm import SVC
    -from sklearn import datasets
    -from sklearn.tree import DecisionTreeClassifier
    -from sklearn.datasets import make_moons
    -from sklearn.tree import export_graphviz
    -
    -Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
    -
    -deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
    -deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
    -deep_tree_clf1.fit(Xm, ym)
    -deep_tree_clf2.fit(Xm, ym)
    -
    -
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    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)
    -
    -plt.figure(figsize=(11, 4))
    -plt.subplot(121)
    -plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    -plt.subplot(122)
    -plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

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

    Final regressor code

    - - -
    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    -
    -tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
    -tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
    -tree_reg1.fit(X, y)
    -tree_reg2.fit(X, y)
    -
    -def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
    -    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
    -    y_pred = tree_reg.predict(x1)
    -    plt.axis(axes)
    -    plt.xlabel("$x_1$", fontsize=18)
    -    if ylabel:
    -        plt.ylabel(ylabel, fontsize=18, rotation=0)
    -    plt.plot(X, y, "b.")
    -    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
    -
    -plt.figure(figsize=(11, 4))
    -plt.subplot(121)
    -plot_regression_predictions(tree_reg1, X, y)
    -for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    -    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
    -plt.text(0.21, 0.65, "Depth=0", fontsize=15)
    -plt.text(0.01, 0.2, "Depth=1", fontsize=13)
    -plt.text(0.65, 0.8, "Depth=1", fontsize=13)
    -plt.legend(loc="upper center", fontsize=18)
    -plt.title("max_depth=2", fontsize=14)
    -
    -plt.subplot(122)
    -plot_regression_predictions(tree_reg2, X, y, ylabel=None)
    -for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    -    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
    -for split in (0.0458, 0.1298, 0.2873, 0.9040):
    -    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
    -plt.text(0.3, 0.5, "Depth=2", fontsize=13)
    -plt.title("max_depth=3", fontsize=14)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    tree_reg1 = DecisionTreeRegressor(random_state=42)
    -tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
    -tree_reg1.fit(X, y)
    -tree_reg2.fit(X, y)
    -
    -x1 = np.linspace(0, 1, 500).reshape(-1, 1)
    -y_pred1 = tree_reg1.predict(x1)
    -y_pred2 = tree_reg2.predict(x1)
    -
    -plt.figure(figsize=(11, 4))
    -
    -plt.subplot(121)
    -plt.plot(X, y, "b.")
    -plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
    -plt.axis([0, 1, -0.2, 1.1])
    -plt.xlabel("$x_1$", fontsize=18)
    -plt.ylabel("$y$", fontsize=18, rotation=0)
    -plt.legend(loc="upper center", fontsize=18)
    -plt.title("No restrictions", fontsize=14)
    -
    -plt.subplot(122)
    -plt.plot(X, y, "b.")
    -plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
    -plt.axis([0, 1, -0.2, 1.1])
    -plt.xlabel("$x_1$", fontsize=18)
    -plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Pros and cons of trees, pros

    - - -
    - -
    -

    Disadvantages

    - - -

    -

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

    -
    - -
    -

    An Overview of Ensemble Methods

    - -

    -
    -

    -
    -

    -
    - -
    -

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

    -
    - -
    -

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

    -
    - -
    -

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

    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.

    -
    - -
    -

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

    -
    - -
    -

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

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

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

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

    Random forests

    - -

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

    - -

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

    - -

    A fresh sample of \( m \) predictors is -taken at each split, and typically we choose -

    - -

     
    -$$ -m\approx \sqrt{p}. -$$ -

     
    - -

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

    - -

    The reason for this is rather clever. Suppose that there is one very -strong predictor in the data set, along with a number of other -moderately strong predictors. Then in the collection of bagged -variable importance random forest trees, most or all of the trees will -use this strong predictor in the top split. Consequently, all of the -bagged trees will look quite similar to each other. Hence the -predictions from the bagged trees will be highly correlated. -Unfortunately, averaging many highly correlated quantities does not -lead to as large of a reduction in variance as averaging many -uncorrelated 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.

    -
      -

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

        3. pick the best split point among the \( m \) features using for example the CART algorithm and create a new node
        4. - -

        5. split the node into daughter nodes
        6. -
        -

        -

      -

      -

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

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

    - -

    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

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

    Boosting, a Bird's Eye View

    diff --git a/doc/pub/week45/html/week45-solarized.html b/doc/pub/week45/html/week45-solarized.html index f15c67f11..ec5204b26 100644 --- a/doc/pub/week45/html/week45-solarized.html +++ b/doc/pub/week45/html/week45-solarized.html @@ -64,175 +64,6 @@ div.toc p,a {
    @@ -340,8 +171,8 @@ MathJax.Hub.Config({

    Overview of week 45

    Videos @@ -357,2270 +188,11 @@ MathJax.Hub.Config({ 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.
    2. +
    -









    -

    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, -classification and regression tasks. -

    - -

    The main idea of decision trees -is to find those descriptive features which contain the most -information regarding the target feature and then split the dataset -along the values of these features such that the target feature values -for the resulting underlying datasets are as pure as possible. -

    - -

    The descriptive features which reproduce best the target/output features are normally said -to be the most informative ones. The process of finding the most -informative feature is done until we accomplish a stopping criteria -where we then finally end up in so called leaf nodes. -

    - -









    -

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

    - -









    -

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

    - -









    -

    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. -
    3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
    4. -
    5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
    6. -
    7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    8. -
    -

    Then we are essentially done!

    - -









    -

    Decision trees and Regression

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    -
    -steps=250
    -
    -distance=0
    -x=0
    -distance_list=[]
    -steps_list=[]
    -while x<steps:
    -    distance+=np.random.randint(-1,2)
    -    distance_list.append(distance)
    -    x+=1
    -    steps_list.append(x)
    -plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
    -
    -steps_list=np.asarray(steps_list)
    -distance_list=np.asarray(distance_list)
    -
    -X=steps_list[:,np.newaxis]
    -
    -#Polynomial fits
    -
    -#Degree 2
    -poly_features=PolynomialFeatures(degree=2, include_bias=False)
    -X_poly=poly_features.fit_transform(X)
    -
    -lin_reg=LinearRegression()
    -poly_fit=lin_reg.fit(X_poly,distance_list)
    -b=lin_reg.coef_
    -c=lin_reg.intercept_
    -print ("2nd degree coefficients:")
    -print ("zero power: ",c)
    -print ("first power: ", b[0])
    -print ("second power: ",b[1])
    -
    -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
    -plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
    -plt.title("Polynomial Regression")
    -
    -plt.xlabel("Steps")
    -plt.ylabel("Distance")
    -
    -#Degree 10
    -poly_features10=PolynomialFeatures(degree=10, include_bias=False)
    -X_poly10=poly_features10.fit_transform(X)
    -
    -poly_fit10=lin_reg.fit(X_poly10,distance_list)
    -
    -y_plot=poly_fit10.predict(X_poly10)
    -plt.plot(X, y_plot, color='black', label="10th Degree Fit")
    -
    -plt.legend()
    -plt.show()
    -
    -
    -#Decision Tree Regression
    -from sklearn.tree import DecisionTreeRegressor
    -regr_1=DecisionTreeRegressor(max_depth=2)
    -regr_2=DecisionTreeRegressor(max_depth=5)
    -regr_3=DecisionTreeRegressor(max_depth=7)
    -regr_1.fit(X, distance_list)
    -regr_2.fit(X, distance_list)
    -regr_3.fit(X, distance_list)
    -
    -X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
    -y_1 = regr_1.predict(X_test)
    -y_2 = regr_2.predict(X_test)
    -y_3=regr_3.predict(X_test)
    -
    -# Plot the results
    -plt.figure()
    -plt.scatter(X, distance_list, s=2.5, c="black", label="data")
    -plt.plot(X_test, y_1, color="red",
    -         label="max_depth=2", linewidth=2)
    -plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
    -plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
    -
    -plt.xlabel("Data")
    -plt.ylabel("Darget")
    -plt.title("Decision Tree Regression")
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

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

    How do we construct the regions \( R_1,\dots,R_J \)? In theory, the -regions could have any shape. However, we choose to divide the -predictor space into high-dimensional rectangles, or boxes, for -simplicity and for ease of interpretation of the resulting predictive -model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the -MSE, given by -

    - -$$ -\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, -$$ - -

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

    - -









    -

    A top-down approach, recursive binary splitting

    - -

    Unfortunately, it is computationally infeasible to consider every -possible partition of the feature space into \( J \) boxes. The common -strategy is to take a top-down approach -

    - -

    The approach is top-down because it begins at the top of the tree (all -observations belong to a single region) and then successively splits -the predictor space; each split is indicated via two new branches -further down on the tree. It is greedy because at each step of the -tree-building process, the best split is made at that particular step, -rather than looking ahead and picking a split that will lead to a -better tree in some future step. -

    - -









    -

    Making a tree

    - -

    In order to implement the recursive binary splitting we start by selecting -the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) -

    -$$ -\left\{X\vert x_j < s\right\}, -$$ - -

    and

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

    so that we obtain the lowest MSE, that is

    -$$ -\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, -$$ - -

    which we want to minimize by considering all predictors -\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for -each predictor. These values could be determined by randomly assigned -numbers or by starting at the midpoint and then proceed till we find -an optimal value. -

    - -

    For any \( j \) and \( s \), we define the pair of half-planes where -\( \overline{y}_{R_1} \) is the mean response for the training -observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean -response for the training observations in \( R_2(j,s) \). -

    - -

    Finding the values of \( j \) and \( s \) that minimize the above equation can be -done quite quickly, especially when the number of features \( p \) is not -too large. -

    - -

    Next, we repeat the process, looking -for the best predictor and best cutpoint in order to split the data -further so as to minimize the MSE within each of the resulting -regions. However, this time, instead of splitting the entire predictor -space, we split one of the two previously identified regions. We now -have three regions. Again, we look to split one of these three regions -further, so as to minimize the MSE. The process continues until a -stopping criterion is reached; for instance, we may continue until no -region contains more than five observations. -

    - - -

    Pruning the tree

    - -

    The above procedure is rather straightforward, but leads often to -overfitting and unnecessarily large and complicated trees. The basic -idea is to grow a large tree \( T_0 \) and then prune it back in order to -obtain a subtree. A smaller tree with fewer splits (fewer regions) can -lead to smaller variance and better interpretation at the cost of a -little more bias. -

    - -

    The so-called Cost complexity pruning algorithm gives us a -way to do just this. Rather than considering every possible subtree, -we consider a sequence of trees indexed by a nonnegative tuning -parameter \( \alpha \). -

    - -

    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

    -$$ -\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, -$$ - -

    is as small as possible. Here \( \overline{T} \) is -the number of terminal nodes of the tree \( T \) , \( R_m \) is the -rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. -

    - -

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

    - -

    It turns out that as we increase \( \alpha \) from zero -branches get pruned from the tree in a nested and predictable fashion, -so obtaining the whole sequence of subtrees as a function of \( \alpha \) is -easy. We can select a value of \( \alpha \) using a validation set or using -cross-validation. We then return to the full data set and obtain the -subtree corresponding to \( \alpha \). -

    - -









    -

    Schematic Regression Procedure

    - -
    -Building a Regression Tree -

    - -

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









    -

    A Classification Tree

    - -

    A classification tree is very similar to a regression tree, except -that it is used to predict a qualitative response rather than a -quantitative one. Recall that for a regression tree, the predicted -response for an observation is given by the mean response of the -training observations that belong to the same terminal node. In -contrast, for a classification tree, we predict that each observation -belongs to the most commonly occurring class of training observations -in the region to which it belongs. In interpreting the results of a -classification tree, we are often interested not only in the class -prediction corresponding to a particular terminal node region, but -also in the class proportions among the training observations that -fall into that region. -

    - -









    -

    Growing a classification tree

    - -

    The task of growing a -classification tree is quite similar to the task of growing a -regression tree. Just as in the regression setting, we use recursive -binary splitting to grow a classification tree. However, in the -classification setting, the MSE cannot be used as a criterion for making -the binary splits. A natural alternative to MSE is the classification -error rate. Since we plan to assign an observation in a given region -to the most commonly occurring error rate class of training -observations in that region, the classification error rate is simply -the fraction of the training observations in that region that do not -belong to the most common class. -

    - -

    When building a classification tree, either the Gini index or the -entropy are typically used to evaluate the quality of a particular -split, since these two approaches are more sensitive to node purity -than is the classification error rate. -

    - -









    -

    Classification tree, how to split nodes

    - -

    If our targets are the outcome of a classification process that takes -for example \( k=1,2,\dots,K \) values, the only thing we need to think of -is to set up the splitting criteria for each node. -

    - -

    We define a PDF \( p_{mk} \) that represents the number of observations of -a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent -this likelihood function in terms of the proportion \( I(y_i=k) \) of -observations of this class in the region \( R_m \) as -

    - -$$ -p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). -$$ - -

    We let \( p_{mk} \) represent the majority class of observations in region -\( m \). The three most common ways of splitting a node are given by -

    - - -$$ -\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}}. -$$ - - -









    -

    Gini Index (or Coefficient or Impurity)

    - -

    The Gini index \( g \) gives us the degree of probability of a specific -variable that is wrongly classified. -

    - -

    It takes values \( g \in [0,1] \),

    -
      -
    1. \( g=0 \) means a pure case where all elements belong to one class only.
    2. -
    3. A value \( g=1 \) means that all elements are randomly distributed across various classes.
    4. -
    5. A value \( g=0.5 \) means that the elements in a node are uniformly distributed across classes.
    6. -
    -

    It favors binary splitting.

    - -









    -

    Why binary splits?

    - -

    It is custom to split to a tree uising binary splits. The reason is -that multiway splits fragment the data too quickly, leaving -insufficient data at the next level down. Multiway splits can be -achieved by a series of binary split and this is normally preferred. -

    - -









    -

    Computing a Tree using the Gini Index

    - -

    Consider the following example with attributes/features and two -possible outcomes (classes) for each attribute. Assume we wish to find some -correlations between the average grade of a student as function of the -number of hours studied and hours slept. We want also to correlate the -grade in a given course with the general trend, whether the students -recently has gotten grades below average or above. -

    - -

    We have three features/attributes

    -
      -
    1. Trend of average grades before present course, classified as either below or above the average grade of the whole class
    2. -
    3. The number of hours studies, classified again as either higher (more than 3 hours per day) or lower . Here we have used a standard for one \( ECTS \) which is scaled to 25-30 hours of work for a semester which lasts 18 weeks, with 15 weeks of lectures and 3 weeks for exams, assuming a total of 30 ECTS per semester.
    4. -
    5. The number of hours slept as high for more than \( 8 \) hours and below for less than 8 hours of sleep, classified again as either high or low
    6. -
    7. The final grade whether it is above or below average
    8. -
    -









    -

    The Table

    - - - - - - - - - - - - - - - - - -
    Grade Trend Hours slept Hours Studied Grade
    Above Low High Above
    Below High Low Below
    Above Low High Above
    Above High High Above
    Below Low High Below
    Above Low Low Below
    Below High High Below
    Below Low High Below
    Above Low Low Below
    Above High High Above
    - -









    -

    Computing the various Gini Indices

    - -

    In computations we will translate all classes into numbers. Being -these binary classes, they can easily be split into ones and zeros. -

    - -
    -Gini index for Average trend -

    -

    See handwritten notes for Thursday November 11

    -
    - - -









    -

    Computing the various Gini Indices, Hours slept

    - -
    -Gini index for hour slept -

    -

    See handwritten notes for Thursday November 11

    -
    - - -









    -

    Computing the various Gini Indices, Hours studied

    - -
    -Gini index for hour studied -

    -

    See handwritten notes for Thursday November 11

    -
    - - -

    For final tree, see the above handwritten notes

    - -









    -

    A possible code using Scikit-Learn

    - - - -
    -
    -
    -
    -
    -
    # 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)
    -
    -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')
    -
    -infile = open(data_path("grades.csv"),'r')
    -
    -# Read the experimental data with Pandas
    -from IPython.display import display
    -grades = pd.read_csv(infile,names = ('Trend','Sleep','Studied','Grade'))
    -grades = pd.DataFrame(grades)
    -
    -# Features and targets
    -X = grades.loc[:, grades.columns != 'Grade'].values
    -y = grades.loc[:, grades.columns == 'Grade'].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/grade.dot",
    -    rounded=True,
    -    filled=True
    -)
    -cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'
    -os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualizing Trees, More examples

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









    -

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









    -

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









    -

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









    -

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

    - -









    -

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

    - -









    -

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

    - -









    -

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









    -

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









    -

    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']))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

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

    - -









    -

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









    -

    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
    -
    -
    -from sklearn.svm import SVC
    -from sklearn import datasets
    -from sklearn.tree import DecisionTreeClassifier
    -from sklearn.datasets import make_moons
    -from sklearn.tree import export_graphviz
    -
    -Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
    -
    -deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
    -deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
    -deep_tree_clf1.fit(Xm, ym)
    -deep_tree_clf2.fit(Xm, ym)
    -
    -
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    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)
    -
    -plt.figure(figsize=(11, 4))
    -plt.subplot(121)
    -plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    -plt.subplot(122)
    -plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

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









    -

    Final regressor code

    - - -
    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    -
    -tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
    -tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
    -tree_reg1.fit(X, y)
    -tree_reg2.fit(X, y)
    -
    -def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
    -    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
    -    y_pred = tree_reg.predict(x1)
    -    plt.axis(axes)
    -    plt.xlabel("$x_1$", fontsize=18)
    -    if ylabel:
    -        plt.ylabel(ylabel, fontsize=18, rotation=0)
    -    plt.plot(X, y, "b.")
    -    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
    -
    -plt.figure(figsize=(11, 4))
    -plt.subplot(121)
    -plot_regression_predictions(tree_reg1, X, y)
    -for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    -    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
    -plt.text(0.21, 0.65, "Depth=0", fontsize=15)
    -plt.text(0.01, 0.2, "Depth=1", fontsize=13)
    -plt.text(0.65, 0.8, "Depth=1", fontsize=13)
    -plt.legend(loc="upper center", fontsize=18)
    -plt.title("max_depth=2", fontsize=14)
    -
    -plt.subplot(122)
    -plot_regression_predictions(tree_reg2, X, y, ylabel=None)
    -for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    -    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
    -for split in (0.0458, 0.1298, 0.2873, 0.9040):
    -    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
    -plt.text(0.3, 0.5, "Depth=2", fontsize=13)
    -plt.title("max_depth=3", fontsize=14)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    tree_reg1 = DecisionTreeRegressor(random_state=42)
    -tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
    -tree_reg1.fit(X, y)
    -tree_reg2.fit(X, y)
    -
    -x1 = np.linspace(0, 1, 500).reshape(-1, 1)
    -y_pred1 = tree_reg1.predict(x1)
    -y_pred2 = tree_reg2.predict(x1)
    -
    -plt.figure(figsize=(11, 4))
    -
    -plt.subplot(121)
    -plt.plot(X, y, "b.")
    -plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
    -plt.axis([0, 1, -0.2, 1.1])
    -plt.xlabel("$x_1$", fontsize=18)
    -plt.ylabel("$y$", fontsize=18, rotation=0)
    -plt.legend(loc="upper center", fontsize=18)
    -plt.title("No restrictions", fontsize=14)
    -
    -plt.subplot(122)
    -plt.plot(X, y, "b.")
    -plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
    -plt.axis([0, 1, -0.2, 1.1])
    -plt.xlabel("$x_1$", fontsize=18)
    -plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    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)
    • -
    • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
    • -
    • No feature normalization needed
    • -
    • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
    • -
    • Can model nonlinear relationships
    • -
    • Can model interactions between the different descriptive features
    • -
    • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
    • -
    -









    -

    Disadvantages

    - -
      -
    • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
    • -
    • If continuous features are used the tree may become quite large and hence less interpretable
    • -
    • Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
    • -
    • Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
    • -
    • Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
    • -
    • If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
    • -
    • Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
    • -
    -

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

    - -









    -

    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.

    - -









    -

    An Overview of Ensemble Methods

    - -

    -
    -

    -
    -

    - -









    -

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

    - -









    -

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

    - -









    -

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









    -

    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.

    - -









    -

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

    - -









    -

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









    -

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









    -

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









    -

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









    -

    Random forests

    - -

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

    - -

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

    - -

    A fresh sample of \( m \) predictors is -taken at each split, and typically we choose -

    - -$$ -m\approx \sqrt{p}. -$$ - -

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

    - -

    The reason for this is rather clever. Suppose that there is one very -strong predictor in the data set, along with a number of other -moderately strong predictors. Then in the collection of bagged -variable importance random forest trees, most or all of the trees will -use this strong predictor in the top split. Consequently, all of the -bagged trees will look quite similar to each other. Hence the -predictions from the bagged trees will be highly correlated. -Unfortunately, averaging many highly correlated quantities does not -lead to as large of a reduction in variance as averaging many -uncorrelated 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.

    -
      -
    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. -
        3. pick the best split point among the \( m \) features using for example the CART algorithm and create a new node
        4. -
        5. split the node into daughter nodes
        6. -
        -
      -
    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. -
    -









    -

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

    - -

    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

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









    Boosting, a Bird's Eye View

    diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html index 9470b8531..5ccfffec7 100644 --- a/doc/pub/week45/html/week45.html +++ b/doc/pub/week45/html/week45.html @@ -141,175 +141,6 @@ div.toc p,a {
    @@ -417,8 +248,8 @@ MathJax.Hub.Config({

    Overview of week 45

      -
    • Thursday: Basics of Decision Trees, Bagging and Voting
    • -
    • Friday: More on Bagging, Voting, Random Forests and start Boosting
    • +
    • Thursday: Boosting methods, froma AdaBoost to Gradient boosting
    • +
    • Friday: Gradient boosting and discussion of Decision trees and ensemble methods
    Videos @@ -434,2270 +265,11 @@ MathJax.Hub.Config({ 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.
    2. +
    -









    -

    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, -classification and regression tasks. -

    - -

    The main idea of decision trees -is to find those descriptive features which contain the most -information regarding the target feature and then split the dataset -along the values of these features such that the target feature values -for the resulting underlying datasets are as pure as possible. -

    - -

    The descriptive features which reproduce best the target/output features are normally said -to be the most informative ones. The process of finding the most -informative feature is done until we accomplish a stopping criteria -where we then finally end up in so called leaf nodes. -

    - -









    -

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

    - -









    -

    General Features

    - -

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

    - -
      -
    • A leaf provides the classification of a given instance.
    • -
    • A node specifies a test of some attribute of the instance.
    • -
    • A branch corresponds to a possible values of an attribute.
    • -
    • An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
    • -
    -

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

    - -









    -

    How do we set it up?

    - -

    In simplified terms, the process of training a decision tree and -predicting the target features of query instances is as follows: -

    - -
      -
    1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
    2. -
    3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
    4. -
    5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
    6. -
    7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
    8. -
    -

    Then we are essentially done!

    - -









    -

    Decision trees and Regression

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    -
    -steps=250
    -
    -distance=0
    -x=0
    -distance_list=[]
    -steps_list=[]
    -while x<steps:
    -    distance+=np.random.randint(-1,2)
    -    distance_list.append(distance)
    -    x+=1
    -    steps_list.append(x)
    -plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
    -
    -steps_list=np.asarray(steps_list)
    -distance_list=np.asarray(distance_list)
    -
    -X=steps_list[:,np.newaxis]
    -
    -#Polynomial fits
    -
    -#Degree 2
    -poly_features=PolynomialFeatures(degree=2, include_bias=False)
    -X_poly=poly_features.fit_transform(X)
    -
    -lin_reg=LinearRegression()
    -poly_fit=lin_reg.fit(X_poly,distance_list)
    -b=lin_reg.coef_
    -c=lin_reg.intercept_
    -print ("2nd degree coefficients:")
    -print ("zero power: ",c)
    -print ("first power: ", b[0])
    -print ("second power: ",b[1])
    -
    -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
    -plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
    -plt.title("Polynomial Regression")
    -
    -plt.xlabel("Steps")
    -plt.ylabel("Distance")
    -
    -#Degree 10
    -poly_features10=PolynomialFeatures(degree=10, include_bias=False)
    -X_poly10=poly_features10.fit_transform(X)
    -
    -poly_fit10=lin_reg.fit(X_poly10,distance_list)
    -
    -y_plot=poly_fit10.predict(X_poly10)
    -plt.plot(X, y_plot, color='black', label="10th Degree Fit")
    -
    -plt.legend()
    -plt.show()
    -
    -
    -#Decision Tree Regression
    -from sklearn.tree import DecisionTreeRegressor
    -regr_1=DecisionTreeRegressor(max_depth=2)
    -regr_2=DecisionTreeRegressor(max_depth=5)
    -regr_3=DecisionTreeRegressor(max_depth=7)
    -regr_1.fit(X, distance_list)
    -regr_2.fit(X, distance_list)
    -regr_3.fit(X, distance_list)
    -
    -X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
    -y_1 = regr_1.predict(X_test)
    -y_2 = regr_2.predict(X_test)
    -y_3=regr_3.predict(X_test)
    -
    -# Plot the results
    -plt.figure()
    -plt.scatter(X, distance_list, s=2.5, c="black", label="data")
    -plt.plot(X_test, y_1, color="red",
    -         label="max_depth=2", linewidth=2)
    -plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
    -plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
    -
    -plt.xlabel("Data")
    -plt.ylabel("Darget")
    -plt.title("Decision Tree Regression")
    -plt.legend()
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

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

    How do we construct the regions \( R_1,\dots,R_J \)? In theory, the -regions could have any shape. However, we choose to divide the -predictor space into high-dimensional rectangles, or boxes, for -simplicity and for ease of interpretation of the resulting predictive -model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the -MSE, given by -

    - -$$ -\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, -$$ - -

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

    - -









    -

    A top-down approach, recursive binary splitting

    - -

    Unfortunately, it is computationally infeasible to consider every -possible partition of the feature space into \( J \) boxes. The common -strategy is to take a top-down approach -

    - -

    The approach is top-down because it begins at the top of the tree (all -observations belong to a single region) and then successively splits -the predictor space; each split is indicated via two new branches -further down on the tree. It is greedy because at each step of the -tree-building process, the best split is made at that particular step, -rather than looking ahead and picking a split that will lead to a -better tree in some future step. -

    - -









    -

    Making a tree

    - -

    In order to implement the recursive binary splitting we start by selecting -the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) -

    -$$ -\left\{X\vert x_j < s\right\}, -$$ - -

    and

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

    so that we obtain the lowest MSE, that is

    -$$ -\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, -$$ - -

    which we want to minimize by considering all predictors -\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for -each predictor. These values could be determined by randomly assigned -numbers or by starting at the midpoint and then proceed till we find -an optimal value. -

    - -

    For any \( j \) and \( s \), we define the pair of half-planes where -\( \overline{y}_{R_1} \) is the mean response for the training -observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean -response for the training observations in \( R_2(j,s) \). -

    - -

    Finding the values of \( j \) and \( s \) that minimize the above equation can be -done quite quickly, especially when the number of features \( p \) is not -too large. -

    - -

    Next, we repeat the process, looking -for the best predictor and best cutpoint in order to split the data -further so as to minimize the MSE within each of the resulting -regions. However, this time, instead of splitting the entire predictor -space, we split one of the two previously identified regions. We now -have three regions. Again, we look to split one of these three regions -further, so as to minimize the MSE. The process continues until a -stopping criterion is reached; for instance, we may continue until no -region contains more than five observations. -

    - - -

    Pruning the tree

    - -

    The above procedure is rather straightforward, but leads often to -overfitting and unnecessarily large and complicated trees. The basic -idea is to grow a large tree \( T_0 \) and then prune it back in order to -obtain a subtree. A smaller tree with fewer splits (fewer regions) can -lead to smaller variance and better interpretation at the cost of a -little more bias. -

    - -

    The so-called Cost complexity pruning algorithm gives us a -way to do just this. Rather than considering every possible subtree, -we consider a sequence of trees indexed by a nonnegative tuning -parameter \( \alpha \). -

    - -

    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

    -$$ -\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, -$$ - -

    is as small as possible. Here \( \overline{T} \) is -the number of terminal nodes of the tree \( T \) , \( R_m \) is the -rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. -

    - -

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

    - -

    It turns out that as we increase \( \alpha \) from zero -branches get pruned from the tree in a nested and predictable fashion, -so obtaining the whole sequence of subtrees as a function of \( \alpha \) is -easy. We can select a value of \( \alpha \) using a validation set or using -cross-validation. We then return to the full data set and obtain the -subtree corresponding to \( \alpha \). -

    - -









    -

    Schematic Regression Procedure

    - -
    -Building a Regression Tree -

    - -

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









    -

    A Classification Tree

    - -

    A classification tree is very similar to a regression tree, except -that it is used to predict a qualitative response rather than a -quantitative one. Recall that for a regression tree, the predicted -response for an observation is given by the mean response of the -training observations that belong to the same terminal node. In -contrast, for a classification tree, we predict that each observation -belongs to the most commonly occurring class of training observations -in the region to which it belongs. In interpreting the results of a -classification tree, we are often interested not only in the class -prediction corresponding to a particular terminal node region, but -also in the class proportions among the training observations that -fall into that region. -

    - -









    -

    Growing a classification tree

    - -

    The task of growing a -classification tree is quite similar to the task of growing a -regression tree. Just as in the regression setting, we use recursive -binary splitting to grow a classification tree. However, in the -classification setting, the MSE cannot be used as a criterion for making -the binary splits. A natural alternative to MSE is the classification -error rate. Since we plan to assign an observation in a given region -to the most commonly occurring error rate class of training -observations in that region, the classification error rate is simply -the fraction of the training observations in that region that do not -belong to the most common class. -

    - -

    When building a classification tree, either the Gini index or the -entropy are typically used to evaluate the quality of a particular -split, since these two approaches are more sensitive to node purity -than is the classification error rate. -

    - -









    -

    Classification tree, how to split nodes

    - -

    If our targets are the outcome of a classification process that takes -for example \( k=1,2,\dots,K \) values, the only thing we need to think of -is to set up the splitting criteria for each node. -

    - -

    We define a PDF \( p_{mk} \) that represents the number of observations of -a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent -this likelihood function in terms of the proportion \( I(y_i=k) \) of -observations of this class in the region \( R_m \) as -

    - -$$ -p_{mk} = \frac{1}{N_m}\sum_{i\in R_m}I(y_i=k). -$$ - -

    We let \( p_{mk} \) represent the majority class of observations in region -\( m \). The three most common ways of splitting a node are given by -

    - -
      -
    • Misclassification error
    • -
    -$$ -\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}}. -$$ - - -









    -

    Gini Index (or Coefficient or Impurity)

    - -

    The Gini index \( g \) gives us the degree of probability of a specific -variable that is wrongly classified. -

    - -

    It takes values \( g \in [0,1] \),

    -
      -
    1. \( g=0 \) means a pure case where all elements belong to one class only.
    2. -
    3. A value \( g=1 \) means that all elements are randomly distributed across various classes.
    4. -
    5. A value \( g=0.5 \) means that the elements in a node are uniformly distributed across classes.
    6. -
    -

    It favors binary splitting.

    - -









    -

    Why binary splits?

    - -

    It is custom to split to a tree uising binary splits. The reason is -that multiway splits fragment the data too quickly, leaving -insufficient data at the next level down. Multiway splits can be -achieved by a series of binary split and this is normally preferred. -

    - -









    -

    Computing a Tree using the Gini Index

    - -

    Consider the following example with attributes/features and two -possible outcomes (classes) for each attribute. Assume we wish to find some -correlations between the average grade of a student as function of the -number of hours studied and hours slept. We want also to correlate the -grade in a given course with the general trend, whether the students -recently has gotten grades below average or above. -

    - -

    We have three features/attributes

    -
      -
    1. Trend of average grades before present course, classified as either below or above the average grade of the whole class
    2. -
    3. The number of hours studies, classified again as either higher (more than 3 hours per day) or lower . Here we have used a standard for one \( ECTS \) which is scaled to 25-30 hours of work for a semester which lasts 18 weeks, with 15 weeks of lectures and 3 weeks for exams, assuming a total of 30 ECTS per semester.
    4. -
    5. The number of hours slept as high for more than \( 8 \) hours and below for less than 8 hours of sleep, classified again as either high or low
    6. -
    7. The final grade whether it is above or below average
    8. -
    -









    -

    The Table

    - - - - - - - - - - - - - - - - - -
    Grade Trend Hours slept Hours Studied Grade
    Above Low High Above
    Below High Low Below
    Above Low High Above
    Above High High Above
    Below Low High Below
    Above Low Low Below
    Below High High Below
    Below Low High Below
    Above Low Low Below
    Above High High Above
    - -









    -

    Computing the various Gini Indices

    - -

    In computations we will translate all classes into numbers. Being -these binary classes, they can easily be split into ones and zeros. -

    - -
    -Gini index for Average trend -

    -

    See handwritten notes for Thursday November 11

    -
    - - -









    -

    Computing the various Gini Indices, Hours slept

    - -
    -Gini index for hour slept -

    -

    See handwritten notes for Thursday November 11

    -
    - - -









    -

    Computing the various Gini Indices, Hours studied

    - -
    -Gini index for hour studied -

    -

    See handwritten notes for Thursday November 11

    -
    - - -

    For final tree, see the above handwritten notes

    - -









    -

    A possible code using Scikit-Learn

    - - - -
    -
    -
    -
    -
    -
    # 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)
    -
    -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')
    -
    -infile = open(data_path("grades.csv"),'r')
    -
    -# Read the experimental data with Pandas
    -from IPython.display import display
    -grades = pd.read_csv(infile,names = ('Trend','Sleep','Studied','Grade'))
    -grades = pd.DataFrame(grades)
    -
    -# Features and targets
    -X = grades.loc[:, grades.columns != 'Grade'].values
    -y = grades.loc[:, grades.columns == 'Grade'].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/grade.dot",
    -    rounded=True,
    -    filled=True
    -)
    -cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'
    -os.system(cmd)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Visualizing Trees, More examples

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









    -

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









    -

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









    -

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









    -

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

    - -









    -

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

    - -









    -

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

    - -









    -

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









    -

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









    -

    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']))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

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

    - -









    -

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









    -

    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
    -
    -
    -from sklearn.svm import SVC
    -from sklearn import datasets
    -from sklearn.tree import DecisionTreeClassifier
    -from sklearn.datasets import make_moons
    -from sklearn.tree import export_graphviz
    -
    -Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
    -
    -deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
    -deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
    -deep_tree_clf1.fit(Xm, ym)
    -deep_tree_clf2.fit(Xm, ym)
    -
    -
    -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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    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)
    -
    -plt.figure(figsize=(11, 4))
    -plt.subplot(121)
    -plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    -plt.subplot(122)
    -plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

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









    -

    Final regressor code

    - - -
    -
    -
    -
    -
    -
    from sklearn.tree import DecisionTreeRegressor
    -
    -tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
    -tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
    -tree_reg1.fit(X, y)
    -tree_reg2.fit(X, y)
    -
    -def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
    -    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
    -    y_pred = tree_reg.predict(x1)
    -    plt.axis(axes)
    -    plt.xlabel("$x_1$", fontsize=18)
    -    if ylabel:
    -        plt.ylabel(ylabel, fontsize=18, rotation=0)
    -    plt.plot(X, y, "b.")
    -    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
    -
    -plt.figure(figsize=(11, 4))
    -plt.subplot(121)
    -plot_regression_predictions(tree_reg1, X, y)
    -for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    -    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
    -plt.text(0.21, 0.65, "Depth=0", fontsize=15)
    -plt.text(0.01, 0.2, "Depth=1", fontsize=13)
    -plt.text(0.65, 0.8, "Depth=1", fontsize=13)
    -plt.legend(loc="upper center", fontsize=18)
    -plt.title("max_depth=2", fontsize=14)
    -
    -plt.subplot(122)
    -plot_regression_predictions(tree_reg2, X, y, ylabel=None)
    -for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    -    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
    -for split in (0.0458, 0.1298, 0.2873, 0.9040):
    -    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
    -plt.text(0.3, 0.5, "Depth=2", fontsize=13)
    -plt.title("max_depth=3", fontsize=14)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    tree_reg1 = DecisionTreeRegressor(random_state=42)
    -tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
    -tree_reg1.fit(X, y)
    -tree_reg2.fit(X, y)
    -
    -x1 = np.linspace(0, 1, 500).reshape(-1, 1)
    -y_pred1 = tree_reg1.predict(x1)
    -y_pred2 = tree_reg2.predict(x1)
    -
    -plt.figure(figsize=(11, 4))
    -
    -plt.subplot(121)
    -plt.plot(X, y, "b.")
    -plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
    -plt.axis([0, 1, -0.2, 1.1])
    -plt.xlabel("$x_1$", fontsize=18)
    -plt.ylabel("$y$", fontsize=18, rotation=0)
    -plt.legend(loc="upper center", fontsize=18)
    -plt.title("No restrictions", fontsize=14)
    -
    -plt.subplot(122)
    -plt.plot(X, y, "b.")
    -plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
    -plt.axis([0, 1, -0.2, 1.1])
    -plt.xlabel("$x_1$", fontsize=18)
    -plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
    -
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    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)
    • -
    • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
    • -
    • No feature normalization needed
    • -
    • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
    • -
    • Can model nonlinear relationships
    • -
    • Can model interactions between the different descriptive features
    • -
    • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
    • -
    -









    -

    Disadvantages

    - -
      -
    • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
    • -
    • If continuous features are used the tree may become quite large and hence less interpretable
    • -
    • Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
    • -
    • Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
    • -
    • Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
    • -
    • If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
    • -
    • Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
    • -
    -

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

    - -









    -

    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.

    - -









    -

    An Overview of Ensemble Methods

    - -

    -
    -

    -
    -

    - -









    -

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

    - -









    -

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

    - -









    -

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









    -

    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.

    - -









    -

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

    - -









    -

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









    -

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









    -

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









    -

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









    -

    Random forests

    - -

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

    - -

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

    - -

    A fresh sample of \( m \) predictors is -taken at each split, and typically we choose -

    - -$$ -m\approx \sqrt{p}. -$$ - -

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

    - -

    The reason for this is rather clever. Suppose that there is one very -strong predictor in the data set, along with a number of other -moderately strong predictors. Then in the collection of bagged -variable importance random forest trees, most or all of the trees will -use this strong predictor in the top split. Consequently, all of the -bagged trees will look quite similar to each other. Hence the -predictions from the bagged trees will be highly correlated. -Unfortunately, averaging many highly correlated quantities does not -lead to as large of a reduction in variance as averaging many -uncorrelated 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.

    -
      -
    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. -
        3. pick the best split point among the \( m \) features using for example the CART algorithm and create a new node
        4. -
        5. split the node into daughter nodes
        6. -
        -
      -
    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. -
    -









    -

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

    - -

    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

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









    Boosting, a Bird's Eye View

    diff --git a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz index 9ef82a9ad..cdc809077 100644 Binary files a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz and b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz differ diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb index c9384f2dc..bbfc22b26 100644 --- a/doc/pub/week45/ipynb/week45.ipynb +++ b/doc/pub/week45/ipynb/week45.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "db17fb40", + "id": "3edc7c2f", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "4ec2b0df", + "id": "e41ba5f8", "metadata": { "editable": true }, @@ -22,23 +22,23 @@ "# Week 45: Decisions Trees, Random Forests, Bagging and Boosting\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Aug 23, 2022**\n", + "Date: **Nov 5, 2022**\n", "\n", "Copyright 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" ] }, { "cell_type": "markdown", - "id": "932b9d5b", + "id": "75e08e99", "metadata": { "editable": true }, "source": [ "## Overview of week 45\n", "\n", - "* Thursday: Basics of Decision Trees, Bagging and Voting\n", + "* Thursday: Boosting methods, froma AdaBoost to Gradient boosting\n", "\n", - "* Friday: More on Bagging, Voting, Random Forests and start Boosting\n", + "* Friday: Gradient boosting and discussion of Decision trees and ensemble methods\n", "\n", "**Videos.**\n", "\n", @@ -48,2605 +48,12 @@ "\n", "**Reading.**\n", "\n", - "1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion." + "1." ] }, { "cell_type": "markdown", - "id": "cdef55b7", - "metadata": { - "editable": true - }, - "source": [ - "## Decision trees, overarching aims\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", - "random forests and more) to one of the most popular supervised\n", - "algorithms nowadays, the extreme gradient boosting, or just\n", - "XGBoost. But let us start with the simplest possible ingredient.\n", - "\n", - "Decision trees are supervised learning algorithms used for both,\n", - "classification and regression tasks.\n", - "\n", - "The main idea of decision trees\n", - "is to find those descriptive features which contain the most\n", - "**information** regarding the target feature and then split the dataset\n", - "along the values of these features such that the target feature values\n", - "for the resulting underlying datasets are as pure as possible.\n", - "\n", - "The descriptive features which reproduce best the target/output features are normally said\n", - "to be the most informative ones. The process of finding the **most\n", - "informative** feature is done until we accomplish a stopping criteria\n", - "where we then finally end up in so called **leaf nodes**." - ] - }, - { - "cell_type": "markdown", - "id": "670dc680", - "metadata": { - "editable": true - }, - "source": [ - "## Basics of a tree\n", - "\n", - "A decision tree is typically divided into a **root node**, the **interior nodes**,\n", - "and the final **leaf nodes** or just **leaves**. These entities are then connected by so-called **branches**.\n", - "\n", - "The leaf nodes\n", - "contain the predictions we will make for new query instances presented\n", - "to our trained model. This is possible since the model has \n", - "learned the underlying structure of the training data and hence can,\n", - "given some assumptions, make predictions about the target feature value\n", - "(class) of unseen query instances." - ] - }, - { - "cell_type": "markdown", - "id": "5833bbd3", - "metadata": { - "editable": true - }, - "source": [ - "## A Sketch of a Tree, Regression problem\n", - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "086a7a69", - "metadata": { - "editable": true - }, - "source": [ - "## A Sketch of a Tree, Classification problem\n", - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "7aa50b30", - "metadata": { - "editable": true - }, - "source": [ - "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n", - "\n", - "\n", - "\n", - "\n", - "

    Figure 1:

    \n", - "\n", - "\n", - "This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using **Scikit-Learn**'s decision tree classifier. Here we have used the so-called **gini** index (see below) to split the various branches." - ] - }, - { - "cell_type": "markdown", - "id": "9cf889ab", - "metadata": { - "editable": true - }, - "source": [ - "## General Features\n", - "\n", - "The overarching approach to decision trees is a top-down approach.\n", - "\n", - "* A leaf provides the classification of a given instance.\n", - "\n", - "* A node specifies a test of some attribute of the instance.\n", - "\n", - "* A branch corresponds to a possible values of an attribute.\n", - "\n", - "* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.\n", - "\n", - "This process is then repeated for the subtree rooted at the new\n", - "node." - ] - }, - { - "cell_type": "markdown", - "id": "18292295", - "metadata": { - "editable": true - }, - "source": [ - "## How do we set it up?\n", - "\n", - "In simplified terms, the process of training a decision tree and\n", - "predicting the target features of query instances is as follows:\n", - "\n", - "1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature\n", - "\n", - "2. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process\n", - "\n", - "3. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances\n", - "\n", - "4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n", - "\n", - "Then we are essentially done!" - ] - }, - { - "cell_type": "markdown", - "id": "6f672f93", - "metadata": { - "editable": true - }, - "source": [ - "## Decision trees and Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "7d730382", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "steps=250\n", - "\n", - "distance=0\n", - "x=0\n", - "distance_list=[]\n", - "steps_list=[]\n", - "while x\n", - "\n", - "Grade Trend Hours slept Hours Studied Grade \n", - "\n", - "\n", - " Above Low High Above \n", - " Below High Low Below \n", - " Above Low High Above \n", - " Above High High Above \n", - " Below Low High Below \n", - " Above Low Low Below \n", - " Below High High Below \n", - " Below Low High Below \n", - " Above Low Low Below \n", - " Above High High Above \n", - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "3d309daf", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the various Gini Indices\n", - "\n", - "In computations we will translate all classes into numbers. Being\n", - "these binary classes, they can easily be split into ones and zeros.\n", - "\n", - "**Gini index for Average trend.**\n", - "\n", - "See handwritten notes for Thursday November 11" - ] - }, - { - "cell_type": "markdown", - "id": "47899942", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the various Gini Indices, Hours slept\n", - "\n", - "**Gini index for hour slept.**\n", - "\n", - "See handwritten notes for Thursday November 11" - ] - }, - { - "cell_type": "markdown", - "id": "5ac9e8ae", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the various Gini Indices, Hours studied\n", - "\n", - "**Gini index for hour studied.**\n", - "\n", - "See handwritten notes for Thursday November 11\n", - "\n", - "For final tree, see the above handwritten notes" - ] - }, - { - "cell_type": "markdown", - "id": "51e2ac77", - "metadata": { - "editable": true - }, - "source": [ - "## A possible code using Scikit-Learn" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "1b07cb3e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.tree import export_graphviz\n", - "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", - "from sklearn.compose import ColumnTransformer\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"grades.csv\"),'r')\n", - "\n", - "# Read the experimental data with Pandas\n", - "from IPython.display import display\n", - "grades = pd.read_csv(infile,names = ('Trend','Sleep','Studied','Grade'))\n", - "grades = pd.DataFrame(grades)\n", - "\n", - "# Features and targets\n", - "X = grades.loc[:, grades.columns != 'Grade'].values\n", - "y = grades.loc[:, grades.columns == 'Grade'].values\n", - "\n", - "# Create the encoder.\n", - "encoder = OneHotEncoder(handle_unknown=\"ignore\")\n", - "# Assume for simplicity all features are categorical.\n", - "encoder.fit(X) \n", - "# Apply the encoder.\n", - "X = encoder.transform(X)\n", - "print(X)\n", - "# Then do a Classification tree\n", - "tree_clf = DecisionTreeClassifier(max_depth=2)\n", - "tree_clf.fit(X, y)\n", - "print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n", - "#transfer to a decision tree graph\n", - "export_graphviz(\n", - " tree_clf,\n", - " out_file=\"DataFiles/grade.dot\",\n", - " rounded=True,\n", - " filled=True\n", - ")\n", - "cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'\n", - "os.system(cmd)" - ] - }, - { - "cell_type": "markdown", - "id": "6dc5d834", - "metadata": { - "editable": true - }, - "source": [ - "## Visualizing Trees, More examples" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "e5eae0aa", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import os\n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.metrics import confusion_matrix\n", - "from sklearn.tree import export_graphviz\n", - "\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import pandas as pd\n", - "import numpy as np\n", - "\n", - "\n", - "cancer = load_breast_cancer()\n", - "X = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n", - "print(X)\n", - "y = pd.Categorical.from_codes(cancer.target, cancer.target_names)\n", - "y = pd.get_dummies(y)\n", - "print(y)\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n", - "tree_clf = DecisionTreeClassifier(max_depth=5)\n", - "tree_clf.fit(X_train, y_train)\n", - "\n", - "export_graphviz(\n", - " tree_clf,\n", - " out_file=\"DataFiles/cancer.dot\",\n", - " feature_names=cancer.feature_names,\n", - " class_names=cancer.target_names,\n", - " rounded=True,\n", - " filled=True\n", - ")\n", - "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n", - "os.system(cmd)" - ] - }, - { - "cell_type": "markdown", - "id": "a460a7dd", - "metadata": { - "editable": true - }, - "source": [ - "## Visualizing the Tree, The Moons" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "b14b8dfa", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.datasets import make_moons\n", - "from sklearn.tree import export_graphviz\n", - "from pydot import graph_from_dot_data\n", - "import pandas as pd\n", - "import os\n", - "\n", - "np.random.seed(42)\n", - "X, y = make_moons(n_samples=100, noise=0.25, random_state=53)\n", - "X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)\n", - "tree_clf = DecisionTreeClassifier(max_depth=5)\n", - "tree_clf.fit(X_train, y_train)\n", - "\n", - "export_graphviz(\n", - " tree_clf,\n", - " out_file=\"DataFiles/moons.dot\",\n", - " rounded=True,\n", - " filled=True\n", - ")\n", - "cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'\n", - "os.system(cmd)" - ] - }, - { - "cell_type": "markdown", - "id": "e255d841", - "metadata": { - "editable": true - }, - "source": [ - "## Other ways of visualizing the trees\n", - "\n", - "**Scikit-Learn** has also another way to visualize the trees which is very useful, here with the Iris data." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "5248c4d7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.datasets import load_iris\n", - "from sklearn import tree\n", - "X, y = load_iris(return_X_y=True)\n", - "tree_clf = tree.DecisionTreeClassifier()\n", - "tree_clf = tree_clf.fit(X, y)\n", - "# and then plot the tree\n", - "tree.plot_tree(tree_clf)" - ] - }, - { - "cell_type": "markdown", - "id": "80eb5247", - "metadata": { - "editable": true - }, - "source": [ - "## Printing out as text\n", - "\n", - "Alternatively, the tree can also be exported in textual format with the function exporttext.\n", - "This method doesn’t require the installation of external libraries and is more compact:" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "5b16523c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.datasets import load_iris\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.tree import export_text\n", - "iris = load_iris()\n", - "decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)\n", - "decision_tree = decision_tree.fit(iris.data, iris.target)\n", - "r = export_text(decision_tree, feature_names=iris['feature_names'])\n", - "print(r)" - ] - }, - { - "cell_type": "markdown", - "id": "e06f89e0", - "metadata": { - "editable": true - }, - "source": [ - "## Algorithms for Setting up Decision Trees\n", - "\n", - "Two algorithms stand out in the set up of decision trees:\n", - "1. The CART (Classification And Regression Tree) algorithm for both classification and regression\n", - "\n", - "2. The ID3 algorithm based on the computation of the information gain for classification\n", - "\n", - "We discuss both algorithms with applications here. The popular library\n", - "**Scikit-Learn** uses the CART algorithm. For classification problems\n", - "you can use either the **gini** index or the **entropy** to split a tree\n", - "in two branches." - ] - }, - { - "cell_type": "markdown", - "id": "9dd265ec", - "metadata": { - "editable": true - }, - "source": [ - "## 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", - "This could be for example a threshold set by a number below a certain circumference of a malign tumor.\n", - "\n", - "How do we find these two quantities?\n", - "We search for the pair $(k,t_k)$ that produces the purest subset using for example the **gini** factor $G$.\n", - "The cost function it tries to minimize is then" - ] - }, - { - "cell_type": "markdown", - "id": "61cfa4b0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "96d31486", - "metadata": { - "editable": true - }, - "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", - "\n", - "Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets\n", - "and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the\n", - "$max\\_depth$ hyperparameter), or if it cannot find a split that will reduce impurity. A few other\n", - "hyperparameters control additional stopping conditions such as the $min\\_samples\\_split$,\n", - "$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$." - ] - }, - { - "cell_type": "markdown", - "id": "f4288b07", - "metadata": { - "editable": true - }, - "source": [ - "## 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", - "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" - ] - }, - { - "cell_type": "markdown", - "id": "a5acbc94", - "metadata": { - "editable": true - }, - "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", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4c2a0a69", - "metadata": { - "editable": true - }, - "source": [ - "Here the MSE for a specific node is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "79c95fcd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0030a54b", - "metadata": { - "editable": true - }, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "id": "7ffe431c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dcae142e", - "metadata": { - "editable": true - }, - "source": [ - "the mean value of all observations in a specific node.\n", - "\n", - "Without any regularization, the regression task for decision trees, \n", - "just like for classification tasks, is prone to overfitting." - ] - }, - { - "cell_type": "markdown", - "id": "80f06b52", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the Gini index\n", - "\n", - "The example we will look at is a classical one in many Machine\n", - "Learning applications. Based on various meteorological features, we\n", - "have several so-called attributes which decide whether we at the end\n", - "will do some outdoor activity like skiing, going for a bike ride etc\n", - "etc. The table here contains the feautures **outlook**, **temperature**,\n", - "**humidity** and **wind**. The target or output is whether we ride\n", - "(True=1) or whether we do something else that day (False=0). The\n", - "attributes for each feature are then sunny, overcast and rain for the\n", - "outlook, hot, cold and mild for temperature, high and normal for\n", - "humidity and weak and strong for wind.\n", - "\n", - "The table here summarizes the various attributes and\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
    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
    " - ] - }, - { - "cell_type": "markdown", - "id": "ab6d774f", - "metadata": { - "editable": true - }, - "source": [ - "## Simple Python Code to read in Data and perform Classification" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "bd87fe11", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.tree import export_graphviz\n", - "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", - "from sklearn.compose import ColumnTransformer\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"rideclass.csv\"),'r')\n", - "\n", - "# Read the experimental data with Pandas\n", - "from IPython.display import display\n", - "ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))\n", - "ridedata = pd.DataFrame(ridedata)\n", - "\n", - "# Features and targets\n", - "X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n", - "y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n", - "\n", - "# Create the encoder.\n", - "encoder = OneHotEncoder(handle_unknown=\"ignore\")\n", - "# Assume for simplicity all features are categorical.\n", - "encoder.fit(X) \n", - "# Apply the encoder.\n", - "X = encoder.transform(X)\n", - "print(X)\n", - "# Then do a Classification tree\n", - "tree_clf = DecisionTreeClassifier(max_depth=2)\n", - "tree_clf.fit(X, y)\n", - "print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n", - "#transfer to a decision tree graph\n", - "export_graphviz(\n", - " tree_clf,\n", - " out_file=\"DataFiles/ride.dot\",\n", - " rounded=True,\n", - " filled=True\n", - ")\n", - "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n", - "os.system(cmd)" - ] - }, - { - "cell_type": "markdown", - "id": "43daa955", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the Gini Factor\n", - "\n", - "The above functions (gini, entropy and misclassification error) are\n", - "important components of the so-called CART algorithm. We will discuss\n", - "this algorithm below after we have discussed the information gain\n", - "algorithm ID3.\n", - "\n", - "In the example here we have converted all our attributes into numerical values $0,1,2$ etc." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "0ac83107", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Split a dataset based on an attribute and an attribute value\n", - "def test_split(index, value, dataset):\n", - "\tleft, right = list(), list()\n", - "\tfor row in dataset:\n", - "\t\tif row[index] < value:\n", - "\t\t\tleft.append(row)\n", - "\t\telse:\n", - "\t\t\tright.append(row)\n", - "\treturn left, right\n", - " \n", - "# Calculate the Gini index for a split dataset\n", - "def gini_index(groups, classes):\n", - "\t# count all samples at split point\n", - "\tn_instances = float(sum([len(group) for group in groups]))\n", - "\t# sum weighted Gini index for each group\n", - "\tgini = 0.0\n", - "\tfor group in groups:\n", - "\t\tsize = float(len(group))\n", - "\t\t# avoid divide by zero\n", - "\t\tif size == 0:\n", - "\t\t\tcontinue\n", - "\t\tscore = 0.0\n", - "\t\t# score the group based on the score for each class\n", - "\t\tfor class_val in classes:\n", - "\t\t\tp = [row[-1] for row in group].count(class_val) / size\n", - "\t\t\tscore += p * p\n", - "\t\t# weight the group score by its relative size\n", - "\t\tgini += (1.0 - score) * (size / n_instances)\n", - "\treturn gini\n", - "\n", - "# Select the best split point for a dataset\n", - "def get_split(dataset):\n", - "\tclass_values = list(set(row[-1] for row in dataset))\n", - "\tb_index, b_value, b_score, b_groups = 999, 999, 999, None\n", - "\tfor index in range(len(dataset[0])-1):\n", - "\t\tfor row in dataset:\n", - "\t\t\tgroups = test_split(index, row[index], dataset)\n", - "\t\t\tgini = gini_index(groups, class_values)\n", - "\t\t\tprint('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))\n", - "\t\t\tif gini < b_score:\n", - "\t\t\t\tb_index, b_value, b_score, b_groups = index, row[index], gini, groups\n", - "\treturn {'index':b_index, 'value':b_value, 'groups':b_groups}\n", - " \n", - "dataset = [[0,0,0,0,0],\n", - " [0,0,0,1,1],\n", - " [1,0,0,0,1],\n", - " [2,1,0,0,1],\n", - " [2,2,1,0,1],\n", - " [2,2,1,1,0],\n", - " [1,2,1,1,1],\n", - " [0,1,0,0,0],\n", - " [0,2,1,0,1],\n", - " [2,1,1,0,1],\n", - " [0,1,1,1,1],\n", - " [1,1,0,1,1],\n", - " [1,0,1,0,1],\n", - " [2,1,0,1,0]]\n", - "\n", - "split = get_split(dataset)\n", - "print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))" - ] - }, - { - "cell_type": "markdown", - "id": "c78f6b56", - "metadata": { - "editable": true - }, - "source": [ - "## Entropy and the ID3 algorithm\n", - "\n", - "The ID3 algorithm learns decision trees by constructing\n", - "them in a top down way, beginning with the question **which attribute should be tested at the root of the tree**?\n", - "\n", - "1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.\n", - "\n", - "2. The best attribute is selected and used as the test at the root node of the tree.\n", - "\n", - "3. A descendant of the root node is then created for each possible value of this attribute.\n", - "\n", - "4. Training examples are sorted to the appropriate descendant node.\n", - "\n", - "5. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.\n", - "\n", - "6. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices. \n", - "\n", - "The ID3 algorithm selects which attribute to test at each node in the\n", - "tree.\n", - "\n", - "We would like to select the attribute that is most useful for classifying\n", - "examples.\n", - "\n", - "What is a good quantitative measure of the worth of an attribute?\n", - "\n", - "Information gain measures how well a given attribute separates the\n", - "training examples according to their target classification.\n", - "\n", - "The ID3 algorithm uses this information gain measure to select among the candidate\n", - "attributes at each step while growing the tree." - ] - }, - { - "cell_type": "markdown", - "id": "b8c96705", - "metadata": { - "editable": true - }, - "source": [ - "## Cancer Data again now with Decision Trees and other Methods" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "10c8e3b4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.svm import SVC\n", - "from sklearn.linear_model import LogisticRegression\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "# Logistic Regression\n", - "logreg = LogisticRegression(solver='lbfgs')\n", - "logreg.fit(X_train, y_train)\n", - "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", - "# Support vector machine\n", - "svm = SVC(gamma='auto', C=100)\n", - "svm.fit(X_train, y_train)\n", - "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n", - "# Decision Trees\n", - "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n", - "deep_tree_clf.fit(X_train, y_train)\n", - "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n", - "#now scale the data\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "# Logistic Regression\n", - "logreg.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", - "# Support Vector Machine\n", - "svm.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", - "# Decision Trees\n", - "deep_tree_clf.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "1bc9d4d6", - "metadata": { - "editable": true - }, - "source": [ - "## Another example, the moons again" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "3b590164", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from __future__ import division, print_function, unicode_literals\n", - "\n", - "# Common imports\n", - "import numpy as np\n", - "import os\n", - "\n", - "# to make this notebook's output stable across runs\n", - "np.random.seed(42)\n", - "\n", - "# To plot pretty figures\n", - "import matplotlib\n", - "import matplotlib.pyplot as plt\n", - "from matplotlib.colors import ListedColormap\n", - "plt.rcParams['axes.labelsize'] = 14\n", - "plt.rcParams['xtick.labelsize'] = 12\n", - "plt.rcParams['ytick.labelsize'] = 12\n", - "\n", - "\n", - "from sklearn.svm import SVC\n", - "from sklearn import datasets\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.datasets import make_moons\n", - "from sklearn.tree import export_graphviz\n", - "\n", - "Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)\n", - "\n", - "deep_tree_clf1 = DecisionTreeClassifier(random_state=42)\n", - "deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)\n", - "deep_tree_clf1.fit(Xm, ym)\n", - "deep_tree_clf2.fit(Xm, ym)\n", - "\n", - "\n", - "def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):\n", - " x1s = np.linspace(axes[0], axes[1], 100)\n", - " x2s = np.linspace(axes[2], axes[3], 100)\n", - " x1, x2 = np.meshgrid(x1s, x2s)\n", - " X_new = np.c_[x1.ravel(), x2.ravel()]\n", - " y_pred = clf.predict(X_new).reshape(x1.shape)\n", - " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n", - " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n", - " if not iris:\n", - " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n", - " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n", - " if plot_training:\n", - " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", label=\"Iris-Setosa\")\n", - " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", label=\"Iris-Versicolor\")\n", - " plt.plot(X[:, 0][y==2], X[:, 1][y==2], \"g^\", label=\"Iris-Virginica\")\n", - " plt.axis(axes)\n", - " if iris:\n", - " plt.xlabel(\"Petal length\", fontsize=14)\n", - " plt.ylabel(\"Petal width\", fontsize=14)\n", - " else:\n", - " plt.xlabel(r\"$x_1$\", fontsize=18)\n", - " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n", - " if legend:\n", - " plt.legend(loc=\"lower right\", fontsize=14)\n", - "plt.figure(figsize=(11, 4))\n", - "plt.subplot(121)\n", - "plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n", - "plt.title(\"No restrictions\", fontsize=16)\n", - "plt.subplot(122)\n", - "plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n", - "plt.title(\"min_samples_leaf = {}\".format(deep_tree_clf2.min_samples_leaf), fontsize=14)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "06763654", - "metadata": { - "editable": true - }, - "source": [ - "## Playing around with regions" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "fed932d7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "np.random.seed(6)\n", - "Xs = np.random.rand(100, 2) - 0.5\n", - "ys = (Xs[:, 0] > 0).astype(np.float32) * 2\n", - "\n", - "angle = np.pi/4\n", - "rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n", - "Xsr = Xs.dot(rotation_matrix)\n", - "\n", - "tree_clf_s = DecisionTreeClassifier(random_state=42)\n", - "tree_clf_s.fit(Xs, ys)\n", - "tree_clf_sr = DecisionTreeClassifier(random_state=42)\n", - "tree_clf_sr.fit(Xsr, ys)\n", - "\n", - "plt.figure(figsize=(11, 4))\n", - "plt.subplot(121)\n", - "plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n", - "plt.subplot(122)\n", - "plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "082490df", - "metadata": { - "editable": true - }, - "source": [ - "## Regression trees" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "fed48fd6", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Quadratic training set + noise\n", - "np.random.seed(42)\n", - "m = 200\n", - "X = np.random.rand(m, 1)\n", - "y = 4 * (X - 0.5) ** 2\n", - "y = y + np.random.randn(m, 1) / 10" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "e07a5961", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.tree import DecisionTreeRegressor\n", - "\n", - "tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n", - "tree_reg.fit(X, y)" - ] - }, - { - "cell_type": "markdown", - "id": "04d25c6f", - "metadata": { - "editable": true - }, - "source": [ - "## Final regressor code" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "ac2ea1c2", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.tree import DecisionTreeRegressor\n", - "\n", - "tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n", - "tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n", - "tree_reg1.fit(X, y)\n", - "tree_reg2.fit(X, y)\n", - "\n", - "def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n", - " x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n", - " y_pred = tree_reg.predict(x1)\n", - " plt.axis(axes)\n", - " plt.xlabel(\"$x_1$\", fontsize=18)\n", - " if ylabel:\n", - " plt.ylabel(ylabel, fontsize=18, rotation=0)\n", - " plt.plot(X, y, \"b.\")\n", - " plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", - "\n", - "plt.figure(figsize=(11, 4))\n", - "plt.subplot(121)\n", - "plot_regression_predictions(tree_reg1, X, y)\n", - "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n", - " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n", - "plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n", - "plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n", - "plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n", - "plt.legend(loc=\"upper center\", fontsize=18)\n", - "plt.title(\"max_depth=2\", fontsize=14)\n", - "\n", - "plt.subplot(122)\n", - "plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n", - "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n", - " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n", - "for split in (0.0458, 0.1298, 0.2873, 0.9040):\n", - " plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n", - "plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n", - "plt.title(\"max_depth=3\", fontsize=14)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "7fe38a5f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "tree_reg1 = DecisionTreeRegressor(random_state=42)\n", - "tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n", - "tree_reg1.fit(X, y)\n", - "tree_reg2.fit(X, y)\n", - "\n", - "x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n", - "y_pred1 = tree_reg1.predict(x1)\n", - "y_pred2 = tree_reg2.predict(x1)\n", - "\n", - "plt.figure(figsize=(11, 4))\n", - "\n", - "plt.subplot(121)\n", - "plt.plot(X, y, \"b.\")\n", - "plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", - "plt.axis([0, 1, -0.2, 1.1])\n", - "plt.xlabel(\"$x_1$\", fontsize=18)\n", - "plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n", - "plt.legend(loc=\"upper center\", fontsize=18)\n", - "plt.title(\"No restrictions\", fontsize=14)\n", - "\n", - "plt.subplot(122)\n", - "plt.plot(X, y, \"b.\")\n", - "plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", - "plt.axis([0, 1, -0.2, 1.1])\n", - "plt.xlabel(\"$x_1$\", fontsize=18)\n", - "plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "78ab944f", - "metadata": { - "editable": true - }, - "source": [ - "## Pros and cons of trees, pros\n", - "\n", - "* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)\n", - "\n", - "* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n", - "\n", - "* No feature normalization needed\n", - "\n", - "* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n", - "\n", - "* Can model nonlinear relationships\n", - "\n", - "* Can model interactions between the different descriptive features\n", - "\n", - "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)" - ] - }, - { - "cell_type": "markdown", - "id": "d0846616", - "metadata": { - "editable": true - }, - "source": [ - "## Disadvantages\n", - "\n", - "* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n", - "\n", - "* If continuous features are used the tree may become quite large and hence less interpretable\n", - "\n", - "* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented\n", - "\n", - "* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests\n", - "\n", - "* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. \n", - "\n", - "* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n", - "\n", - "* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain\n", - "\n", - "However, by aggregating many decision trees, using methods like\n", - "bagging, random forests, and boosting, the predictive performance of\n", - "trees can be substantially improved." - ] - }, - { - "cell_type": "markdown", - "id": "7a075199", - "metadata": { - "editable": true - }, - "source": [ - "## 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", - "a single decision tree, we often end up overfitting our training\n", - "data. This normally means that we have a high variance. Can we reduce\n", - "the variance of a statistical learning method?\n", - "\n", - "This leads us to a set of different methods that can combine different\n", - "machine learning algorithms or just use one of them to construct\n", - "forests and jungles of trees, homogeneous ones or heterogenous\n", - "ones. These methods are recognized by different names which we will\n", - "try to explain here. These are\n", - "\n", - "1. Voting classifiers\n", - "\n", - "2. Bagging and Pasting\n", - "\n", - "3. Random forests\n", - "\n", - "4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n", - "\n", - "We discuss these methods here." - ] - }, - { - "cell_type": "markdown", - "id": "b84e22c7", - "metadata": { - "editable": true - }, - "source": [ - "## An Overview of Ensemble Methods\n", - "\n", - "\n", - "\n", - "\n", - "

    Figure 1:

    \n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "d144431f", - "metadata": { - "editable": true - }, - "source": [ - "## Bagging\n", - "\n", - "The **plain** decision trees suffer from high\n", - "variance. This means that if we split the training data into two parts\n", - "at random, and fit a decision tree to both halves, the results that we\n", - "get could be quite different. In contrast, a procedure with low\n", - "variance will yield similar results if applied repeatedly to distinct\n", - "data sets; linear regression tends to have low variance, if the ratio\n", - "of $n$ to $p$ is moderately large. \n", - "\n", - "**Bootstrap aggregation**, or just **bagging**, is a\n", - "general-purpose procedure for reducing the variance of a statistical\n", - "learning method." - ] - }, - { - "cell_type": "markdown", - "id": "9ad28e89", - "metadata": { - "editable": true - }, - "source": [ - "## More bagging\n", - "\n", - "Bagging typically results in improved accuracy\n", - "over prediction using a single tree. Unfortunately, however, it can be\n", - "difficult to interpret the resulting model. Recall that one of the\n", - "advantages of decision trees is the attractive and easily interpreted\n", - "diagram that results.\n", - "\n", - "However, when we bag a large number of trees, it is no longer\n", - "possible to represent the resulting statistical learning procedure\n", - "using a single tree, and it is no longer clear which variables are\n", - "most important to the procedure. Thus, bagging improves prediction\n", - "accuracy at the expense of interpretability. Although the collection\n", - "of bagged trees is much more difficult to interpret than a single\n", - "tree, one can obtain an overall summary of the importance of each\n", - "predictor using the MSE (for bagging regression trees) or the Gini\n", - "index (for bagging classification trees). In the case of bagging\n", - "regression trees, we can record the total amount that the MSE is\n", - "decreased due to splits over a given predictor, averaged over all $B$ possible\n", - "trees. A large value indicates an important predictor. Similarly, in\n", - "the context of bagging classification trees, we can add up the total\n", - "amount that the Gini index is decreased by splits over a given\n", - "predictor, averaged over all $B$ trees." - ] - }, - { - "cell_type": "markdown", - "id": "05046bf5", - "metadata": { - "editable": true - }, - "source": [ - "## 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", - "a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$)." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "87ff8892", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "from sklearn.tree import DecisionTreeRegressor\n", - "\n", - "n = 1000\n", - "n_boostraps = 100\n", - "maxdepth = 10\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "error = np.zeros(maxdepth)\n", - "bias = np.zeros(maxdepth)\n", - "variance = np.zeros(maxdepth)\n", - "polydegree = np.zeros(maxdepth)\n", - "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "# we produce a simple tree first as benchmark, no scaling\n", - "simpletree = DecisionTreeRegressor(max_depth=3) \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, y_train)\n", - " model.fit(x_, y_)\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", - " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - " print('Polynomial degree:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " 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", - "print(mse_simpletree)\n", - "plt.xlim(1,maxdepth)\n", - "plt.plot(polydegree, error, label='MSE')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "save_fig(\"baggingboot\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "530055df", - "metadata": { - "editable": true - }, - "source": [ - "## Why Voting?\n", - "\n", - "The idea behind boosting, and voting as well can be phrased as follows:\n", - "**Can a group of people somehow arrive at highly\n", - "reasoned decisions, despite the weak judgement of the individual\n", - "members?**\n", - "\n", - "The aim is to create a good classifier by combining several weak classifiers.\n", - "**A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random.**\n", - "\n", - "The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.\n", - "In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in\n", - "each iteration. \n", - "\n", - "Decision trees play an important role as our weak classifier. They serve as the basic method." - ] - }, - { - "cell_type": "markdown", - "id": "4b371d5d", - "metadata": { - "editable": true - }, - "source": [ - "## Tossing coins\n", - "\n", - "The simplest case is a so-called voting ensemble. To illustrate this,\n", - "think of yourself tossing coins with a biased outcome of 51 per cent\n", - "for heads and 49% for tails. With only few tosses,\n", - "you may not clearly see this distribution for heads and tails. However, after some\n", - "thousands of tosses, there will be a clear majority of heads. With 2000 tosses\n", - "you should see approximately 1020 heads and 980 tails.\n", - "\n", - "We can then state that the outcome is a clear majority of heads. If\n", - "you do this ten thousand times, it is easy to see that there is a 97%\n", - "likelihood of a majority of heads.\n", - "\n", - "Another example would be to collect all polls before an\n", - "election. Different polls may show different likelihoods for a\n", - "candidate winning with say a majority of the popular vote. The majority vote\n", - "would then consist in many polls indicating that this candidate will\n", - "actually win.\n", - "\n", - "The example here shows how we can implement the coin tossing case,\n", - "clealry demostrating that after some tosses we see the [law of large](https://en.wikipedia.org/wiki/Law_of_large_numbers)\n", - "numbers kicking in." - ] - }, - { - "cell_type": "markdown", - "id": "a783b4a6", - "metadata": { - "editable": true - }, - "source": [ - "## Standard imports first" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "0a55830c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import pandas as pd\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.tree import export_graphviz\n", - "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", - "from sklearn.compose import ColumnTransformer\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')" - ] - }, - { - "cell_type": "markdown", - "id": "b1f44b12", - "metadata": { - "editable": true - }, - "source": [ - "## Simple Voting Example, head or tail" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "81ff3794", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "# Common imports\n", - "import numpy as np\n", - "import matplotlib\n", - "import matplotlib.pyplot as plt\n", - "from matplotlib.colors import ListedColormap\n", - "plt.rcParams['axes.labelsize'] = 14\n", - "plt.rcParams['xtick.labelsize'] = 12\n", - "plt.rcParams['ytick.labelsize'] = 12\n", - "\n", - "heads_proba = 0.51\n", - "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n", - "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n", - "plt.figure(figsize=(8,3.5))\n", - "plt.plot(cumulative_heads_ratio)\n", - "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n", - "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n", - "plt.xlabel(\"Number of coin tosses\")\n", - "plt.ylabel(\"Heads ratio\")\n", - "plt.legend(loc=\"lower right\")\n", - "plt.axis([0, 10000, 0.42, 0.58])\n", - "save_fig(\"votingsimple\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "0abe7dd3", - "metadata": { - "editable": true - }, - "source": [ - "## Using the Voting Classifier\n", - "\n", - "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**." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "20dc43ee", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "from sklearn.datasets import make_moons\n", - "\n", - "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n", - "\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "from sklearn.ensemble import VotingClassifier\n", - "from sklearn.linear_model import LogisticRegression\n", - "from sklearn.svm import SVC\n", - "\n", - "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n", - "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n", - "svm_clf = SVC(gamma=\"auto\", random_state=42)\n", - "\n", - "voting_clf = VotingClassifier(\n", - " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", - " voting='hard')\n", - "\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", - "voting_clf = VotingClassifier(\n", - " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", - " voting='soft')\n", - "voting_clf.fit(X_train, y_train)\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))" - ] - }, - { - "cell_type": "markdown", - "id": "5de42689", - "metadata": { - "editable": true - }, - "source": [ - "## Voting and Bagging" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "7b49c302", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "from sklearn.datasets import make_moons\n", - "\n", - "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "from sklearn.ensemble import VotingClassifier\n", - "from sklearn.linear_model import LogisticRegression\n", - "from sklearn.svm import SVC\n", - "\n", - "log_clf = LogisticRegression(random_state=42)\n", - "rnd_clf = RandomForestClassifier(random_state=42)\n", - "svm_clf = SVC(random_state=42)\n", - "\n", - "voting_clf = VotingClassifier(\n", - " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", - " voting='hard')\n", - "voting_clf.fit(X_train, y_train)" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "8b08d1e0", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.metrics import accuracy_score\n", - "\n", - "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", - " clf.fit(X_train, y_train)\n", - " y_pred = clf.predict(X_test)\n", - " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "251a53bd", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "log_clf = LogisticRegression(random_state=42)\n", - "rnd_clf = RandomForestClassifier(random_state=42)\n", - "svm_clf = SVC(probability=True, random_state=42)\n", - "\n", - "voting_clf = VotingClassifier(\n", - " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", - " voting='soft')\n", - "voting_clf.fit(X_train, y_train)" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "a4607683", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.metrics import accuracy_score\n", - "\n", - "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", - " clf.fit(X_train, y_train)\n", - " y_pred = clf.predict(X_test)\n", - " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" - ] - }, - { - "cell_type": "markdown", - "id": "beb8afe1", - "metadata": { - "editable": true - }, - "source": [ - "## Random forests\n", - "\n", - "Random forests provide an improvement over bagged trees by way of a\n", - "small tweak that decorrelates the trees. \n", - "\n", - "As in bagging, we build a\n", - "number of decision trees on bootstrapped training samples. But when\n", - "building these decision trees, each time a split in a tree is\n", - "considered, a random sample of $m$ predictors is chosen as split\n", - "candidates from the full set of $p$ predictors. The split is allowed to\n", - "use only one of those $m$ predictors. \n", - "\n", - "A fresh sample of $m$ predictors is\n", - "taken at each split, and typically we choose" - ] - }, - { - "cell_type": "markdown", - "id": "6dd32780", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m\\approx \\sqrt{p}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "95775422", - "metadata": { - "editable": true - }, - "source": [ - "In building a random forest, at\n", - "each split in the tree, the algorithm is not even allowed to consider\n", - "a majority of the available predictors. \n", - "\n", - "The reason for this is rather clever. Suppose that there is one very\n", - "strong predictor in the data set, along with a number of other\n", - "moderately strong predictors. Then in the collection of bagged\n", - "variable importance random forest trees, most or all of the trees will\n", - "use this strong predictor in the top split. Consequently, all of the\n", - "bagged trees will look quite similar to each other. Hence the\n", - "predictions from the bagged trees will be highly correlated.\n", - "Unfortunately, averaging many highly correlated quantities does not\n", - "lead to as large of a reduction in variance as averaging many\n", - "uncorrelated quantities. In particular, this means that bagging will\n", - "not lead to a substantial reduction in variance over a single tree in\n", - "this setting." - ] - }, - { - "cell_type": "markdown", - "id": "e232ac2e", - "metadata": { - "editable": true - }, - "source": [ - "## Random Forest Algorithm\n", - "The algorithm described here can be applied to both classification and regression problems.\n", - "\n", - "We will grow of forest of say $B$ trees.\n", - "1. For $b=1:B$\n", - "\n", - " * Draw a bootstrap sample from the training data organized in our $\\boldsymbol{X}$ matrix.\n", - "\n", - " * 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\n", - "\n", - "1. we select $m \\le p$ variables at random from the $p$ predictors/features\n", - "\n", - "2. pick the best split point among the $m$ features using for example the CART algorithm and create a new node\n", - "\n", - "3. split the node into daughter nodes\n", - "\n", - "4. Output then the ensemble of trees $\\{T_b\\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem." - ] - }, - { - "cell_type": "markdown", - "id": "00c712ec", - "metadata": { - "editable": true - }, - "source": [ - "## Random Forests Compared with other Methods on the Cancer Data" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "dfbf0cb3", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.svm import SVC\n", - "from sklearn.linear_model import LogisticRegression\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.ensemble import BaggingClassifier\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "# Logistic Regression\n", - "logreg = LogisticRegression(solver='lbfgs')\n", - "logreg.fit(X_train, y_train)\n", - "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", - "# Support vector machine\n", - "svm = SVC(gamma='auto', C=100)\n", - "svm.fit(X_train, y_train)\n", - "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n", - "# Decision Trees\n", - "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n", - "deep_tree_clf.fit(X_train, y_train)\n", - "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n", - "#now scale the data\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "# Logistic Regression\n", - "logreg.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", - "# Support Vector Machine\n", - "svm.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", - "# Decision Trees\n", - "deep_tree_clf.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))\n", - "\n", - "\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "from sklearn.preprocessing import LabelEncoder\n", - "from sklearn.model_selection import cross_validate\n", - "# Data set not specificied\n", - "#Instantiate the model with 500 trees and entropy as splitting criteria\n", - "Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion=\"entropy\")\n", - "Random_Forest_model.fit(X_train_scaled, y_train)\n", - "#Cross validation\n", - "accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']\n", - "print(accuracy)\n", - "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(Random_Forest_model.score(X_test_scaled,y_test)))\n", - "\n", - "\n", - "import scikitplot as skplt\n", - "y_pred = Random_Forest_model.predict(X_test_scaled)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "plt.show()\n", - "y_probas = Random_Forest_model.predict_proba(X_test_scaled)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "d4be7244", - "metadata": { - "editable": true - }, - "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", - "percentage of the total number of cases.\n", - "\n", - "Similarly, the receiver operating characteristic curve, or ROC curve,\n", - "displays the diagnostic ability of a binary classifier system as its\n", - "discrimination threshold is varied. It plots the true positive rate against the false positive rate." - ] - }, - { - "cell_type": "markdown", - "id": "6c43e752", - "metadata": { - "editable": true - }, - "source": [ - "## Compare Bagging on Trees with Random Forests" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "7275b11a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "bag_clf = BaggingClassifier(\n", - " DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n", - " n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "afe71c04", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "bag_clf.fit(X_train, y_train)\n", - "y_pred = bag_clf.predict(X_test)\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)\n", - "rnd_clf.fit(X_train, y_train)\n", - "y_pred_rf = rnd_clf.predict(X_test)\n", - "np.sum(y_pred == y_pred_rf) / len(y_pred)" - ] - }, - { - "cell_type": "markdown", - "id": "bb8033bf", + "id": "9a67eef0", "metadata": { "editable": true }, @@ -2666,7 +73,7 @@ }, { "cell_type": "markdown", - "id": "43d9c197", + "id": "602121d5", "metadata": { "editable": true }, @@ -2680,7 +87,7 @@ }, { "cell_type": "markdown", - "id": "59512eb5", + "id": "b0099a71", "metadata": { "editable": true }, @@ -2692,7 +99,7 @@ }, { "cell_type": "markdown", - "id": "d01de458", + "id": "2ac118ee", "metadata": { "editable": true }, @@ -2709,7 +116,7 @@ }, { "cell_type": "markdown", - "id": "9618b7ac", + "id": "3ace88e3", "metadata": { "editable": true }, @@ -2721,7 +128,7 @@ }, { "cell_type": "markdown", - "id": "f4d04ccc", + "id": "75c1b603", "metadata": { "editable": true }, @@ -2735,7 +142,7 @@ }, { "cell_type": "markdown", - "id": "7a32772c", + "id": "ee048c5a", "metadata": { "editable": true }, @@ -2747,7 +154,7 @@ }, { "cell_type": "markdown", - "id": "dfc76f2d", + "id": "63c4692a", "metadata": { "editable": true }, @@ -2760,7 +167,7 @@ }, { "cell_type": "markdown", - "id": "c77c73c5", + "id": "c80d0206", "metadata": { "editable": true }, @@ -2772,7 +179,7 @@ }, { "cell_type": "markdown", - "id": "a2a93b75", + "id": "e09ad7cd", "metadata": { "editable": true }, @@ -2782,7 +189,7 @@ }, { "cell_type": "markdown", - "id": "b4fc91c8", + "id": "45a84284", "metadata": { "editable": true }, @@ -2810,7 +217,7 @@ }, { "cell_type": "markdown", - "id": "7b755f85", + "id": "092888ab", "metadata": { "editable": true }, @@ -2826,7 +233,7 @@ }, { "cell_type": "markdown", - "id": "b7cd33c5", + "id": "06017c50", "metadata": { "editable": true }, @@ -2838,7 +245,7 @@ }, { "cell_type": "markdown", - "id": "c1abc094", + "id": "5ca4a91b", "metadata": { "editable": true }, @@ -2849,7 +256,7 @@ }, { "cell_type": "markdown", - "id": "4f12e7aa", + "id": "c0b3c663", "metadata": { "editable": true }, @@ -2861,7 +268,7 @@ }, { "cell_type": "markdown", - "id": "c9fe0d94", + "id": "3ea292e6", "metadata": { "editable": true }, @@ -2871,7 +278,7 @@ }, { "cell_type": "markdown", - "id": "ab49d8e8", + "id": "f4c7200b", "metadata": { "editable": true }, @@ -2883,7 +290,7 @@ }, { "cell_type": "markdown", - "id": "8259add1", + "id": "cd6a8041", "metadata": { "editable": true }, @@ -2893,7 +300,7 @@ }, { "cell_type": "markdown", - "id": "6ba21032", + "id": "9850f21f", "metadata": { "editable": true }, @@ -2905,7 +312,7 @@ }, { "cell_type": "markdown", - "id": "6d02a090", + "id": "fea0f4cd", "metadata": { "editable": true }, @@ -2915,7 +322,7 @@ }, { "cell_type": "markdown", - "id": "1b946cef", + "id": "2aa4c414", "metadata": { "editable": true }, @@ -2927,7 +334,7 @@ }, { "cell_type": "markdown", - "id": "b7f1658c", + "id": "f1a64c7e", "metadata": { "editable": true }, @@ -2941,7 +348,7 @@ }, { "cell_type": "markdown", - "id": "c1168b34", + "id": "ce29eba2", "metadata": { "editable": true }, @@ -2957,7 +364,7 @@ }, { "cell_type": "markdown", - "id": "1c39b99a", + "id": "c923f84a", "metadata": { "editable": true }, @@ -2969,7 +376,7 @@ }, { "cell_type": "markdown", - "id": "6f3404b3", + "id": "8240183e", "metadata": { "editable": true }, @@ -2985,7 +392,7 @@ }, { "cell_type": "markdown", - "id": "4c70dc47", + "id": "f45de38e", "metadata": { "editable": true }, @@ -2997,7 +404,7 @@ }, { "cell_type": "markdown", - "id": "680b4e03", + "id": "4ad8e546", "metadata": { "editable": true }, @@ -3007,7 +414,7 @@ }, { "cell_type": "markdown", - "id": "d48c297a", + "id": "1b62a9ed", "metadata": { "editable": true }, @@ -3019,7 +426,7 @@ }, { "cell_type": "markdown", - "id": "9ea78855", + "id": "2d64eec8", "metadata": { "editable": true }, @@ -3031,7 +438,7 @@ }, { "cell_type": "markdown", - "id": "aacac0b8", + "id": "b9f65f3b", "metadata": { "editable": true }, @@ -3043,7 +450,7 @@ }, { "cell_type": "markdown", - "id": "970d560e", + "id": "2794d15d", "metadata": { "editable": true }, @@ -3054,7 +461,7 @@ }, { "cell_type": "markdown", - "id": "fa0f6981", + "id": "b32b1e54", "metadata": { "editable": true }, @@ -3066,7 +473,7 @@ }, { "cell_type": "markdown", - "id": "4f692fa0", + "id": "c22d2f68", "metadata": { "editable": true }, @@ -3077,7 +484,7 @@ }, { "cell_type": "markdown", - "id": "4ee21d3d", + "id": "b48d2b47", "metadata": { "editable": true }, @@ -3089,7 +496,7 @@ }, { "cell_type": "markdown", - "id": "d5685bf3", + "id": "abf513dd", "metadata": { "editable": true }, @@ -3099,7 +506,7 @@ }, { "cell_type": "markdown", - "id": "aea2be59", + "id": "5903cd62", "metadata": { "editable": true }, @@ -3111,7 +518,7 @@ }, { "cell_type": "markdown", - "id": "787d4be2", + "id": "d93b783e", "metadata": { "editable": true }, @@ -3123,7 +530,7 @@ }, { "cell_type": "markdown", - "id": "00f6d701", + "id": "1e41df6e", "metadata": { "editable": true }, @@ -3135,7 +542,7 @@ }, { "cell_type": "markdown", - "id": "2515d852", + "id": "236d858f", "metadata": { "editable": true }, @@ -3147,7 +554,7 @@ }, { "cell_type": "markdown", - "id": "d98b609b", + "id": "96827827", "metadata": { "editable": true }, @@ -3157,7 +564,7 @@ }, { "cell_type": "markdown", - "id": "092938b5", + "id": "4861d8e1", "metadata": { "editable": true }, @@ -3169,7 +576,7 @@ }, { "cell_type": "markdown", - "id": "e610a697", + "id": "69f49701", "metadata": { "editable": true }, @@ -3179,7 +586,7 @@ }, { "cell_type": "markdown", - "id": "9325f7ab", + "id": "5a0afb66", "metadata": { "editable": true }, @@ -3191,7 +598,7 @@ }, { "cell_type": "markdown", - "id": "0b111723", + "id": "e6ed8534", "metadata": { "editable": true }, @@ -3201,7 +608,7 @@ }, { "cell_type": "markdown", - "id": "bc56e91c", + "id": "cce07aef", "metadata": { "editable": true }, @@ -3213,7 +620,7 @@ }, { "cell_type": "markdown", - "id": "6ea7be4d", + "id": "7837a10e", "metadata": { "editable": true }, @@ -3223,7 +630,7 @@ }, { "cell_type": "markdown", - "id": "fc97e2c0", + "id": "406aa2b3", "metadata": { "editable": true }, @@ -3235,7 +642,7 @@ }, { "cell_type": "markdown", - "id": "3396a105", + "id": "9d086c2e", "metadata": { "editable": true }, @@ -3245,7 +652,7 @@ }, { "cell_type": "markdown", - "id": "86164277", + "id": "27933ed4", "metadata": { "editable": true }, @@ -3257,7 +664,7 @@ }, { "cell_type": "markdown", - "id": "56e9bc72", + "id": "9f76a58e", "metadata": { "editable": true }, @@ -3277,7 +684,7 @@ }, { "cell_type": "markdown", - "id": "c19ae181", + "id": "739a8940", "metadata": { "editable": true }, @@ -3289,7 +696,7 @@ }, { "cell_type": "markdown", - "id": "e8da19a4", + "id": "73394e42", "metadata": { "editable": true }, @@ -3299,7 +706,7 @@ }, { "cell_type": "markdown", - "id": "6528d252", + "id": "64e26b40", "metadata": { "editable": true }, @@ -3315,7 +722,7 @@ }, { "cell_type": "markdown", - "id": "03061ff0", + "id": "87c5f9fd", "metadata": { "editable": true }, @@ -3327,7 +734,7 @@ }, { "cell_type": "markdown", - "id": "329880e6", + "id": "6a5697b7", "metadata": { "editable": true }, @@ -3355,7 +762,7 @@ }, { "cell_type": "markdown", - "id": "a17484e2", + "id": "63850db2", "metadata": { "editable": true }, @@ -3367,8 +774,8 @@ }, { "cell_type": "code", - "execution_count": 27, - "id": "0368e8cf", + "execution_count": 1, + "id": "4ff56ccb", "metadata": { "collapsed": false, "editable": true @@ -3400,7 +807,7 @@ }, { "cell_type": "markdown", - "id": "bec09d13", + "id": "74525cdb", "metadata": { "editable": true }, @@ -3418,7 +825,7 @@ }, { "cell_type": "markdown", - "id": "956f0ebb", + "id": "350831a7", "metadata": { "editable": true }, @@ -3431,7 +838,7 @@ }, { "cell_type": "markdown", - "id": "9c8261f8", + "id": "59220eb7", "metadata": { "editable": true }, @@ -3443,7 +850,7 @@ }, { "cell_type": "markdown", - "id": "b52aa243", + "id": "7548978e", "metadata": { "editable": true }, @@ -3453,7 +860,7 @@ }, { "cell_type": "markdown", - "id": "9f907030", + "id": "ee4db9d5", "metadata": { "editable": true }, @@ -3465,7 +872,7 @@ }, { "cell_type": "markdown", - "id": "3f2b936d", + "id": "36e73e54", "metadata": { "editable": true }, @@ -3475,7 +882,7 @@ }, { "cell_type": "markdown", - "id": "2b495785", + "id": "b5089686", "metadata": { "editable": true }, @@ -3487,7 +894,7 @@ }, { "cell_type": "markdown", - "id": "8b09c2e3", + "id": "92f5f377", "metadata": { "editable": true }, @@ -3500,7 +907,7 @@ }, { "cell_type": "markdown", - "id": "00ea9bd0", + "id": "f5ed7b9b", "metadata": { "editable": true }, @@ -3512,7 +919,7 @@ }, { "cell_type": "markdown", - "id": "c95c9ca3", + "id": "ca65ab31", "metadata": { "editable": true }, @@ -3524,7 +931,7 @@ }, { "cell_type": "markdown", - "id": "ab0dad4c", + "id": "c65e0584", "metadata": { "editable": true }, @@ -3536,7 +943,7 @@ }, { "cell_type": "markdown", - "id": "118bcafc", + "id": "70091313", "metadata": { "editable": true }, @@ -3546,7 +953,7 @@ }, { "cell_type": "markdown", - "id": "541e9c64", + "id": "1c00d11b", "metadata": { "editable": true }, @@ -3558,7 +965,7 @@ }, { "cell_type": "markdown", - "id": "0d6955b5", + "id": "15c71668", "metadata": { "editable": true }, @@ -3568,7 +975,7 @@ }, { "cell_type": "markdown", - "id": "d1e3d511", + "id": "0740c01c", "metadata": { "editable": true }, @@ -3584,7 +991,7 @@ }, { "cell_type": "markdown", - "id": "0f51da66", + "id": "482a581c", "metadata": { "editable": true }, @@ -3596,7 +1003,7 @@ }, { "cell_type": "markdown", - "id": "9b12e6f5", + "id": "67825485", "metadata": { "editable": true }, @@ -3617,7 +1024,7 @@ }, { "cell_type": "markdown", - "id": "a2092cee", + "id": "81109715", "metadata": { "editable": true }, @@ -3627,14 +1034,16 @@ }, { "cell_type": "code", - "execution_count": 28, - "id": "38910c9a", + "execution_count": 2, + "id": "043fd38b", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ + "%matplotlib inline\n", + "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from sklearn.model_selection import train_test_split\n", @@ -3680,7 +1089,7 @@ }, { "cell_type": "markdown", - "id": "a6ecaf58", + "id": "f20fba0f", "metadata": { "editable": true }, @@ -3690,8 +1099,8 @@ }, { "cell_type": "code", - "execution_count": 29, - "id": "b12de0d2", + "execution_count": 3, + "id": "83e60e4d", "metadata": { "collapsed": false, "editable": true @@ -3742,7 +1151,7 @@ }, { "cell_type": "markdown", - "id": "a55eefd0", + "id": "82c6b7dc", "metadata": { "editable": true }, @@ -3765,7 +1174,7 @@ }, { "cell_type": "markdown", - "id": "dba0b7bb", + "id": "7c991464", "metadata": { "editable": true }, @@ -3775,8 +1184,8 @@ }, { "cell_type": "code", - "execution_count": 30, - "id": "5620b93c", + "execution_count": 4, + "id": "fda5cd85", "metadata": { "collapsed": false, "editable": true @@ -3828,7 +1237,7 @@ }, { "cell_type": "markdown", - "id": "d0a95e1f", + "id": "8764bd38", "metadata": { "editable": true }, @@ -3840,8 +1249,8 @@ }, { "cell_type": "code", - "execution_count": 31, - "id": "49018eb3", + "execution_count": 5, + "id": "82566474", "metadata": { "collapsed": false, "editable": true diff --git a/doc/src/week45/week45.do.txt b/doc/src/week45/week45.do.txt index 07b41149b..f6c5f174f 100644 --- a/doc/src/week45/week45.do.txt +++ b/doc/src/week45/week45.do.txt @@ -5,8 +5,8 @@ DATE: today !split ===== Overview of week 45 ===== -* Thursday: Basics of Decision Trees, Bagging and Voting -* Friday: More on Bagging, Voting, Random Forests and start Boosting +* Thursday: Boosting methods, froma AdaBoost to Gradient boosting +* Friday: Gradient boosting and discussion of Decision trees and ensemble methods !bblock Videos o "Video on Decision trees":"https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn" @@ -14,1759 +14,10 @@ o "Video on boosting methods by Hastie":"https://www.youtube.com/watch?v=wPqtzj5 !eblock !bblock Reading -o 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. +o !eblock -!split -===== 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, -classification and regression tasks. - - -The main idea of decision trees -is to find those descriptive features which contain the most -_information_ regarding the target feature and then split the dataset -along the values of these features such that the target feature values -for the resulting underlying datasets are as pure as possible. - -The descriptive features which reproduce best the target/output features are normally said -to be the most informative ones. The process of finding the _most -informative_ feature is done until we accomplish a stopping criteria -where we then finally end up in so called _leaf nodes_. - -!split -===== 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 -contain the predictions we will make for new query instances presented -to our trained model. This is possible since the model has -learned the underlying structure of the training data and hence can, -given some assumptions, make predictions about the target feature value -(class) of unseen query instances. - -!split -===== A Sketch of a Tree, Regression problem ===== - - - -#FIGURE: [DataFiles/Regsimpletree.png, width=600 frac=0.8] - -!split -===== A Sketch of a Tree, Classification problem ===== - -#FIGURE: [DataFiles/Classimpletree.png, width=600 frac=0.8] - - - -!split -===== A typical Decision Tree with its pertinent Jargon, Classification Problem ===== - -FIGURE: [DataFiles/cancer.png, width=600 frac=0.8] - -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. - - - -!split -===== General Features ===== - -The overarching approach to decision trees is a top-down approach. - -* A leaf provides the classification of a given instance. -* A node specifies a test of some attribute of the instance. -* A branch corresponds to a possible values of an attribute. -* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example. - - -This process is then repeated for the subtree rooted at the new -node. - - -!split -===== 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: - -o Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature - -o Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process - -o Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances - -o Show query instances to the tree and run down the tree until we arrive at leaf nodes - -Then we are essentially done! - - - - - -!split -===== Decision trees and Regression ===== -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression - -steps=250 - -distance=0 -x=0 -distance_list=[] -steps_list=[] -while x 0).astype(np.float32) * 2 - -angle = np.pi/4 -rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) -Xsr = Xs.dot(rotation_matrix) - -tree_clf_s = DecisionTreeClassifier(random_state=42) -tree_clf_s.fit(Xs, ys) -tree_clf_sr = DecisionTreeClassifier(random_state=42) -tree_clf_sr.fit(Xsr, ys) - -plt.figure(figsize=(11, 4)) -plt.subplot(121) -plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) -plt.subplot(122) -plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) - -plt.show() -!ec - -!split -===== Regression trees ===== -!bc pycod -# 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 -!ec - -!bc pycod -from sklearn.tree import DecisionTreeRegressor - -tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42) -tree_reg.fit(X, y) -!ec - -!split -===== Final regressor code ===== -!bc pycod -from sklearn.tree import DecisionTreeRegressor - -tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2) -tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3) -tree_reg1.fit(X, y) -tree_reg2.fit(X, y) - -def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"): - x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1) - y_pred = tree_reg.predict(x1) - plt.axis(axes) - plt.xlabel("$x_1$", fontsize=18) - if ylabel: - plt.ylabel(ylabel, fontsize=18, rotation=0) - plt.plot(X, y, "b.") - plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$") - -plt.figure(figsize=(11, 4)) -plt.subplot(121) -plot_regression_predictions(tree_reg1, X, y) -for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): - plt.plot([split, split], [-0.2, 1], style, linewidth=2) -plt.text(0.21, 0.65, "Depth=0", fontsize=15) -plt.text(0.01, 0.2, "Depth=1", fontsize=13) -plt.text(0.65, 0.8, "Depth=1", fontsize=13) -plt.legend(loc="upper center", fontsize=18) -plt.title("max_depth=2", fontsize=14) - -plt.subplot(122) -plot_regression_predictions(tree_reg2, X, y, ylabel=None) -for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): - plt.plot([split, split], [-0.2, 1], style, linewidth=2) -for split in (0.0458, 0.1298, 0.2873, 0.9040): - plt.plot([split, split], [-0.2, 1], "k:", linewidth=1) -plt.text(0.3, 0.5, "Depth=2", fontsize=13) -plt.title("max_depth=3", fontsize=14) - -plt.show() -!ec - -!bc pycod -tree_reg1 = DecisionTreeRegressor(random_state=42) -tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10) -tree_reg1.fit(X, y) -tree_reg2.fit(X, y) - -x1 = np.linspace(0, 1, 500).reshape(-1, 1) -y_pred1 = tree_reg1.predict(x1) -y_pred2 = tree_reg2.predict(x1) - -plt.figure(figsize=(11, 4)) - -plt.subplot(121) -plt.plot(X, y, "b.") -plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$") -plt.axis([0, 1, -0.2, 1.1]) -plt.xlabel("$x_1$", fontsize=18) -plt.ylabel("$y$", fontsize=18, rotation=0) -plt.legend(loc="upper center", fontsize=18) -plt.title("No restrictions", fontsize=14) - -plt.subplot(122) -plt.plot(X, y, "b.") -plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$") -plt.axis([0, 1, -0.2, 1.1]) -plt.xlabel("$x_1$", fontsize=18) -plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14) - -plt.show() -!ec - - - -!split -===== 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) -* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression! -* No feature normalization needed -* Tree models can handle both continuous and categorical data (Classification and Regression Trees) -* Can model nonlinear relationships -* Can model interactions between the different descriptive features -* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small) - - -!split -===== Disadvantages ===== - -* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches -* If continuous features are used the tree may become quite large and hence less interpretable -* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented -* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests -* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. -* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data -* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain - -However, by aggregating many decision trees, using methods like -bagging, random forests, and boosting, the predictive performance of -trees can be substantially improved. - - -!split -===== 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 - -o Voting classifiers -o Bagging and Pasting -o Random forests -o Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost) - -We discuss these methods here. - - -!split -===== An Overview of Ensemble Methods ===== - -FIGURE: [DataFiles/ensembleoverview.png, width=600 frac=0.8] - - - -!split -===== 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. - - -!split -===== 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. - - - -!split -===== 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$). -!bc pycod - -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() - - 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() - -!ec - - - - - -!split -===== 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. - -!split -===== 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":"https://en.wikipedia.org/wiki/Law_of_large_numbers" -numbers kicking in. - -!split -===== Standard imports first ===== - -!bc pycod -# 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) - -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') - -!ec - - - - -!split -===== Simple Voting Example, head or tail ===== -!bc pycod - -# 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() - -!ec - - -!split -===== 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_. -!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 -===== 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 -===== 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 - -!bt -\[ -m\approx \sqrt{p}. -\] -!et - -In building a random forest, at -each split in the tree, the algorithm is not even allowed to consider -a majority of the available predictors. - -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. - - -!split -===== 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. -o For $b=1:B$ - * Draw a bootstrap sample from the training data organized in our $\bm{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 - o we select $m \le p$ variables at random from the $p$ predictors/features - o pick the best split point among the $m$ features using for example the CART algorithm and create a new node - o split the node into daughter nodes -o 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. - - - -!split -===== Random Forests Compared with other Methods on the Cancer Data ===== -!bc pycod -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() - -!ec - - -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, -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. - - -!split -===== Compare Bagging on Trees with Random Forests ===== -!bc pycod -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) -!ec - - - -!bc pycod -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) -!ec - - - !split @@ -2405,3 +656,4 @@ plt.show() +