From 9190a0499f454b8fd679b9919672daa7ce34bfc4 Mon Sep 17 00:00:00 2001 From: mhjensen Date: Mon, 2 Nov 2020 16:11:18 +0100 Subject: [PATCH] week 45 --- doc/pub/week45/html/._week45-bs000.html | 117 ++++---- doc/pub/week45/html/._week45-bs001.html | 119 ++++---- doc/pub/week45/html/._week45-bs002.html | 117 ++++---- doc/pub/week45/html/._week45-bs003.html | 158 +++++----- doc/pub/week45/html/._week45-bs004.html | 148 +++++----- doc/pub/week45/html/._week45-bs005.html | 193 +++++------- doc/pub/week45/html/._week45-bs006.html | 172 +++++++---- doc/pub/week45/html/._week45-bs007.html | 175 +++++++---- doc/pub/week45/html/._week45-bs008.html | 187 ++++++------ doc/pub/week45/html/._week45-bs009.html | 144 +++++---- doc/pub/week45/html/._week45-bs010.html | 214 ++++++++------ doc/pub/week45/html/._week45-bs011.html | 158 +++++----- doc/pub/week45/html/._week45-bs012.html | 144 ++++----- doc/pub/week45/html/._week45-bs013.html | 173 ++++++----- doc/pub/week45/html/._week45-bs014.html | 146 +++++---- doc/pub/week45/html/._week45-bs015.html | 173 ++++++----- doc/pub/week45/html/._week45-bs016.html | 161 +++++----- doc/pub/week45/html/._week45-bs017.html | 147 +++++----- doc/pub/week45/html/._week45-bs018.html | 158 ++++++---- doc/pub/week45/html/._week45-bs019.html | 151 +++++----- doc/pub/week45/html/._week45-bs020.html | 155 ++++++---- doc/pub/week45/html/._week45-bs021.html | 157 +++++----- doc/pub/week45/html/._week45-bs022.html | 143 +++++---- doc/pub/week45/html/._week45-bs023.html | 175 +++++------ doc/pub/week45/html/._week45-bs024.html | 183 ++++++------ doc/pub/week45/html/._week45-bs025.html | 141 +++++---- doc/pub/week45/html/week45-bs.html | 117 ++++---- doc/pub/week45/html/week45-reveal.html | 238 +++++++++++++-- doc/pub/week45/html/week45-solarized.html | 293 +++++++++++++++---- doc/pub/week45/html/week45.html | 293 +++++++++++++++---- doc/pub/week45/ipynb/ipynb-week45-src.tar.gz | Bin 190 -> 191 bytes doc/pub/week45/ipynb/week45.ipynb | 230 ++++++++++++++- 32 files changed, 3226 insertions(+), 2054 deletions(-) diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index 39586fc8c..213838dad 100644 --- a/doc/pub/week45/html/._week45-bs000.html +++ b/doc/pub/week45/html/._week45-bs000.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -199,7 +212,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 31, 2020

+

Nov 2, 2020


@@ -223,7 +236,7 @@ MathJax.Hub.Config({

  • 9
  • 10
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs001.html b/doc/pub/week45/html/._week45-bs001.html index 956dcdf9f..c81c750a6 100644 --- a/doc/pub/week45/html/._week45-bs001.html +++ b/doc/pub/week45/html/._week45-bs001.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -183,11 +196,11 @@ MathJax.Hub.Config({

    Overview of week 45

    -Geron's chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion. +Geron's chapter 7. See also lecture from STK-IN4300, lecture 9. Chapter 10 (sections 10.1-10.10 are the most relevant ones) of Hastie et al contains also a good discussion.

    @@ -206,7 +219,7 @@ Geron's chapter 7. See also lecture from 10

  • 11
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs002.html b/doc/pub/week45/html/._week45-bs002.html index 4ef20a4f7..873ad97b6 100644 --- a/doc/pub/week45/html/._week45-bs002.html +++ b/doc/pub/week45/html/._week45-bs002.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -184,6 +197,8 @@ MathJax.Hub.Config({

    Bagging, voting and random forests. +The material on bagging and voting is a repeat from last week and can be found in the slides from week 44. +We repeat here the voting approach since this will serve as a motivation for boosting methods later.

    @@ -203,7 +218,7 @@ Bagging, voting and random forests.

  • 11
  • 12
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs003.html b/doc/pub/week45/html/._week45-bs003.html index 632efc707..5175ce22d 100644 --- a/doc/pub/week45/html/._week45-bs003.html +++ b/doc/pub/week45/html/._week45-bs003.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,46 +193,25 @@ MathJax.Hub.Config({ -

    Random forests

    +

    Why Voting?

    -Random forests provide an improvement over bagged trees by way of a -small tweak that decorrelates the trees. +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?

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

    -A fresh sample of \( m \) predictors is -taken at each split, and typically we choose - -$$ -m\approx \sqrt{p}. -$$ +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.

    -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. +Decision trees play an important role as our weak classifier. They serve as the basic method.

    @@ -240,7 +232,7 @@ this setting.

  • 12
  • 13
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs004.html b/doc/pub/week45/html/._week45-bs004.html index 87f861cbd..f5da7e22a 100644 --- a/doc/pub/week45/html/._week45-bs004.html +++ b/doc/pub/week45/html/._week45-bs004.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,30 +193,25 @@ MathJax.Hub.Config({ -

    Random Forest Algorithm

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

    Tossing coins

    +The simplest case is a so-called voting ensemble. To illustrate this, Think of you 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. However, after some thousands of tosses (sounds like you may have some spare time problems), there will be a clear majority of heads. +With 2000 tosses you should see approximately 1020 heads and 980 tails.

    -We will grow of forest of say \( B \) trees. +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. -

      -
    1. For \( b=1:B \)
    2. +

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

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

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

    diff --git a/doc/pub/week45/html/._week45-bs005.html b/doc/pub/week45/html/._week45-bs005.html index 00fe570d3..d25c825f9 100644 --- a/doc/pub/week45/html/._week45-bs005.html +++ b/doc/pub/week45/html/._week45-bs005.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,74 +193,22 @@ MathJax.Hub.Config({ -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Simple Voting Example, head or tail

    -

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

    @@ -271,7 +232,7 @@ plt.show()

  • 14
  • 15
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs006.html b/doc/pub/week45/html/._week45-bs006.html index c2ecc1c69..6fe955249 100644 --- a/doc/pub/week45/html/._week45-bs006.html +++ b/doc/pub/week45/html/._week45-bs006.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,24 +193,55 @@ MathJax.Hub.Config({ -

    Compare Bagging on Trees with Random Forests

    +

    Using the Voting Classifier

    + +

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

    -

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

    +

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

    @@ -221,7 +265,7 @@ np.sum(y_pred =

  • 15
  • 16
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs007.html b/doc/pub/week45/html/._week45-bs007.html index e6718368e..92c3272dc 100644 --- a/doc/pub/week45/html/._week45-bs007.html +++ b/doc/pub/week45/html/._week45-bs007.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,20 +193,62 @@ MathJax.Hub.Config({ -

    Boosting, a Bird's Eye View

    +

    Please, not the moons again! Voting and Bagging

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

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

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

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

    @@ -217,7 +272,7 @@ them with a factor.

  • 16
  • 17
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs008.html b/doc/pub/week45/html/._week45-bs008.html index 23e5346ec..64e6e6aaf 100644 --- a/doc/pub/week45/html/._week45-bs008.html +++ b/doc/pub/week45/html/._week45-bs008.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,54 +193,46 @@ MathJax.Hub.Config({ -

    What is boosting? Additive Modelling/Iterative Fitting

    +

    Random forests

    -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 +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 + $$ -f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +m\approx \sqrt{p}. $$

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

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

    @@ -253,7 +258,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re

  • 17
  • 18
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs009.html b/doc/pub/week45/html/._week45-bs009.html index 0f97fde2c..22b482fb6 100644 --- a/doc/pub/week45/html/._week45-bs009.html +++ b/doc/pub/week45/html/._week45-bs009.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,29 +193,30 @@ MathJax.Hub.Config({ -

    Iterative Fitting, Regression and Squared-error Cost Function

    +

    Random Forest Algorithm

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

    -The way we proceed is as follows (here we specialize to the squared-error cost function) +We will grow of forest of say \( B \) trees.

      -
    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 \) +
    6. For \( b=1:B \)
    7. -
        -
      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. +
          +
        • Draw a bootstrap sample of 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 either the CART algorithm or the ID3 for classification and create a new node
          4. +
          5. split the node into daughter nodes
          +
        + +
      7. 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.
      -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. - -

        @@ -227,7 +241,7 @@ at the internal nodes, and the predictions at the terminal nodes.
      • 18
      • 19
      • ...
      • -
      • 28
      • +
      • 33
      • »
      diff --git a/doc/pub/week45/html/._week45-bs010.html b/doc/pub/week45/html/._week45-bs010.html index 1718a9eaa..467da9474 100644 --- a/doc/pub/week45/html/._week45-bs010.html +++ b/doc/pub/week45/html/._week45-bs010.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,51 +193,76 @@ MathJax.Hub.Config({ -

      Squared-Error Example and Iterative Fitting

      - +

      Random Forests Compared with other Methods on the Cancer Data

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

      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
       
      -

      -This means that for every iteration \( m \), we need to optimize +# Load the data +cancer = load_breast_cancer() -$$ -(\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. -$$ +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))) -

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

      @@ -251,7 +289,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma

    8. 19
    9. 20
    10. ...
    11. -
    12. 28
    13. +
    14. 33
    15. »
    16. diff --git a/doc/pub/week45/html/._week45-bs011.html b/doc/pub/week45/html/._week45-bs011.html index 2cf347720..0cdd3b379 100644 --- a/doc/pub/week45/html/._week45-bs011.html +++ b/doc/pub/week45/html/._week45-bs011.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,38 +193,25 @@ MathJax.Hub.Config({ -

      Iterative Fitting, Classification and AdaBoost

      - +

      Compare Bagging on Trees with Random Forests

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

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

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

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

      @@ -238,7 +238,7 @@ $$

    17. 20
    18. 21
    19. ...
    20. -
    21. 28
    22. +
    23. 33
    24. »
    25. diff --git a/doc/pub/week45/html/._week45-bs012.html b/doc/pub/week45/html/._week45-bs012.html index 39ae61561..e2e10902d 100644 --- a/doc/pub/week45/html/._week45-bs012.html +++ b/doc/pub/week45/html/._week45-bs012.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,30 +193,19 @@ MathJax.Hub.Config({ -

      Adaptive Boosting, AdaBoost

      +

      Boosting, a Bird's Eye View

      -In our iterative procedure we define thus -$$ -f_m(x) = f_{m-1}(x)+\beta_mG_m(x). -$$ +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.

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

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

    26. 21
    27. 22
    28. ...
    29. -
    30. 28
    31. +
    32. 33
    33. »
    34. diff --git a/doc/pub/week45/html/._week45-bs013.html b/doc/pub/week45/html/._week45-bs013.html index 3d6b09011..a6261f2a2 100644 --- a/doc/pub/week45/html/._week45-bs013.html +++ b/doc/pub/week45/html/._week45-bs013.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,46 +193,54 @@ MathJax.Hub.Config({ -

      Building up AdaBoost

      +

      What is boosting? Additive Modelling/Iterative Fitting

      -First, for any \( \beta > 0 \), we optimize \( G \) by setting +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 $$ -G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ -which is the classifier that minimizes the weighted error rate in predicting \( y \). -

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

      +As an example, consider the Sigmoid function we used in logistic +regression. In that case, we can translate the function +\( b(x;\gamma_m) \) into the Sigmoid function + $$ -\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, +\sigma(t) = \frac{1}{1+\exp{(-t)}}, $$ -which can be rewritten as +

      +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 $$ -(\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, +C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$ -which leads to +

      +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 + $$ -\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -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))} -$$ +

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

      @@ -247,7 +268,7 @@ $$

    35. 22
    36. 23
    37. ...
    38. -
    39. 28
    40. +
    41. 33
    42. »
    43. diff --git a/doc/pub/week45/html/._week45-bs014.html b/doc/pub/week45/html/._week45-bs014.html index 6700fb44c..22d6e66c8 100644 --- a/doc/pub/week45/html/._week45-bs014.html +++ b/doc/pub/week45/html/._week45-bs014.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,24 +193,27 @@ MathJax.Hub.Config({ -

      Adaptive boosting: AdaBoost, Basic Algorithm

      +

      Iterative Fitting, Regression and Squared-error Cost Function

      -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} \). +The way we proceed is as follows (here we specialize to the squared-error cost function) -

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

        +
      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 \) -where the function \( I() \) is one if we misclassify and zero if we classify correctly. +
          +
        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.

      @@ -225,7 +241,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co

    44. 23
    45. 24
    46. ...
    47. -
    48. 28
    49. +
    50. 33
    51. »
    52. diff --git a/doc/pub/week45/html/._week45-bs015.html b/doc/pub/week45/html/._week45-bs015.html index 567db5dd8..dced6e2cc 100644 --- a/doc/pub/week45/html/._week45-bs015.html +++ b/doc/pub/week45/html/._week45-bs015.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,42 +193,50 @@ MathJax.Hub.Config({ -

      Basic Steps of AdaBoost

      +

      Squared-Error Example and Iterative Fitting

      -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. +To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. -

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

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

        -
      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. +and +$$ +\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. +$$ -
          -
        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. -
        +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, +$$ -
      2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
      3. -
      +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, +$$ -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. +

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

      @@ -243,7 +264,7 @@ observations that are missed in the previous iterations.

    53. 24
    54. 25
    55. ...
    56. -
    57. 28
    58. +
    59. 33
    60. »
    61. diff --git a/doc/pub/week45/html/._week45-bs016.html b/doc/pub/week45/html/._week45-bs016.html index 997772367..3d195614a 100644 --- a/doc/pub/week45/html/._week45-bs016.html +++ b/doc/pub/week45/html/._week45-bs016.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,36 +193,38 @@ MathJax.Hub.Config({ -

      AdaBoost Examples

      +

      Iterative Fitting, Classification and AdaBoost

      -Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. +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 - -

      from sklearn.ensemble import AdaBoostClassifier
      +$$
      +\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). 
      +$$
       
      -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)
      +

      +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) \). -from sklearn.ensemble import AdaBoostClassifier +

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

      @@ -236,7 +251,7 @@ plt.show()

    62. 25
    63. 26
    64. ...
    65. -
    66. 28
    67. +
    68. 33
    69. »
    70. diff --git a/doc/pub/week45/html/._week45-bs017.html b/doc/pub/week45/html/._week45-bs017.html index d126baf39..8f6f5a2ff 100644 --- a/doc/pub/week45/html/._week45-bs017.html +++ b/doc/pub/week45/html/._week45-bs017.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,30 +193,30 @@ MathJax.Hub.Config({ -

      AdaBoost for Regression

      +

      Adaptive Boosting, AdaBoost

      -Here we present Drucker's AdaBoost tailored for regression. +In our iterative procedure we define thus +$$ +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +$$

      -In bagging, each training example is equally likely to be -picked. In boosting, the probability of a particular -example being in the training set of a particular machine -depends on the performance of the prior machines on -that example. The following is a modification of -Adaboost by Drucker. +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))}. +$$

      -Start by selecting a set of training data \( n \) and assign to each entry a weight \( w_i=1 \) for \( i=1,2,\dots,n \). As we have done earlier, we could pick say \( 80\% \) of the data set for training. The algorithm runs as follows: +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 -

        -
      1. We define the probability that the training sample \( i \) is in the set by \( p_i = w_i/\sum_iw_i \). We pick \( n \) samples (with replacement) to form our training set. We pick a number uniformly in the range \( [0,\sum_iw_i] \).
      2. -
      3. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
      4. -
      5. Using every member of the training set with the chosen regression machine we obtain then a prediction \( \tilde{y}_i \).
      6. -
      7. We calculate then the loss function \( L_i \) for each training sample. We can use various types of loss function as long as we have a value
      8. -
      +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, +$$ -\( L_i\in [0,1] \). +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

      @@ -231,7 +244,7 @@ Start by selecting a set of training data \( n \) and assign to each entry a wei

    71. 26
    72. 27
    73. ...
    74. -
    75. 28
    76. +
    77. 33
    78. »
    79. diff --git a/doc/pub/week45/html/._week45-bs018.html b/doc/pub/week45/html/._week45-bs018.html index 2bf3230a3..3ac5cd724 100644 --- a/doc/pub/week45/html/._week45-bs018.html +++ b/doc/pub/week45/html/._week45-bs018.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,17 +193,46 @@ MathJax.Hub.Config({ -

      Gradient boosting: Basics with Steepest Descent

      +

      Building up AdaBoost

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

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

      @@ -217,6 +259,8 @@ function was the least squares function.

    80. 26
    81. 27
    82. 28
    83. +
    84. ...
    85. +
    86. 33
    87. »
    88. diff --git a/doc/pub/week45/html/._week45-bs019.html b/doc/pub/week45/html/._week45-bs019.html index 4c4ba244a..20b8306a8 100644 --- a/doc/pub/week45/html/._week45-bs019.html +++ b/doc/pub/week45/html/._week45-bs019.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,37 +193,24 @@ MathJax.Hub.Config({ -

      The Squared-Error again! Steepest Descent

      +

      Adaptive boosting: AdaBoost, Basic Algorithm

      -We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize -This means that for every iteration, we need to optimize - -$$ -(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. -$$ +The algorithm here is rather straightforward. Assume that our weak +classifier is a decision tree and we consider a binary set of outputs +with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. Our design matrix is given in terms of the +feature/predictor vectors +\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a +classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \).

      -We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as +We have already defined the misclassification error \( \mathrm{err} \) as $$ -f_M(x) = \sum_{m=0}^M h_m(x). +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), $$ -

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

      -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. -$$ +where the function \( I() \) is one if we misclassify and zero if we classify correctly.

      @@ -236,6 +236,9 @@ $$

    89. 26
    90. 27
    91. 28
    92. +
    93. 29
    94. +
    95. ...
    96. +
    97. 33
    98. »
    99. diff --git a/doc/pub/week45/html/._week45-bs020.html b/doc/pub/week45/html/._week45-bs020.html index 280b59923..ad19e1633 100644 --- a/doc/pub/week45/html/._week45-bs020.html +++ b/doc/pub/week45/html/._week45-bs020.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,20 +193,42 @@ MathJax.Hub.Config({ -

      Steepest Descent Example

      +

      Basic Steps of AdaBoost

      -Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that +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. +
      + $$ -f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. +\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}, $$ -We can then proceed and compute -$$ -g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, -$$ -and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting. +
        +
      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.

      @@ -218,6 +253,10 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(

    100. 26
    101. 27
    102. 28
    103. +
    104. 29
    105. +
    106. 30
    107. +
    108. ...
    109. +
    110. 33
    111. »
    112. diff --git a/doc/pub/week45/html/._week45-bs021.html b/doc/pub/week45/html/._week45-bs021.html index 4b8e814e5..829f2d8fc 100644 --- a/doc/pub/week45/html/._week45-bs021.html +++ b/doc/pub/week45/html/._week45-bs021.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,30 +193,37 @@ MathJax.Hub.Config({ -

      Gradient Boosting, algorithm

      +

      AdaBoost Examples

      -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. -$$ +Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.

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

        -
      1. Initialize our estimate \( f_0(x) \).
      2. -
      3. For \( m=1:M \), we + +
        from sklearn.ensemble import AdaBoostClassifier
         
        -
          -
        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)+\nu h_m(u_m,x) \);
        6. -
        +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) -
      4. The final estimate is then \( f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x) \).
      5. -
      +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() +
    +

      @@ -225,6 +245,11 @@ The way we proceed in an iterative fashion is to
    • 26
    • 27
    • 28
    • +
    • 29
    • +
    • 30
    • +
    • 31
    • +
    • ...
    • +
    • 33
    • »
    diff --git a/doc/pub/week45/html/._week45-bs022.html b/doc/pub/week45/html/._week45-bs022.html index 1dde295c0..225d3b65c 100644 --- a/doc/pub/week45/html/._week45-bs022.html +++ b/doc/pub/week45/html/._week45-bs022.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,10 +193,30 @@ MathJax.Hub.Config({ -

    Gradient Boosting Example, Regression

    +

    AdaBoost for Regression

    -We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. +Here we present Drucker's AdaBoost tailored for regression. + +

    +In bagging, each training example is equally likely to be +picked. In boosting, the probability of a particular +example being in the training set of a particular machine +depends on the performance of the prior machines on +that example. The following is a modification of +Adaboost by Drucker. + +

    +Start by selecting a set of training data \( n \) and assign to each entry a weight \( w_i=1 \) for \( i=1,2,\dots,n \). As we have done earlier, we could pick say \( 80\% \) of the data set for training. The algorithm runs as follows: + +

      +
    1. We define the probability that the training sample \( i \) is in the set by \( p_i = w_i/\sum_iw_i \). We pick \( n \) samples (with replacement) to form our training set. We pick a number uniformly in the range \( [0,\sum_iw_i] \).
    2. +
    3. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
    4. +
    5. Using every member of the training set with the chosen regression machine we obtain then a prediction \( \tilde{y}_i \).
    6. +
    7. We calculate then the loss function \( L_i \) for each training sample. We can use various types of loss function as long as we have a value
    8. +
    + +\( L_i\in [0,1] \).

    @@ -206,6 +239,12 @@ We discuss here the difference between the steepest descent approach and gradien

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • +
  • ...
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs023.html b/doc/pub/week45/html/._week45-bs023.html index fe2eac04a..960b8f658 100644 --- a/doc/pub/week45/html/._week45-bs023.html +++ b/doc/pub/week45/html/._week45-bs023.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,57 +193,18 @@ MathJax.Hub.Config({ -

    Gradient Boosting, Examples of Regression

    +

    Gradient boosting: Basics with Steepest Descent

    +

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

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.ensemble import GradientBoostingRegressor
    -from sklearn.preprocessing import StandardScaler
    -import scikitplot as skplt
    -from sklearn.metrics import mean_squared_error
    +

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

    @@ -251,6 +225,11 @@ plt.show()

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs024.html b/doc/pub/week45/html/._week45-bs024.html index 1fd29fa6d..de3902463 100644 --- a/doc/pub/week45/html/._week45-bs024.html +++ b/doc/pub/week45/html/._week45-bs024.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,51 +193,38 @@ MathJax.Hub.Config({ -

    Gradient Boosting, Classification Example

    +

    The Squared-Error again! Steepest Descent

    +

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

    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
    +$$
    +(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
    +$$
     
    -# Load the data
    -cancer = load_breast_cancer()
    +

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

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

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

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

    @@ -244,6 +244,11 @@ plt.show()

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs025.html b/doc/pub/week45/html/._week45-bs025.html index bd18e3ec4..90e83e1b2 100644 --- a/doc/pub/week45/html/._week45-bs025.html +++ b/doc/pub/week45/html/._week45-bs025.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -180,23 +193,20 @@ MathJax.Hub.Config({ -

    XGBoost: Extreme Gradient Boosting

    +

    Steepest Descent Example

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

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

    -It is now the algorithm which wins essentially all ML competitions!!! +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.

    @@ -216,6 +226,11 @@ It is now the algorithm which wins essentially all ML competitions!!!

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/week45-bs.html b/doc/pub/week45/html/week45-bs.html index 39586fc8c..213838dad 100644 --- a/doc/pub/week45/html/week45-bs.html +++ b/doc/pub/week45/html/week45-bs.html @@ -43,64 +43,72 @@ Automatically generated HTML file from DocOnce source {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -140,31 +148,36 @@ MathJax.Hub.Config({ @@ -199,7 +212,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Oct 31, 2020

    +

    Nov 2, 2020


    @@ -223,7 +236,7 @@ MathJax.Hub.Config({

  • 9
  • 10
  • ...
  • -
  • 28
  • +
  • 33
  • »
  • diff --git a/doc/pub/week45/html/week45-reveal.html b/doc/pub/week45/html/week45-reveal.html index 185bba217..2c774648a 100644 --- a/doc/pub/week45/html/week45-reveal.html +++ b/doc/pub/week45/html/week45-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

     
    -

    Oct 31, 2020

    +

    Nov 2, 2020


    @@ -162,12 +162,12 @@ MathJax.Hub.Config({

    Overview of week 45

      -

    • "Thursday: Wrapping up from last week. Bagging and Random forests.
    • +

    • "Thursday: Wrapping up from last week. Bagging and Random forests. Boosting methods.
    • "Friday: Boosting and gradient boosting

    -Geron's chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion. +Geron's chapter 7. See also lecture from STK-IN4300, lecture 9. Chapter 10 (sections 10.1-10.10 are the most relevant ones) of Hastie et al contains also a good discussion. @@ -176,11 +176,193 @@ Geron's chapter 7. See also lecture from Random forests +

    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 you 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. However, after some thousands of tosses (sounds like you may have some spare time problems), 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. +

    + + +
    +

    Simple Voting Example, head or tail

    +

    + + +

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

    Using the Voting Classifier

    + +

    +We can use the voting classifier on other data sets, here the excting 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))
    +
    +
    + + +
    +

    Please, not the moons again! Voting and Bagging

    + +

    + + +

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

    + + +

    from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +

    + + +

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

    + + +

    from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +
    + + +
    +

    Random forests

    Random forests provide an improvement over bagged trees by way of a @@ -226,7 +408,7 @@ this setting.

    -

    Random Forest Algorithm

    +

    Random Forest Algorithm

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

    @@ -257,7 +439,7 @@ We will grow of forest of say \( B \) trees.

    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -331,7 +513,7 @@ plt.show()

    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    @@ -354,7 +536,7 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)

    -

    Boosting, a Bird's Eye View

    +

    Boosting, a Bird's Eye View

    The basic idea is to combine weak classifiers in order to create a good @@ -371,7 +553,7 @@ them with a factor.

    -

    What is boosting? Additive Modelling/Iterative Fitting

    +

    What is boosting? Additive Modelling/Iterative Fitting

    Boosting is a way of fitting an additive expansion in a set of @@ -431,7 +613,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re

    -

    Iterative Fitting, Regression and Squared-error Cost Function

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    The way we proceed is as follows (here we specialize to the squared-error cost function) @@ -457,7 +639,7 @@ at the internal nodes, and the predictions at the terminal nodes.

    -

    Squared-Error Example and Iterative Fitting

    +

    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. @@ -515,7 +697,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma

    -

    Iterative Fitting, Classification and AdaBoost

    +

    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 @@ -556,7 +738,7 @@ $$

    -

    Adaptive Boosting, AdaBoost

    +

    Adaptive Boosting, AdaBoost

    In our iterative procedure we define thus @@ -590,7 +772,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

    -

    Building up AdaBoost

    +

    Building up AdaBoost

    First, for any \( \beta > 0 \), we optimize \( G \) by setting @@ -648,7 +830,7 @@ $$

    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    The algorithm here is rather straightforward. Assume that our weak @@ -672,7 +854,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co

    -

    Basic Steps of AdaBoost

    +

    Basic Steps of AdaBoost

    With the above definitions we are now ready to set up the algorithm for AdaBoost. @@ -713,7 +895,7 @@ observations that are missed in the previous iterations.

    -

    AdaBoost Examples

    +

    AdaBoost Examples

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. @@ -747,7 +929,7 @@ plt.show()

    -

    AdaBoost for Regression

    +

    AdaBoost for Regression

    Here we present Drucker's AdaBoost tailored for regression. @@ -776,7 +958,7 @@ Start by selecting a set of training data \( n \) and assign to each entry a wei

    -

    Gradient boosting: Basics with Steepest Descent

    +

    Gradient boosting: Basics with Steepest Descent

    Gradient boosting is again a similar technique to Adaptive boosting, @@ -791,7 +973,7 @@ function was the least squares function.

    -

    The Squared-Error again! Steepest Descent

    +

    The Squared-Error again! Steepest Descent

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

    -

    Steepest Descent Example

    +

    Steepest Descent Example

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that @@ -856,7 +1038,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(

    -

    Gradient Boosting, algorithm

    +

    Gradient Boosting, algorithm

    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 @@ -884,7 +1066,7 @@ The way we proceed in an iterative fashion is to

    -

    Gradient Boosting Example, Regression

    +

    Gradient Boosting Example, Regression

    We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. @@ -892,7 +1074,7 @@ We discuss here the difference between the steepest descent approach and gradien

    -

    Gradient Boosting, Examples of Regression

    +

    Gradient Boosting, Examples of Regression

    @@ -947,7 +1129,7 @@ plt.show()

    -

    Gradient Boosting, Classification Example

    +

    Gradient Boosting, Classification Example

    @@ -996,7 +1178,7 @@ plt.show()

    -

    XGBoost: Extreme Gradient Boosting

    +

    XGBoost: Extreme Gradient Boosting

    XGBoost or Extreme Gradient @@ -1017,7 +1199,7 @@ It is now the algorithm which wins essentially all ML competitions!!!

    -

    Regression Case

    +

    Regression Case

    @@ -1073,7 +1255,7 @@ plt.show()

    -

    Xgboost on the Cancer Data

    +

    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. diff --git a/doc/pub/week45/html/week45-solarized.html b/doc/pub/week45/html/week45-solarized.html index 43e4bfa95..57e21a0d0 100644 --- a/doc/pub/week45/html/week45-solarized.html +++ b/doc/pub/week45/html/week45-solarized.html @@ -37,64 +37,72 @@ div { text-align: justify; text-justify: inter-word; } {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -136,7 +144,7 @@ MathJax.Hub.Config({

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

    -

    Oct 31, 2020

    +

    Nov 2, 2020












    @@ -144,11 +152,11 @@ MathJax.Hub.Config({

    Overview of week 45

      -
    • "Thursday: Wrapping up from last week. Bagging and Random forests.
    • +
    • "Thursday: Wrapping up from last week. Bagging and Random forests. Boosting methods.
    • "Friday: Boosting and gradient boosting
    -Geron's chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion. +Geron's chapter 7. See also lecture from
    STK-IN4300, lecture 9. Chapter 10 (sections 10.1-10.10 are the most relevant ones) of Hastie et al contains also a good discussion.











    @@ -157,11 +165,190 @@ Geron's chapter 7. See also lecture from Random forests +

    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 you 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. However, after some thousands of tosses (sounds like you may have some spare time problems), 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. + +

    +









    + +

    Simple Voting Example, head or tail

    +

    + + +

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

    +









    + +

    Using the Voting Classifier

    + +

    +We can use the voting classifier on other data sets, here the excting 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))
    +
    +

    +









    + +

    Please, not the moons again! Voting and Bagging

    + +

    + + +

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

    + + +

    from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +

    + + +

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

    + + +

    from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +

    +









    + +

    Random forests

    Random forests provide an improvement over bagged trees by way of a @@ -205,7 +392,7 @@ this setting.











    -

    Random Forest Algorithm

    +

    Random Forest Algorithm

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

    @@ -231,7 +418,7 @@ We will grow of forest of say \( B \) trees.









    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -304,7 +491,7 @@ plt.show()











    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    @@ -326,7 +513,7 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)











    -

    Boosting, a Bird's Eye View

    +

    Boosting, a Bird's Eye View

    The basic idea is to combine weak classifiers in order to create a good @@ -343,7 +530,7 @@ them with a factor.











    -

    What is boosting? Additive Modelling/Iterative Fitting

    +

    What is boosting? Additive Modelling/Iterative Fitting

    Boosting is a way of fitting an additive expansion in a set of @@ -395,7 +582,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re











    -

    Iterative Fitting, Regression and Squared-error Cost Function

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    The way we proceed is as follows (here we specialize to the squared-error cost function) @@ -420,7 +607,7 @@ at the internal nodes, and the predictions at the terminal nodes.











    -

    Squared-Error Example and Iterative Fitting

    +

    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. @@ -468,7 +655,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma











    -

    Iterative Fitting, Classification and AdaBoost

    +

    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 @@ -503,7 +690,7 @@ $$











    -

    Adaptive Boosting, AdaBoost

    +

    Adaptive Boosting, AdaBoost

    In our iterative procedure we define thus @@ -531,7 +718,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).











    -

    Building up AdaBoost

    +

    Building up AdaBoost

    First, for any \( \beta > 0 \), we optimize \( G \) by setting @@ -575,7 +762,7 @@ $$











    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    The algorithm here is rather straightforward. Assume that our weak @@ -597,7 +784,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co











    -

    Basic Steps of AdaBoost

    +

    Basic Steps of AdaBoost

    With the above definitions we are now ready to set up the algorithm for AdaBoost. @@ -637,7 +824,7 @@ observations that are missed in the previous iterations.











    -

    AdaBoost Examples

    +

    AdaBoost Examples

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. @@ -670,7 +857,7 @@ plt.show()











    -

    AdaBoost for Regression

    +

    AdaBoost for Regression

    Here we present Drucker's AdaBoost tailored for regression. @@ -698,7 +885,7 @@ Start by selecting a set of training data \( n \) and assign to each entry a wei











    -

    Gradient boosting: Basics with Steepest Descent

    +

    Gradient boosting: Basics with Steepest Descent

    Gradient boosting is again a similar technique to Adaptive boosting, @@ -713,7 +900,7 @@ function was the least squares function.











    -

    The Squared-Error again! Steepest Descent

    +

    The Squared-Error again! Steepest Descent

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











    -

    Steepest Descent Example

    +

    Steepest Descent Example

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that @@ -766,7 +953,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(











    -

    Gradient Boosting, algorithm

    +

    Gradient Boosting, algorithm

    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 @@ -792,7 +979,7 @@ The way we proceed in an iterative fashion is to









    -

    Gradient Boosting Example, Regression

    +

    Gradient Boosting Example, Regression

    We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. @@ -800,7 +987,7 @@ We discuss here the difference between the steepest descent approach and gradien











    -

    Gradient Boosting, Examples of Regression

    +

    Gradient Boosting, Examples of Regression

    @@ -854,7 +1041,7 @@ plt.show()











    -

    Gradient Boosting, Classification Example

    +

    Gradient Boosting, Classification Example

    @@ -902,7 +1089,7 @@ plt.show()











    -

    XGBoost: Extreme Gradient Boosting

    +

    XGBoost: Extreme Gradient Boosting

    XGBoost or Extreme Gradient @@ -923,7 +1110,7 @@ It is now the algorithm which wins essentially all ML competitions!!!











    -

    Regression Case

    +

    Regression Case

    @@ -978,7 +1165,7 @@ plt.show()











    -

    Xgboost on the Cancer Data

    +

    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. diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html index 7617607e2..f6214a740 100644 --- a/doc/pub/week45/html/week45.html +++ b/doc/pub/week45/html/week45.html @@ -42,64 +42,72 @@ div { text-align: justify; text-justify: inter-word; } {'highest level': 2, 'sections': [('Overview of week 45', 2, None, '___sec0'), ('Thursday', 2, None, '___sec1'), - ('Random forests', 2, None, '___sec2'), - ('Random Forest Algorithm', 2, None, '___sec3'), + ('Why Voting?', 2, None, '___sec2'), + ('Tossing coins', 2, None, '___sec3'), + ('Simple Voting Example, head or tail', 2, None, '___sec4'), + ('Using the Voting Classifier', 2, None, '___sec5'), + ('Please, not the moons again! Voting and Bagging', + 2, + None, + '___sec6'), + ('Random forests', 2, None, '___sec7'), + ('Random Forest Algorithm', 2, None, '___sec8'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec4'), + '___sec9'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec5'), - ("Boosting, a Bird's Eye View", 2, None, '___sec6'), + '___sec10'), + ("Boosting, a Bird's Eye View", 2, None, '___sec11'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec7'), + '___sec12'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec8'), + '___sec13'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec9'), + '___sec14'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec10'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec11'), - ('Building up AdaBoost', 2, None, '___sec12'), + '___sec15'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec16'), + ('Building up AdaBoost', 2, None, '___sec17'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec13'), - ('Basic Steps of AdaBoost', 2, None, '___sec14'), - ('AdaBoost Examples', 2, None, '___sec15'), - ('AdaBoost for Regression', 2, None, '___sec16'), + '___sec18'), + ('Basic Steps of AdaBoost', 2, None, '___sec19'), + ('AdaBoost Examples', 2, None, '___sec20'), + ('AdaBoost for Regression', 2, None, '___sec21'), ('Gradient boosting: Basics with Steepest Descent', 2, None, - '___sec17'), + '___sec22'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec18'), - ('Steepest Descent Example', 2, None, '___sec19'), - ('Gradient Boosting, algorithm', 2, None, '___sec20'), - ('Gradient Boosting Example, Regression', 2, None, '___sec21'), + '___sec23'), + ('Steepest Descent Example', 2, None, '___sec24'), + ('Gradient Boosting, algorithm', 2, None, '___sec25'), + ('Gradient Boosting Example, Regression', 2, None, '___sec26'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec22'), + '___sec27'), ('Gradient Boosting, Classification Example', 2, None, - '___sec23'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec24'), - ('Regression Case', 2, None, '___sec25'), - ('Xgboost on the Cancer Data', 2, None, '___sec26')]} + '___sec28'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec29'), + ('Regression Case', 2, None, '___sec30'), + ('Xgboost on the Cancer Data', 2, None, '___sec31')]} end of tocinfo --> @@ -141,7 +149,7 @@ MathJax.Hub.Config({

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

    -

    Oct 31, 2020

    +

    Nov 2, 2020












    @@ -149,11 +157,11 @@ MathJax.Hub.Config({

    Overview of week 45

      -
    • "Thursday: Wrapping up from last week. Bagging and Random forests.
    • +
    • "Thursday: Wrapping up from last week. Bagging and Random forests. Boosting methods.
    • "Friday: Boosting and gradient boosting
    -Geron's chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion. +Geron's chapter 7. See also lecture from STK-IN4300, lecture 9. Chapter 10 (sections 10.1-10.10 are the most relevant ones) of Hastie et al contains also a good discussion.











    @@ -162,11 +170,190 @@ Geron's chapter 7. See also lecture from Random forests +

    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 you 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. However, after some thousands of tosses (sounds like you may have some spare time problems), 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. + +

    +









    + +

    Simple Voting Example, head or tail

    +

    + + +

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

    +









    + +

    Using the Voting Classifier

    + +

    +We can use the voting classifier on other data sets, here the excting 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))
    +
    +

    +









    + +

    Please, not the moons again! Voting and Bagging

    + +

    + + +

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

    + + +

    from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +

    + + +

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

    + + +

    from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +

    +









    + +

    Random forests

    Random forests provide an improvement over bagged trees by way of a @@ -210,7 +397,7 @@ this setting.











    -

    Random Forest Algorithm

    +

    Random Forest Algorithm

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

    @@ -236,7 +423,7 @@ We will grow of forest of say \( B \) trees.









    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -309,7 +496,7 @@ plt.show()











    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    @@ -331,7 +518,7 @@ np.sum(y_pred =











    -

    Boosting, a Bird's Eye View

    +

    Boosting, a Bird's Eye View

    The basic idea is to combine weak classifiers in order to create a good @@ -348,7 +535,7 @@ them with a factor.











    -

    What is boosting? Additive Modelling/Iterative Fitting

    +

    What is boosting? Additive Modelling/Iterative Fitting

    Boosting is a way of fitting an additive expansion in a set of @@ -400,7 +587,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re











    -

    Iterative Fitting, Regression and Squared-error Cost Function

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    The way we proceed is as follows (here we specialize to the squared-error cost function) @@ -425,7 +612,7 @@ at the internal nodes, and the predictions at the terminal nodes.











    -

    Squared-Error Example and Iterative Fitting

    +

    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. @@ -473,7 +660,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma











    -

    Iterative Fitting, Classification and AdaBoost

    +

    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 @@ -508,7 +695,7 @@ $$











    -

    Adaptive Boosting, AdaBoost

    +

    Adaptive Boosting, AdaBoost

    In our iterative procedure we define thus @@ -536,7 +723,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).











    -

    Building up AdaBoost

    +

    Building up AdaBoost

    First, for any \( \beta > 0 \), we optimize \( G \) by setting @@ -580,7 +767,7 @@ $$











    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    The algorithm here is rather straightforward. Assume that our weak @@ -602,7 +789,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co











    -

    Basic Steps of AdaBoost

    +

    Basic Steps of AdaBoost

    With the above definitions we are now ready to set up the algorithm for AdaBoost. @@ -642,7 +829,7 @@ observations that are missed in the previous iterations.











    -

    AdaBoost Examples

    +

    AdaBoost Examples

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. @@ -675,7 +862,7 @@ plt.show()











    -

    AdaBoost for Regression

    +

    AdaBoost for Regression

    Here we present Drucker's AdaBoost tailored for regression. @@ -703,7 +890,7 @@ Start by selecting a set of training data \( n \) and assign to each entry a wei











    -

    Gradient boosting: Basics with Steepest Descent

    +

    Gradient boosting: Basics with Steepest Descent

    Gradient boosting is again a similar technique to Adaptive boosting, @@ -718,7 +905,7 @@ function was the least squares function.











    -

    The Squared-Error again! Steepest Descent

    +

    The Squared-Error again! Steepest Descent

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











    -

    Steepest Descent Example

    +

    Steepest Descent Example

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that @@ -771,7 +958,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(











    -

    Gradient Boosting, algorithm

    +

    Gradient Boosting, algorithm

    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 @@ -797,7 +984,7 @@ The way we proceed in an iterative fashion is to









    -

    Gradient Boosting Example, Regression

    +

    Gradient Boosting Example, Regression

    We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. @@ -805,7 +992,7 @@ We discuss here the difference between the steepest descent approach and gradien











    -

    Gradient Boosting, Examples of Regression

    +

    Gradient Boosting, Examples of Regression

    @@ -859,7 +1046,7 @@ plt.show()











    -

    Gradient Boosting, Classification Example

    +

    Gradient Boosting, Classification Example

    @@ -907,7 +1094,7 @@ plt.show()











    -

    XGBoost: Extreme Gradient Boosting

    +

    XGBoost: Extreme Gradient Boosting

    XGBoost or Extreme Gradient @@ -928,7 +1115,7 @@ It is now the algorithm which wins essentially all ML competitions!!!











    -

    Regression Case

    +

    Regression Case

    @@ -983,7 +1170,7 @@ plt.show()











    -

    Xgboost on the Cancer Data

    +

    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. diff --git a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz index f8420afba1eab6f41ae0e83da4170995a5f77fd0..2e7cca3f414d512e7742c36bc256f3f3245ab0c9 100644 GIT binary patch literal 191 zcmV;w06_mAiwFRVA)sFX1MSaC3c@fD2H>uHia9|^Owz6eUAPcLyg*8)Hdd3Gq-bw% zAD}D6O%WmA=4X;&nAxwFtL-}RcOT7$5R!5ZLuRQMlPsosM5zGEGSR=1lrkWcG0q|& z^R4vKIxlU%N_9f*P`~Z#+sg98oaq#J=ASrJ%E4yW`O0X}#$#?w4L8J^i$pb@&Y>{q thA*&qZIwlkx&v7h$}6MgIc}^uT6u9v{Oe{q sh89@7w#p(%-GM9$<(1L$95>b+t-QD-{`E6K5Cp;39`n6WmH-F<0K#Bi)c^nh diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb index d7b453b7b..d8e9702c6 100644 --- a/doc/pub/week45/ipynb/week45.ipynb +++ b/doc/pub/week45/ipynb/week45.ipynb @@ -10,7 +10,7 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Oct 31, 2020**\n", + "Date: **Nov 2, 2020**\n", "\n", "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", @@ -18,18 +18,226 @@ "\n", "## Overview of week 45\n", "\n", - "* \"Thursday: Wrapping up from last week. Bagging and Random forests.\n", + "* \"Thursday: Wrapping up from last week. Bagging and Random forests. Boosting methods.\n", "\n", "* \"Friday: Boosting and gradient boosting\n", "\n", - "Geron's chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion.\n", + "Geron's chapter 7. See also lecture from [STK-IN4300, lecture 9](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_9.pdf). Chapter 10 (sections 10.1-10.10 are the most relevant ones) of Hastie et al contains also a good discussion.\n", "\n", "\n", "## Thursday\n", "\n", "Bagging, voting and random forests.\n", + "The material on bagging and voting is a repeat from last week and can be found in the slides from week 44.\n", + "We repeat here the voting approach since this will serve as a motivation for boosting methods later.\n", "\n", + "## 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. \n", + "\n", + "## Tossing coins\n", + "The simplest case is a so-called voting ensemble. To illustrate this, Think of you tossing coins with a biased outcome of 51 per cent for heads and 49% for tails.\n", + "With only few tosses, you may not clearly see this distribution. However, after some thousands of tosses (sounds like you may have some spare time problems), there will be a clear majority of heads.\n", + "With 2000 tosses 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 you do this ten thousand times, it is easy to see that there is a 97% 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, clealry demostrating that after some tosses we see the law of large numbers kicking in.\n", + "\n", + "## Simple Voting Example, head or tail" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "heads_proba = 0.51\n", + "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n", + "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n", + "plt.figure(figsize=(8,3.5))\n", + "plt.plot(cumulative_heads_ratio)\n", + "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n", + "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n", + "plt.xlabel(\"Number of coin tosses\")\n", + "plt.ylabel(\"Heads ratio\")\n", + "plt.legend(loc=\"lower right\")\n", + "plt.axis([0, 10000, 0.42, 0.58])\n", + "save_fig(\"votingsimple\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using the Voting Classifier\n", + "\n", + "We can use the voting classifier on other data sets, here the excting binary case of two distinct objects using the make moons functionality of -Scikit-Learn-." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "from sklearn.datasets import make_moons\n", + "\n", + "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n", + "\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", + "metadata": {}, + "source": [ + "## Please, not the moons again! Voting and Bagging" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "from sklearn.datasets import make_moons\n", + "\n", + "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.svm import SVC\n", + "\n", + "log_clf = LogisticRegression(random_state=42)\n", + "rnd_clf = RandomForestClassifier(random_state=42)\n", + "svm_clf = SVC(random_state=42)\n", + "\n", + "voting_clf = VotingClassifier(\n", + " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", + " voting='hard')\n", + "voting_clf.fit(X_train, y_train)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.metrics import accuracy_score\n", + "\n", + "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", + " clf.fit(X_train, y_train)\n", + " y_pred = clf.predict(X_test)\n", + " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "log_clf = LogisticRegression(random_state=42)\n", + "rnd_clf = RandomForestClassifier(random_state=42)\n", + "svm_clf = SVC(probability=True, random_state=42)\n", + "\n", + "voting_clf = VotingClassifier(\n", + " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", + " voting='soft')\n", + "voting_clf.fit(X_train, y_train)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.metrics import accuracy_score\n", + "\n", + "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", + " clf.fit(X_train, y_train)\n", + " y_pred = clf.predict(X_test)\n", + " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "## Random forests\n", "\n", "Random forests provide an improvement over bagged trees by way of a\n", @@ -102,7 +310,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 7, "metadata": { "collapsed": false }, @@ -186,7 +394,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 8, "metadata": { "collapsed": false }, @@ -199,7 +407,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 9, "metadata": { "collapsed": false }, @@ -743,7 +951,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 10, "metadata": { "collapsed": false }, @@ -956,7 +1164,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 11, "metadata": { "collapsed": false }, @@ -1019,7 +1227,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 12, "metadata": { "collapsed": false }, @@ -1092,7 +1300,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 13, "metadata": { "collapsed": false }, @@ -1157,7 +1365,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 14, "metadata": { "collapsed": false },