diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html index cfc8c9a63..263295b72 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html index ce0cd4709..79fbfc13e 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html index 826c588f6..54da0e0de 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html index 7227d3372..12f9d3166 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html index 95963bdbe..18a6fbe9b 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html index 7c89669c1..1a1bd8838 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html index d66b98492..500fbf4fa 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html index 0127d1301..d511cd5de 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html index 212fcf49e..11194998e 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html index 697c502e2..eb5aa5671 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html index d255f36e7..85b95dded 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html index 88e444f30..4be724e7f 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html index 2809ab887..72a1783d5 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html index 4f42c7a2b..3b717abff 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html index 02016f7be..c12a0d38c 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html index 7fd9c8230..8b6cf4b08 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html index 8c7b4e80d..60adf1836 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html index 904e184ad..d35ad431d 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html index 644fe7bbb..f1b07f07e 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html index 8d2a18b42..528dedd74 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html index a1a708d79..715646b0a 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html index c0c27cf60..a050b8b34 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html index cf1324afa..0177f1aae 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html index 1e3e04676..eea8b3d83 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html index 4be1ac486..9b371bc57 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html index b6806a8e1..0120d48af 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html index 7ab79cd45..b0014d62f 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html index 785b455fa..e19d0024e 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html index 7755c7d4d..62f8fa987 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html index ed615163d..fad03ce5d 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html index f7faa8f50..3431c71d4 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html index 5c6217b3f..62a37dcb0 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs032.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs032.html index 711b9c8e6..42345f6bb 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs032.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs032.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs033.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs033.html index d1b16089b..89a1e8210 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs033.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs033.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs034.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs034.html index 04be98f42..b3329a307 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs034.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs034.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs035.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs035.html index 0750e65bb..09eed4d06 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs035.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs035.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs036.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs036.html index f234a1f54..21fd02d4b 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs036.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs036.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs037.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs037.html index da7b2e0c1..33e9ecf58 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs037.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs037.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs038.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs038.html index 3b1d454d3..cc87226ec 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs038.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs038.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs039.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs039.html index c5850d1bb..f08ea8d23 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs039.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs039.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs040.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs040.html index b63ab6261..c3d1f4f4d 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs040.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs040.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs041.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs041.html index dbd2fe7c9..d2471d168 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs041.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs041.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs042.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs042.html index 9483dcfa1..795ef5233 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs042.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs042.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs043.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs043.html index 45f547496..459bb57ff 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs043.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs043.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs044.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs044.html index 7e7fe255f..757cecffe 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs044.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs044.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • @@ -240,74 +240,61 @@ MathJax.Hub.Config({ -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    +

    import matplotlib.pyplot as plt
     import numpy as np
    -from sklearn.model_selection import  train_test_split 
    -from sklearn.datasets import load_breast_cancer
    -from sklearn.svm import SVC
    -from sklearn.linear_model import LogisticRegression
    -from sklearn.tree import DecisionTreeClassifier
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.ensemble import RandomForestRegressor
     
    -# Load the data
    -cancer = load_breast_cancer()
    +np.random.seed(2018)
    +
    +n = 100
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
     
    -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)))
     
    +for degree in range(maxdegree):
    +    model = RandomForestRegressor()
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_.ravel())
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
     
    -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)))
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
     
    -
    -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.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
     plt.show()
     

    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs045.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs045.html index 4372127c9..17be7fe3c 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs045.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs045.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({

  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • @@ -240,24 +240,75 @@ MathJax.Hub.Config({ -

    Compare Bagging on Trees with Random Forests

    +

    Random Forests Compared with other Methods on the Cancer Data

    -

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

    +

    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)))
    +
     
    -
    -
    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.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +# Data set not specificied
    +#Instantiate the model with 500 trees and entropy as splitting criteria
    +Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
    +Random_Forest_model.fit(X_train_scaled, y_train)
    +#Cross validation
    +accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
    +print(accuracy)
    +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
    +
    +
    +import scikitplot as skplt
    +y_pred = Random_Forest_model.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = Random_Forest_model.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +plt.show()
     

    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs046.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs046.html index 09ecd3191..04cbb3018 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs046.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs046.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({

  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • @@ -240,62 +240,24 @@ MathJax.Hub.Config({ -

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    - +

    Compare Bagging on Trees with Random Forests

    -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -from sklearn.ensemble import RandomForestRegressor
    +
    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)
    +
    +

    -np.random.seed(2018) - -n = 100 -n_boostraps = 100 -maxdegree = 14 - -# 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) - -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) - -for degree in range(maxdegree): - model = RandomForestRegressor() - y_pred = np.empty((y_test.shape[0], n_boostraps)) - for i in range(n_boostraps): - x_, y_ = resample(X_train_scaled, y_train) - model.fit(x_, y_.ravel()) - y_pred[:, i] = model.predict(X_test_scaled).ravel() - - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) - variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) - print('Polynomial degree:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.plot(polydegree, error, label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -plt.show() + +

    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) 
     

    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs047.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs047.html index 2c10930ed..2eb3e3331 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs047.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs047.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({

  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs048.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs048.html index 633771aec..307d7d155 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs048.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs048.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs049.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs049.html index 0a56c63ac..720cd6745 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs049.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs049.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs050.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs050.html index c12d3cb33..b0f46a328 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs050.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs050.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs051.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs051.html index cbbe511d6..89e47b91f 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs051.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs051.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs052.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs052.html index 5b430bec9..61212693a 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs052.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs052.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs053.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs053.html index 6dabddbf2..255a7b826 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs053.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs053.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs054.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs054.html index 7f4292f42..0178c6e44 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs054.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs054.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs055.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs055.html index e5de741a6..00eaee4c4 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs055.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs055.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs056.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs056.html index 93ffabf9c..7d8c8d74c 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs056.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs056.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs057.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs057.html index 08bf5350e..6a1d2bd8b 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs057.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs057.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-bs.html b/doc/pub/DecisionTrees/html/DecisionTrees-bs.html index cfc8c9a63..263295b72 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees-bs.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees-bs.html @@ -104,16 +104,16 @@ Automatically generated HTML file from DocOnce source ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -211,9 +211,9 @@ MathJax.Hub.Config({
  • Changing the Level of the Decision Tree
  • Random forests
  • Random Forest Algorithm
  • -
  • Random Forests Compared with other Methods on the Cancer Data
  • -
  • Compare Bagging on Trees with Random Forests
  • -
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Bootstrap with Random Forests Instead of a Single Tree, own Bagging
  • +
  • Random Forests Compared with other Methods on the Cancer Data
  • +
  • Compare Bagging on Trees with Random Forests
  • Boosting, a Bird'e Eye
  • Adaptive boosting: AdaBoost, Basic Algorithm
  • Basic Steps of AdaBoost
  • diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html b/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html index debbea6c2..0d1365a1e 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html @@ -1914,7 +1914,68 @@ We will grow of forest of say \( M \) trees.
    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    + +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.ensemble import RandomForestRegressor
    +
    +np.random.seed(2018)
    +
    +n = 100
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = RandomForestRegressor()
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_.ravel())
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +
    + + +
    +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -1988,7 +2049,7 @@ plt.show()

    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    @@ -2010,67 +2071,6 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)

    -
    -

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    - -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -from sklearn.ensemble import RandomForestRegressor
    -
    -np.random.seed(2018)
    -
    -n = 100
    -n_boostraps = 100
    -maxdegree = 14
    -
    -# 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)
    -
    -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)
    -
    -for degree in range(maxdegree):
    -    model = RandomForestRegressor()
    -    y_pred = np.empty((y_test.shape[0], n_boostraps))
    -    for i in range(n_boostraps):
    -        x_, y_ = resample(X_train_scaled, y_train)
    -        model.fit(x_, y_.ravel())
    -        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    -
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -    print('Polynomial degree:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    -
    -
    - -

    Boosting, a Bird'e Eye

    diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html b/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html index b220f97f4..1d6e730c8 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html @@ -124,16 +124,16 @@ div { text-align: justify; text-justify: inter-word; } ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -1904,7 +1904,67 @@ We will grow of forest of say \( M \) trees.









    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    + +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.ensemble import RandomForestRegressor
    +
    +np.random.seed(2018)
    +
    +n = 100
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = RandomForestRegressor()
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_.ravel())
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +

    +









    + +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -1977,7 +2037,7 @@ plt.show()











    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    @@ -1999,66 +2059,6 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)











    -

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    - -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -from sklearn.ensemble import RandomForestRegressor
    -
    -np.random.seed(2018)
    -
    -n = 100
    -n_boostraps = 100
    -maxdegree = 14
    -
    -# 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)
    -
    -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)
    -
    -for degree in range(maxdegree):
    -    model = RandomForestRegressor()
    -    y_pred = np.empty((y_test.shape[0], n_boostraps))
    -    for i in range(n_boostraps):
    -        x_, y_ = resample(X_train_scaled, y_train)
    -        model.fit(x_, y_.ravel())
    -        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    -
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -    print('Polynomial degree:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    -
    -

    -









    -

    Boosting, a Bird'e Eye

    diff --git a/doc/pub/DecisionTrees/html/DecisionTrees.html b/doc/pub/DecisionTrees/html/DecisionTrees.html index 98e5b068e..e66d392b2 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees.html @@ -129,16 +129,16 @@ div { text-align: justify; text-justify: inter-word; } ('Changing the Level of the Decision Tree', 2, None, '___sec40'), ('Random forests', 2, None, '___sec41'), ('Random Forest Algorithm', 2, None, '___sec42'), - ('Random Forests Compared with other Methods on the Cancer Data', + ('Bootstrap with Random Forests Instead of a Single Tree, own ' + 'Bagging', 2, None, '___sec43'), - ('Compare Bagging on Trees with Random Forests', + ('Random Forests Compared with other Methods on the Cancer Data', 2, None, '___sec44'), - ('Bootstrap with Random Forests Instead of a Single Tree, own ' - 'Bagging', + ('Compare Bagging on Trees with Random Forests', 2, None, '___sec45'), @@ -1909,7 +1909,67 @@ We will grow of forest of say \( M \) trees.









    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    + +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.ensemble import RandomForestRegressor
    +
    +np.random.seed(2018)
    +
    +n = 100
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = RandomForestRegressor()
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_.ravel())
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +

    +









    + +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -1982,7 +2042,7 @@ plt.show()











    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    @@ -2004,66 +2064,6 @@ np.sum(y_pred =











    -

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    - -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -from sklearn.ensemble import RandomForestRegressor
    -
    -np.random.seed(2018)
    -
    -n = 100
    -n_boostraps = 100
    -maxdegree = 14
    -
    -# 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)
    -
    -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)
    -
    -for degree in range(maxdegree):
    -    model = RandomForestRegressor()
    -    y_pred = np.empty((y_test.shape[0], n_boostraps))
    -    for i in range(n_boostraps):
    -        x_, y_ = resample(X_train_scaled, y_train)
    -        model.fit(x_, y_.ravel())
    -        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    -
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -    print('Polynomial degree:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    -
    -

    -









    -

    Boosting, a Bird'e Eye

    diff --git a/doc/pub/DecisionTrees/ipynb/DataFiles/cancer.dot b/doc/pub/DecisionTrees/ipynb/DataFiles/cancer.dot index a8bce3417..4d258be18 100644 --- a/doc/pub/DecisionTrees/ipynb/DataFiles/cancer.dot +++ b/doc/pub/DecisionTrees/ipynb/DataFiles/cancer.dot @@ -6,15 +6,15 @@ edge [fontname=helvetica] ; 0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ; 2 [label="worst concave points <= 0.135\ngini = 0.031\nsamples = 253\nvalue = [[249, 4]\n[4, 249]]", fillcolor="#e58139ee"] ; 1 -> 2 ; -3 [label="area error <= 48.975\ngini = 0.008\nsamples = 242\nvalue = [[241, 1]\n[1, 241]]", fillcolor="#e58139fb"] ; +3 [label="radius error <= 0.643\ngini = 0.008\nsamples = 242\nvalue = [[241, 1]\n[1, 241]]", fillcolor="#e58139fb"] ; 2 -> 3 ; 4 [label="gini = 0.0\nsamples = 239\nvalue = [[239, 0]\n[0, 239]]", fillcolor="#e58139ff"] ; 3 -> 4 ; -5 [label="mean area <= 469.25\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#e5813913"] ; +5 [label="texture error <= 1.938\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#e5813913"] ; 3 -> 5 ; -6 [label="gini = 0.0\nsamples = 1\nvalue = [[0, 1]\n[1, 0]]", fillcolor="#e58139ff"] ; +6 [label="gini = 0.0\nsamples = 2\nvalue = [[2, 0]\n[0, 2]]", fillcolor="#e58139ff"] ; 5 -> 6 ; -7 [label="gini = 0.0\nsamples = 2\nvalue = [[2, 0]\n[0, 2]]", fillcolor="#e58139ff"] ; +7 [label="gini = 0.0\nsamples = 1\nvalue = [[0, 1]\n[1, 0]]", fillcolor="#e58139ff"] ; 5 -> 7 ; 8 [label="mean texture <= 20.84\ngini = 0.397\nsamples = 11\nvalue = [[8, 3]\n[3, 8]]", fillcolor="#e581392c"] ; 2 -> 8 ; @@ -22,7 +22,7 @@ edge [fontname=helvetica] ; 8 -> 9 ; 10 [label="gini = 0.0\nsamples = 3\nvalue = [[0, 3]\n[3, 0]]", fillcolor="#e58139ff"] ; 8 -> 10 ; -11 [label="mean texture <= 16.22\ngini = 0.278\nsamples = 6\nvalue = [[1, 5]\n[5, 1]]", fillcolor="#e581396b"] ; +11 [label="area error <= 13.475\ngini = 0.278\nsamples = 6\nvalue = [[1, 5]\n[5, 1]]", fillcolor="#e581396b"] ; 1 -> 11 ; 12 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ; 11 -> 12 ; @@ -30,11 +30,11 @@ edge [fontname=helvetica] ; 11 -> 13 ; 14 [label="worst texture <= 20.645\ngini = 0.202\nsamples = 167\nvalue = [[19, 148]\n[148, 19]]", fillcolor="#e5813994"] ; 0 -> 14 [labeldistance=2.5, labelangle=-45, headlabel="False"] ; -15 [label="worst area <= 964.4\ngini = 0.375\nsamples = 16\nvalue = [[12, 4]\n[4, 12]]", fillcolor="#e5813938"] ; +15 [label="worst concavity <= 0.318\ngini = 0.375\nsamples = 16\nvalue = [[12, 4]\n[4, 12]]", fillcolor="#e5813938"] ; 14 -> 15 ; 16 [label="gini = 0.0\nsamples = 11\nvalue = [[11, 0]\n[0, 11]]", fillcolor="#e58139ff"] ; 15 -> 16 ; -17 [label="mean fractal dimension <= 0.054\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#e5813955"] ; +17 [label="mean concavity <= 0.07\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#e5813955"] ; 15 -> 17 ; 18 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ; 17 -> 18 ; @@ -42,7 +42,7 @@ edge [fontname=helvetica] ; 17 -> 19 ; 20 [label="mean concave points <= 0.049\ngini = 0.088\nsamples = 151\nvalue = [[7, 144]\n[144, 7]]", fillcolor="#e58139d0"] ; 14 -> 20 ; -21 [label="concave points error <= 0.01\ngini = 0.48\nsamples = 15\nvalue = [[6, 9]\n[9, 6]]", fillcolor="#e5813900"] ; +21 [label="compactness error <= 0.016\ngini = 0.48\nsamples = 15\nvalue = [[6, 9]\n[9, 6]]", fillcolor="#e5813900"] ; 20 -> 21 ; 22 [label="gini = 0.0\nsamples = 9\nvalue = [[0, 9]\n[9, 0]]", fillcolor="#e58139ff"] ; 21 -> 22 ; diff --git a/doc/pub/DecisionTrees/ipynb/DataFiles/cancer.png b/doc/pub/DecisionTrees/ipynb/DataFiles/cancer.png index 22ae432a0..98014cc9c 100644 Binary files a/doc/pub/DecisionTrees/ipynb/DataFiles/cancer.png and b/doc/pub/DecisionTrees/ipynb/DataFiles/cancer.png differ diff --git a/doc/pub/DecisionTrees/ipynb/DecisionTrees.ipynb b/doc/pub/DecisionTrees/ipynb/DecisionTrees.ipynb index 6353b4ab0..1161b80b6 100644 --- a/doc/pub/DecisionTrees/ipynb/DecisionTrees.ipynb +++ b/doc/pub/DecisionTrees/ipynb/DecisionTrees.ipynb @@ -1935,7 +1935,7 @@ "\n", "4. Output then the ensemble of trees $\\{T_m\\}_1^{M}$ and make predictions for either a regression type of problem or a classification type of problem. \n", "\n", - "## Random Forests Compared with other Methods on the Cancer Data" + "## Bootstrap with Random Forests Instead of a Single Tree, own Bagging" ] }, { @@ -1945,6 +1945,75 @@ "collapsed": false }, "outputs": [], + "source": [ + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "np.random.seed(2018)\n", + "\n", + "n = 100\n", + "n_boostraps = 100\n", + "maxdegree = 14\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "error = np.zeros(maxdegree)\n", + "bias = np.zeros(maxdegree)\n", + "variance = np.zeros(maxdegree)\n", + "polydegree = np.zeros(maxdegree)\n", + "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "for degree in range(maxdegree):\n", + " model = RandomForestRegressor()\n", + " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", + " for i in range(n_boostraps):\n", + " x_, y_ = resample(X_train_scaled, y_train)\n", + " model.fit(x_, y_.ravel())\n", + " y_pred[:, i] = model.predict(X_test_scaled).ravel()\n", + "\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", + " print('Polynomial degree:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "plt.plot(polydegree, error, label='Error')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Random Forests Compared with other Methods on the Cancer Data" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", @@ -2022,7 +2091,7 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 28, "metadata": { "collapsed": false }, @@ -2035,7 +2104,7 @@ }, { "cell_type": "code", - "execution_count": 28, + "execution_count": 29, "metadata": { "collapsed": false }, @@ -2050,75 +2119,6 @@ "np.sum(y_pred == y_pred_rf) / len(y_pred)" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Bootstrap with Random Forests Instead of a Single Tree, own Bagging" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "from sklearn.ensemble import RandomForestRegressor\n", - "\n", - "np.random.seed(2018)\n", - "\n", - "n = 100\n", - "n_boostraps = 100\n", - "maxdegree = 14\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "error = np.zeros(maxdegree)\n", - "bias = np.zeros(maxdegree)\n", - "variance = np.zeros(maxdegree)\n", - "polydegree = np.zeros(maxdegree)\n", - "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "for degree in range(maxdegree):\n", - " model = RandomForestRegressor()\n", - " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - " for i in range(n_boostraps):\n", - " x_, y_ = resample(X_train_scaled, y_train)\n", - " model.fit(x_, y_.ravel())\n", - " y_pred[:, i] = model.predict(X_test_scaled).ravel()\n", - "\n", - " polydegree[degree] = degree\n", - " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - " print('Polynomial degree:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " print('Var:', variance[degree])\n", - " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", - "\n", - "plt.plot(polydegree, error, label='Error')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "plt.show()" - ] - }, { "cell_type": "markdown", "metadata": {}, diff --git a/doc/pub/DecisionTrees/ipynb/ipynb-DecisionTrees-src.tar.gz b/doc/pub/DecisionTrees/ipynb/ipynb-DecisionTrees-src.tar.gz index e1351e4b1..0ff487d36 100644 Binary files a/doc/pub/DecisionTrees/ipynb/ipynb-DecisionTrees-src.tar.gz and b/doc/pub/DecisionTrees/ipynb/ipynb-DecisionTrees-src.tar.gz differ diff --git a/doc/pub/DecisionTrees/pdf/DecisionTrees-minted.pdf b/doc/pub/DecisionTrees/pdf/DecisionTrees-minted.pdf index 0f6cc40c4..6fc29fb0b 100644 Binary files a/doc/pub/DecisionTrees/pdf/DecisionTrees-minted.pdf and b/doc/pub/DecisionTrees/pdf/DecisionTrees-minted.pdf differ diff --git a/doc/src/DecisionTrees/DecisionTrees-bs.html b/doc/src/DecisionTrees/DecisionTrees-bs.html new file mode 100644 index 000000000..263295b72 --- /dev/null +++ b/doc/src/DecisionTrees/DecisionTrees-bs.html @@ -0,0 +1,311 @@ + + + + + + + + +Data Analysis and Machine Learning: From Decision Trees to Forests and all that + + + + + + + + + + + + + + + + + + + + + + + +

    +
    + +
    + +

     

     

     

    + + + + + + +
    +

    Data Analysis and Machine Learning: From Decision Trees to Forests and all that

    + +

    + + +

    +Morten Hjorth-Jensen [1, 2] +
    + +

    + + +

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

    +

    Nov 7, 2019

    +
    +

    + + +

    Read »

    + + +
    + +

    + +

    + + +
    + + + + + + + +
    + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
    + + + + + + diff --git a/doc/src/DecisionTrees/DecisionTrees-minted.pdf b/doc/src/DecisionTrees/DecisionTrees-minted.pdf new file mode 100644 index 000000000..6fc29fb0b Binary files /dev/null and b/doc/src/DecisionTrees/DecisionTrees-minted.pdf differ diff --git a/doc/src/DecisionTrees/DecisionTrees-plain-minted.tex b/doc/src/DecisionTrees/DecisionTrees-plain-minted.tex new file mode 100644 index 000000000..5ab09d845 --- /dev/null +++ b/doc/src/DecisionTrees/DecisionTrees-plain-minted.tex @@ -0,0 +1,2395 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/hplgit/doconce/) +%% +%% + + +%-------------------- begin preamble ---------------------- + +\documentclass[% +oneside, % oneside: electronic viewing, twoside: printing +final, % draft: marks overfull hboxes, figures with paths +10pt]{article} + +\listfiles % print all files needed to compile this document + +\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} +\usepackage[table]{xcolor} +\usepackage{bm,ltablex,microtype} + +\usepackage[pdftex]{graphicx} + +\usepackage{fancyvrb} % packages needed for verbatim environments +\usepackage{minted} +\usemintedstyle{default} + +\usepackage[T1]{fontenc} +%\usepackage[latin1]{inputenc} +\usepackage{ucs} +\usepackage[utf8x]{inputenc} + +\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern + +% Hyperlinks in PDF: +\definecolor{linkcolor}{rgb}{0,0,0.4} +\usepackage{hyperref} +\hypersetup{ + breaklinks=true, + colorlinks=true, + linkcolor=linkcolor, + urlcolor=linkcolor, + citecolor=black, + filecolor=black, + %filecolor=blue, + pdfmenubar=true, + pdftoolbar=true, + bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC + } +%\hyperbaseurl{} % hyperlinks are relative to this root + +\setcounter{tocdepth}{2} % levels in table of contents + +% Tricks for having figures close to where they are defined: +% 1. define less restrictive rules for where to put figures +\setcounter{topnumber}{2} +\setcounter{bottomnumber}{2} +\setcounter{totalnumber}{4} +\renewcommand{\topfraction}{0.95} +\renewcommand{\bottomfraction}{0.95} +\renewcommand{\textfraction}{0} +\renewcommand{\floatpagefraction}{0.75} +% floatpagefraction must always be less than topfraction! +% 2. ensure all figures are flushed before next section +\usepackage[section]{placeins} +% 3. enable begin{figure}[H] (often leads to ugly pagebreaks) +%\usepackage{float}\restylefloat{figure} + +% --- fancyhdr package for fancy headers --- +\usepackage{fancyhdr} +\fancyhf{} % sets both header and footer to nothing +\renewcommand{\headrulewidth}{0pt} +\fancyfoot[LE,RO]{\thepage} +% Ensure copyright on titlepage (article style) and chapter pages (book style) +\fancypagestyle{plain}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} +% \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} +% Ensure copyright on titlepages with \thispagestyle{empty} +\fancypagestyle{empty}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} + \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} + +\pagestyle{fancy} + + +\usepackage[framemethod=TikZ]{mdframed} + +% --- begin definitions of admonition environments --- + +% --- end of definitions of admonition environments --- + +% prevent orhpans and widows +\clubpenalty = 10000 +\widowpenalty = 10000 + +% --- end of standard preamble for documents --- + + +% insert custom LaTeX commands... + +\raggedbottom +\makeindex +\usepackage[totoc]{idxlayout} % for index in the toc +\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc + +%-------------------- end preamble ---------------------- + +\begin{document} + +% matching end for #ifdef PREAMBLE + +\newcommand{\exercisesection}[1]{\subsection*{#1}} + + +% ------------------- main content ---------------------- + + + +% ----------------- title ------------------------- + +\thispagestyle{empty} + +\begin{center} +{\LARGE\bf +\begin{spacing}{1.25} +Data Analysis and Machine Learning: From Decision Trees to Forests and all that +\end{spacing} +} +\end{center} + +% ----------------- author(s) ------------------------- + +\begin{center} +{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] +\end{center} + +\begin{center} +% List of all institutions: +\centerline{{\small ${}^1$Department of Physics, University of Oslo}} +\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} +\end{center} + +% ----------------- end author(s) ------------------------- + +% --- begin date --- +\begin{center} +Nov 7, 2019 +\end{center} +% --- end date --- + +\vspace{1cm} + + +% !split +\subsection*{Decision trees, overarching aims} + + +Decision trees are supervised learning algorithms used for both, +classification and regression tasks. + + +The main idea of decision trees +is to find those descriptive features which contain the most +\textbf{information} regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. + +The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the \textbf{most +informative} feature is done until we accomplish a stopping criteria +where we then finally end up in so called \textbf{leaf nodes}. + +A decision tree is typically divided into a \textbf{root node}, the \textbf{interior nodes}, +and the final \textbf{leaf nodes} or just \textbf{leaves}. These entities are then connected by so-called \textbf{branches}. + +The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +% !split +\subsection*{A typical Decision Tree with its pertinent Jargon, Classification Problem} + + + +\vspace{6mm} + +% inline figure +\centerline{\includegraphics[width=0.8\linewidth]{DataFiles/cancer.png}} + +\vspace{6mm} + + + +This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using \textbf{Scikit-Learn}'s decision tree classifier. Here we have used the so-called \textbf{gini} index (see below) to split the various branches. + + + +% !split +\subsection*{General Features} + +The overarching approach to decision trees is a top-down approach. + +\begin{itemize} +\item A leaf provides the classification of a given instance. + +\item A node specifies a test of some attribute of the instance. + +\item A branch corresponds to a possible values of an attribute. + +\item An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example. +\end{itemize} + +\noindent +This process is then repeated for the subtree rooted at the new +node. + + +% !split +\subsection*{How do we set it up?} + + +In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: + +\begin{enumerate} +\item Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature + +\item Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process + +\item Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the \emph{predictions} we want to make for new query instances + +\item Show query instances to the tree and run down the tree until we arrive at leaf nodes +\end{enumerate} + +\noindent +Then we are essentially done! + + + + + +% !split +\subsection*{Decision trees and Regression} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +import numpy as np +import matplotlib.pyplot as plt +from sklearn.preprocessing import PolynomialFeatures +from sklearn.linear_model import LinearRegression + +steps=250 + +distance=0 +x=0 +distance_list=[] +steps_list=[] +while x 0 and bestAttrId in attributeIds: + toRemove = attributeIds.index(bestAttrId) + attributeIds.pop(toRemove) + child.next = self.id3Recv( + childSampleIds, attributeIds, child.next) + return root + + def printTree(self): + if self.root: + roots = deque() + roots.append(self.root) + while len(roots) > 0: + root = roots.popleft() + print(root.value) + if root.childs: + for child in root.childs: + print('({})'.format(child.value)) + roots.append(child.next) + elif root.next: + print(root.next) + + +def test(): + f = open('DataFiles/rideclass.csv') + attributes = f.readline().split(',') + attributes = attributes[1:len(attributes)-1] + print(attributes) + sample = f.readlines() + f.close() + for i in range(len(sample)): + sample[i] = re.sub('\d+,', '', sample[i]) + sample[i] = sample[i].strip().split(',') + labels = [] + for s in sample: + labels.append(s.pop()) + # print(sample) + # print(labels) + decisionTree = DecisionTree(sample, attributes, labels) + print("System entropy {}".format(decisionTree.entropy)) + decisionTree.id3() + decisionTree.printTree() + + +if __name__ == '__main__': + test() +\end{minted} + +% !split +\subsection*{Cancer Data again now with Decision Trees and other Methods} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +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))) + +\end{minted} + + +% !split +\subsection*{Another example, the moons again} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from __future__ import division, print_function, unicode_literals + +# Common imports +import numpy as np +import os + +# to make this notebook's output stable across runs +np.random.seed(42) + +# To plot pretty figures +import matplotlib +import matplotlib.pyplot as plt +from matplotlib.colors import ListedColormap +plt.rcParams['axes.labelsize'] = 14 +plt.rcParams['xtick.labelsize'] = 12 +plt.rcParams['ytick.labelsize'] = 12 + + +from sklearn.svm import SVC +from sklearn import datasets +from sklearn.tree import DecisionTreeClassifier +from sklearn.datasets import make_moons +from sklearn.tree import export_graphviz + +Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53) + +deep_tree_clf1 = DecisionTreeClassifier(random_state=42) +deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42) +deep_tree_clf1.fit(Xm, ym) +deep_tree_clf2.fit(Xm, ym) + + +def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True): + x1s = np.linspace(axes[0], axes[1], 100) + x2s = np.linspace(axes[2], axes[3], 100) + x1, x2 = np.meshgrid(x1s, x2s) + X_new = np.c_[x1.ravel(), x2.ravel()] + y_pred = clf.predict(X_new).reshape(x1.shape) + custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) + plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) + if not iris: + custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) + plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) + if plot_training: + plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa") + plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor") + plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica") + plt.axis(axes) + if iris: + plt.xlabel("Petal length", fontsize=14) + plt.ylabel("Petal width", fontsize=14) + else: + plt.xlabel(r"$x_1$", fontsize=18) + plt.ylabel(r"$x_2$", fontsize=18, rotation=0) + if legend: + plt.legend(loc="lower right", fontsize=14) +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False) +plt.title("No restrictions", fontsize=16) +plt.subplot(122) +plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False) +plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14) +plt.show() + +\end{minted} + +% !split +\subsection*{Playing around with regions} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +np.random.seed(6) +Xs = np.random.rand(100, 2) - 0.5 +ys = (Xs[:, 0] > 0).astype(np.float32) * 2 + +angle = np.pi/4 +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) +Xsr = Xs.dot(rotation_matrix) + +tree_clf_s = DecisionTreeClassifier(random_state=42) +tree_clf_s.fit(Xs, ys) +tree_clf_sr = DecisionTreeClassifier(random_state=42) +tree_clf_sr.fit(Xsr, ys) + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) +plt.subplot(122) +plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) + +plt.show() +\end{minted} + +% !split +\subsection*{Regression trees} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +# Quadratic training set + noise +np.random.seed(42) +m = 200 +X = np.random.rand(m, 1) +y = 4 * (X - 0.5) ** 2 +y = y + np.random.randn(m, 1) / 10 +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.tree import DecisionTreeRegressor + +tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg.fit(X, y) +\end{minted} + +% !split +\subsection*{Final regressor code} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.tree import DecisionTreeRegressor + +tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2) +tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"): + x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1) + y_pred = tree_reg.predict(x1) + plt.axis(axes) + plt.xlabel("$x_1$", fontsize=18) + if ylabel: + plt.ylabel(ylabel, fontsize=18, rotation=0) + plt.plot(X, y, "b.") + plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$") + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_regression_predictions(tree_reg1, X, y) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +plt.text(0.21, 0.65, "Depth=0", fontsize=15) +plt.text(0.01, 0.2, "Depth=1", fontsize=13) +plt.text(0.65, 0.8, "Depth=1", fontsize=13) +plt.legend(loc="upper center", fontsize=18) +plt.title("max_depth=2", fontsize=14) + +plt.subplot(122) +plot_regression_predictions(tree_reg2, X, y, ylabel=None) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +for split in (0.0458, 0.1298, 0.2873, 0.9040): + plt.plot([split, split], [-0.2, 1], "k:", linewidth=1) +plt.text(0.3, 0.5, "Depth=2", fontsize=13) +plt.title("max_depth=3", fontsize=14) + +plt.show() +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +tree_reg1 = DecisionTreeRegressor(random_state=42) +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +x1 = np.linspace(0, 1, 500).reshape(-1, 1) +y_pred1 = tree_reg1.predict(x1) +y_pred2 = tree_reg2.predict(x1) + +plt.figure(figsize=(11, 4)) + +plt.subplot(121) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.ylabel("$y$", fontsize=18, rotation=0) +plt.legend(loc="upper center", fontsize=18) +plt.title("No restrictions", fontsize=14) + +plt.subplot(122) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14) + +plt.show() +\end{minted} + + + +% !split +\subsection*{Pros and cons of trees, pros} + +\begin{itemize} +\item White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines) + +\item Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression! + +\item No feature normalization needed + +\item Tree models can handle both continuous and categorical data (Classification and Regression Trees) + +\item Can model nonlinear relationships + +\item Can model interactions between the different descriptive features + +\item Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small) +\end{itemize} + +\noindent +% !split +\subsection*{Disadvantages} + +\begin{itemize} +\item Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches + +\item If continuous features are used the tree may become quite large and hence less interpretable + +\item Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented + +\item Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests + +\item Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. + +\item If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data + +\item Features with many levels may be preferred over features with less levels since for them it is \emph{more easy} to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain +\end{itemize} + +\noindent +However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved. + + +% !split +\subsection*{Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods} + +As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct forests and jungles of trees, homogeneous ones or heterogenous ones. These methods are recognized by different names which we will try to explain here. These are +\begin{enumerate} +\item Voting classifiers + +\item Bagging and Pasting + +\item Random forests + +\item Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost) +\end{enumerate} + +\noindent +We discuss these methods here. + + +% !split +\subsection*{An Overview of Ensemble Methods} + + + +\vspace{6mm} + +% inline figure +\centerline{\includegraphics[width=0.8\linewidth]{DataFiles/ensembleoverview.png}} + +\vspace{6mm} + + + + + +% !split +\subsection*{Bagging} + +The \textbf{plain} decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of $n$ to $p$ is moderately large. + +\textbf{Bootstrap aggregation}, or just \textbf{bagging}, is a +general-purpose procedure for reducing the variance of a statistical +learning method. + + +% !split +\subsection*{More bagging} + +Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all $B$ possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all $B$ trees. + +% !split +\subsection*{Simple Voting Example, head or tail} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +heads_proba = 0.51 +coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32) +cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1) +plt.figure(figsize=(8,3.5)) +plt.plot(cumulative_heads_ratio) +plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%") +plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%") +plt.xlabel("Number of coin tosses") +plt.ylabel("Heads ratio") +plt.legend(loc="lower right") +plt.axis([0, 10000, 0.42, 0.58]) +plt.show() + +\end{minted} + +% !split +\subsection*{Using the Voting Classifier} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) + +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(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)) + +\end{minted} + +% !split +\subsection*{Please, not the moons again! Voting and Bagging} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='hard') +voting_clf.fit(X_train, y_train) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(probability=True, random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='soft') +voting_clf.fit(X_train, y_train) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +\end{minted} + +% !split +\subsection*{Now Bagging} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.ensemble import BaggingClassifier +from sklearn.tree import DecisionTreeClassifier + +bag_clf = BaggingClassifier( + DecisionTreeClassifier(random_state=42), n_estimators=500, + max_samples=100, bootstrap=True, n_jobs=-1, random_state=42) +bag_clf.fit(X_train, y_train) +y_pred = bag_clf.predict(X_test) +\end{minted} + + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.metrics import accuracy_score +print(accuracy_score(y_test, y_pred)) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +tree_clf = DecisionTreeClassifier(random_state=42) +tree_clf.fit(X_train, y_train) +y_pred_tree = tree_clf.predict(X_test) +print(accuracy_score(y_test, y_pred_tree)) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from matplotlib.colors import ListedColormap + +def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True): + x1s = np.linspace(axes[0], axes[1], 100) + x2s = np.linspace(axes[2], axes[3], 100) + x1, x2 = np.meshgrid(x1s, x2s) + X_new = np.c_[x1.ravel(), x2.ravel()] + y_pred = clf.predict(X_new).reshape(x1.shape) + custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) + plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) + if contour: + custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) + plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) + plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha) + plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha) + plt.axis(axes) + plt.xlabel(r"$x_1$", fontsize=18) + plt.ylabel(r"$x_2$", fontsize=18, rotation=0) +plt.figure(figsize=(11,4)) +plt.subplot(121) +plot_decision_boundary(tree_clf, X, y) +plt.title("Decision Tree", fontsize=14) +plt.subplot(122) +plot_decision_boundary(bag_clf, X, y) +plt.title("Decision Trees with Bagging", fontsize=14) +plt.show() +\end{minted} + + +% !split +\subsection*{Making our own Bagging with Bootstrap} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.tree import DecisionTreeRegressor + + +np.random.seed(2018) + +n = 40 +n_boostraps = 100 +maxdegree = 14 + +# 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) + +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) + +for degree in range(maxdegree): + model = DecisionTreeRegressor(max_depth=5) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_) + y_pred[:, i] = model.predict(X_test_scaled).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + +\end{minted} + + +% !split +\subsection*{Changing the Level of the Decision Tree} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.tree import DecisionTreeRegressor + +n = 100 +n_boostraps = 100 +maxdepth = 8 + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +error = np.zeros(maxdepth) +bias = np.zeros(maxdepth) +variance = np.zeros(maxdepth) +polydegree = np.zeros(maxdepth) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +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) + +for degree in range(1,maxdepth): + model = DecisionTreeRegressor(max_depth=degree) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_) + y_pred[:, i] = model.predict(X_test_scaled)#.ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.xlim(1,maxdepth) +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + + +\end{minted} + + + + +% !split +\subsection*{Random forests} + +Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. + +As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of $m$ predictors is chosen as split +candidates from the full set of $p$ predictors. The split is allowed to +use only one of those $m$ predictors. + +A fresh sample of $m$ predictors is +taken at each split, and typically we choose + +\[ +m\approx \sqrt{p}. +\] + +In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. + +The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quanti- ties. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. + + +% !split +\subsection*{Random Forest Algorithm} +The algorithm described here can be applied to both classification and regression problems. + +We will grow of forest of say $M$ trees. +\begin{enumerate} +\item For $m=1:M$ we +\begin{itemize} + + \item Draw a bootstrap sample of from the training data organized in our $\bm{X}$ matrix. + + \item We grow then a random forest tree $T_m$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached +\begin{enumerate} + + \item we select $m \le p$ varibales at random from the $p$ predictors/features + + \item pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node + + \item split the node into daughter nodes + +\end{enumerate} + +\noindent +\end{itemize} + +\noindent +\item Output then the ensemble of trees $\{T_m\}_1^{M}$ and make predictions for either a regression type of problem or a classification type of problem. +\end{enumerate} + +\noindent +% !split +\subsection*{Bootstrap with Random Forests Instead of a Single Tree, own Bagging} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.ensemble import RandomForestRegressor + +np.random.seed(2018) + +n = 100 +n_boostraps = 100 +maxdegree = 14 + +# 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) + +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) + +for degree in range(maxdegree): + model = RandomForestRegressor() + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_.ravel()) + y_pred[:, i] = model.predict(X_test_scaled).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + +\end{minted} + + + + +% !split +\subsection*{Random Forests Compared with other Methods on the Cancer Data} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +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) +plt.show() + +\end{minted} + + +% !split +\subsection*{Compare Bagging on Trees with Random Forests} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +bag_clf = BaggingClassifier( + DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42), + n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42) +\end{minted} + + + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +bag_clf.fit(X_train, y_train) +y_pred = bag_clf.predict(X_test) +from sklearn.ensemble import RandomForestClassifier +rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42) +rnd_clf.fit(X_train, y_train) +y_pred_rf = rnd_clf.predict(X_test) +np.sum(y_pred == y_pred_rf) / len(y_pred) +\end{minted} + + + + + +% !split +\subsection*{Boosting, a Bird'e Eye} + +The basic idea is to combine weak classifiers in order to create a good +classifier. With a weak classifier we often intend a classifier which +produces results which are only slightly better than we would get by +random guesses. + +This is done by applying in an iterative way a weak (or a standard +classifier like decision trees) to modify the data. In each iteration +we emphasize those observations which are misclassified by weighting +them with a factor. + + +% !split +\subsection*{Adaptive boosting: AdaBoost, Basic Algorithm} + +The algorithm here is rather straightforward. Assume that our weak +classifier is a decision tree and we consider a binary set of outputs +with $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of +observations. Our design matrix is given in terms of the +feature/predictor vectors +$\bm{X}=[\bm{x}_0\bm{x}_1\dots\bm{x}_{p-1}$. Finally, we define also a +classifier determined by our data via a function $G(\bm{X})$. This function tells us how well we are able to classify our outputs/targets $\bm{y}$. + +We can then define the misclassification error $\mathrm{err}$ as +\[ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(\bm{X}_{i*}), +\] +where the function $I()$ is one if we misclassify and zero if we classify correctly. + +% !split +\subsection*{Basic Steps of AdaBoost} + +With the above definitions we are now ready to set up the algorithm for AdaBoost. +The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. +\begin{enumerate} +\item We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\dots n-1$. It is to see then that $\sum_{i=0}^{n-1}w_i = 1$. + +\item We rewrite the misclassification error as +\end{enumerate} + +\noindent +\[ +\mathrm{err}=\frac{\sum_{i=0}^{n-1}w_iI(y_i\ne G(\bm{X}_{i*})}{\sum_{i=0}^{n-1}w_i}, +\] +\begin{enumerate} +\item 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. +\begin{enumerate} + + \item Fit then a given classifier to the training using the weights $w_i$. + + \item Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly. + + \item Define a quantity $\alpha_{m} = \log{(1-\mathrm{err})/\mathrm{err}} + + \item Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(\bm{X}_{i*})}. + +\end{enumerate} + +\noindent +\item Compute the new classifier $G(\bm{X})= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(\bm{X}_{i*}). +\end{enumerate} + +\noindent +For the iterations with $m \le 2$ the weights are modified +individually at each steps. The obersvations 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. + + + +% !split +\subsection*{AdaBoost Examples} + +Using \textbf{Scikit-Learn} it is easy to appply the adaptive boosting algorithm, as done here. + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.ensemble import AdaBoostClassifier + +ada_clf = AdaBoostClassifier( + DecisionTreeClassifier(max_depth=1), n_estimators=200, + algorithm="SAMME.R", learning_rate=0.5, random_state=42) +ada_clf.fit(X_train, y_train) + +plot_decision_boundary(ada_clf, X, y) + +m = len(X_train) + +plt.figure(figsize=(11, 4)) +for subplot, learning_rate in ((121, 1), (122, 0.5)): + sample_weights = np.ones(m) + plt.subplot(subplot) + for i in range(5): + svm_clf = SVC(kernel="rbf", C=0.05, gamma="auto", random_state=42) + svm_clf.fit(X_train, y_train, sample_weight=sample_weights) + y_pred = svm_clf.predict(X_train) + sample_weights[y_pred != y_train] *= (1 + learning_rate) + plot_decision_boundary(svm_clf, X, y, alpha=0.2) + plt.title("learning_rate = {}".format(learning_rate), fontsize=16) + if subplot == 121: + plt.text(-0.7, -0.65, "1", fontsize=14) + plt.text(-0.6, -0.10, "2", fontsize=14) + plt.text(-0.5, 0.10, "3", fontsize=14) + plt.text(-0.4, 0.55, "4", fontsize=14) + plt.text(-0.3, 0.90, "5", fontsize=14) + +save_fig("boosting_plot") +plt.show() +\end{minted} + + +% !split +\subsection*{Gradient boosting: Basics} + +Gradient boosting is again a similar technique to Adapative boosting, +it combines so-called weak classifiers or regressors into a strong +method via a series of iterations. + +In order to understand the method, let us illustrate its basics by +bringing back the essential steps in linear regression, where our cost +function was the least squares function. + +% !split +\subsection*{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 least squares function +\[ +C(\bm{y},\bm{f})=\frac{1}{n}\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +\] + +The way we proceed in an iterative fashion is to +\begin{enumerate} +\item Initialize our estimate by $f_0(x)=0$. + +\item For $m=1:M$, we +\begin{enumerate} + + \item compute the negative gradient vector $\bm{u}_m = -\partial C(\bm{y},\bm{f})/\partial \bm{f}(x)$ at $f(x) = f_{m-1}(x); + + \item fit the so-called base-learner to the negative gradient $h_m(u_m,x)$; + + \item update the estimate $f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x)$; + +\end{enumerate} + +\noindent +\item The final estimate is then $f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x)$. +\end{enumerate} + +\noindent +% !split +\subsection*{Gradient Boosting, Examples} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +np.random.seed(42) +X = np.random.rand(100, 1) - 0.5 +y = 3*X[:, 0]**2 + 0.05 * np.random.randn(100) + +from sklearn.tree import DecisionTreeRegressor + +tree_reg1 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg1.fit(X, y) + +y2 = y - tree_reg1.predict(X) +tree_reg2 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg2.fit(X, y2) + +y3 = y2 - tree_reg2.predict(X) +tree_reg3 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg3.fit(X, y3) + +X_new = np.array([[0.8]]) +y_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3)) + +def plot_predictions(regressors, X, y, axes, label=None, style="r-", data_style="b.", data_label=None): + x1 = np.linspace(axes[0], axes[1], 500) + y_pred = sum(regressor.predict(x1.reshape(-1, 1)) for regressor in regressors) + plt.plot(X[:, 0], y, data_style, label=data_label) + plt.plot(x1, y_pred, style, linewidth=2, label=label) + if label or data_label: + plt.legend(loc="upper center", fontsize=16) + plt.axis(axes) + +plt.figure(figsize=(11,11)) + +plt.subplot(321) +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h_1(x_1)$", style="g-", data_label="Training set") +plt.ylabel("$y$", fontsize=16, rotation=0) +plt.title("Residuals and tree predictions", fontsize=16) + +plt.subplot(322) +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1)$", data_label="Training set") +plt.ylabel("$y$", fontsize=16, rotation=0) +plt.title("Ensemble predictions", fontsize=16) + +plt.subplot(323) +plot_predictions([tree_reg2], X, y2, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_2(x_1)$", style="g-", data_style="k+", data_label="Residuals") +plt.ylabel("$y - h_1(x_1)$", fontsize=16) + +plt.subplot(324) +plot_predictions([tree_reg1, tree_reg2], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1)$") +plt.ylabel("$y$", fontsize=16, rotation=0) + +plt.subplot(325) +plot_predictions([tree_reg3], X, y3, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_3(x_1)$", style="g-", data_style="k+") +plt.ylabel("$y - h_1(x_1) - h_2(x_1)$", fontsize=16) +plt.xlabel("$x_1$", fontsize=16) + +plt.subplot(326) +plot_predictions([tree_reg1, tree_reg2, tree_reg3], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1) + h_3(x_1)$") +plt.xlabel("$x_1$", fontsize=16) +plt.ylabel("$y$", fontsize=16, rotation=0) + +save_fig("gradient_boosting_plot") +plt.show() + +from sklearn.ensemble import GradientBoostingRegressor + +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0, random_state=42) +gbrt.fit(X, y) + +gbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42) +gbrt_slow.fit(X, y) + +plt.figure(figsize=(11,4)) + +plt.subplot(121) +plot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="Ensemble predictions") +plt.title("learning_rate={}, n_estimators={}".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14) + +plt.subplot(122) +plot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8]) +plt.title("learning_rate={}, n_estimators={}".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14) + +save_fig("gbrt_learning_rate_plot") +plt.show() + +\end{minted} + + +% !split +\subsection*{Gradient Boots with Early Stopping} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} + +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error + +X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=49) + +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120, random_state=42) +gbrt.fit(X_train, y_train) + +errors = [mean_squared_error(y_val, y_pred) + for y_pred in gbrt.staged_predict(X_val)] +bst_n_estimators = np.argmin(errors) + 1 + +gbrt_best = GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators, random_state=42) +gbrt_best.fit(X_train, y_train) + +min_error = np.min(errors) +plt.figure(figsize=(11, 4)) + +plt.subplot(121) +plt.plot(errors, "b.-") +plt.plot([bst_n_estimators, bst_n_estimators], [0, min_error], "k--") +plt.plot([0, 120], [min_error, min_error], "k--") +plt.plot(bst_n_estimators, min_error, "ko") +plt.text(bst_n_estimators, min_error*1.2, "Minimum", ha="center", fontsize=14) +plt.axis([0, 120, 0, 0.01]) +plt.xlabel("Number of trees") +plt.title("Validation error", fontsize=14) + +plt.subplot(122) +plot_predictions([gbrt_best], X, y, axes=[-0.5, 0.5, -0.1, 0.8]) +plt.title("Best model (%d trees)" % bst_n_estimators, fontsize=14) + +save_fig("early_stopping_gbrt_plot") +plt.show() + + +gbrt = GradientBoostingRegressor(max_depth=2, warm_start=True, random_state=42) + +min_val_error = float("inf") +error_going_up = 0 +for n_estimators in range(1, 120): + gbrt.n_estimators = n_estimators + gbrt.fit(X_train, y_train) + y_pred = gbrt.predict(X_val) + val_error = mean_squared_error(y_val, y_pred) + if val_error < min_val_error: + min_val_error = val_error + error_going_up = 0 + else: + error_going_up += 1 + if error_going_up == 5: + break # early stopping + + +print(gbrt.n_estimators) +print("Minimum validation MSE:", min_val_error) +\end{minted} + +% !split +\subsection*{XGBoost: Extreme Gradient Boosting} + + +\href{{https://github.com/dmlc/xgboost}}{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 \href{{https://arxiv.org/abs/1603.02754}}{article by Chen and Guestrin}. + +The authors design and build a highly scalable end-to-end tree +boosting system. It has a theoretically justified weighted quantile +sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. + +It is now the algorithm which wins essentially all ML competitions!!! + +% !split +\subsection*{Regression Case} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +import xgboost as xgb +from sklearn.preprocessing import StandardScaler +import scikitplot as skplt +from sklearn.metrics import mean_squared_error + +n = 100 +maxdegree = 6 + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) + +error = np.zeros(maxdegree) +bias = np.zeros(maxdegree) +variance = np.zeros(maxdegree) +polydegree = np.zeros(maxdegree) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +for degree in range(maxdegree): + model = xgb.XGBRegressor(objective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1, + max_depth = degree, alpha = 10, n_estimators = 10) + model.fit(X_train_scaled,y_train) + y_pred = model.predict(X_test_scaled) + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) + variance[degree] = np.mean( np.var(y_pred) ) + print('Max depth:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.xlim(1,maxdegree-1) +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + +\end{minted} + + + +% !split +\subsection*{Xgboost on the Cancer Data} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.datasets import load_breast_cancer +from sklearn.preprocessing import LabelEncoder +from sklearn.model_selection import cross_validate +import scikitplot as skplt +import xgboost as xgb +# Load the data +cancer = load_breast_cancer() + +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) +print(X_train.shape) +print(X_test.shape) +#now scale the data +from sklearn.preprocessing import StandardScaler +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +xg_clf = xgb.XGBClassifier() +xg_clf.fit(X_train_scaled,y_train) +xgb.plot_tree(xg_clf,num_trees=0) +plt.rcParams['figure.figsize'] = [50, 10] +plt.show() +xgb.plot_importance(xg_clf) +plt.rcParams['figure.figsize'] = [5, 5] +plt.show() +\end{minted} + +% ------------------- end of main content --------------- + +\end{document} + diff --git a/doc/src/DecisionTrees/DecisionTrees-reveal.html b/doc/src/DecisionTrees/DecisionTrees-reveal.html new file mode 100644 index 000000000..0d1365a1e --- /dev/null +++ b/doc/src/DecisionTrees/DecisionTrees-reveal.html @@ -0,0 +1,2657 @@ + + + + + + + +Data Analysis and Machine Learning: From Decision Trees to Forests and all that + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    + + + + + + + + + + + + + + +
    + + + + +

    Data Analysis and Machine Learning: From Decision Trees to Forests and all that

    + +

    + + +

    +Morten Hjorth-Jensen [1, 2] +
    + +

     
    + + +

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

     
    +

    Nov 7, 2019

    +
    +

    + +

    + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
    +
    + + +
    +

    Decision trees, overarching aims

    + +

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

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

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

    +A decision tree is typically divided into a root node, the interior nodes, +and the final leaf nodes or just leaves. These entities are then connected by so-called branches. + +

    +The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. +

    + + +
    +

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    + +

    +



    + +

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

    + + +
    +

    General Features

    + +

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

      +

    • A leaf provides the classification of a given instance.
    • +

    • A node specifies a test of some attribute of the instance.
    • +

    • A branch corresponds to a possible values of an attribute.
    • +

    • An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
    • +
    +

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

    + + +
    +

    How do we set it up?

    + +

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

      +

    1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
    2. +

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

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

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

    + +Then we are essentially done! +

    + + +
    +

    Decision trees and Regression

    +

    + + +

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

    Building a tree, regression

    + +

    +There are mainly two steps + +

      +

    1. We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
    2. + +

    3. For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
    4. +
    +

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

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

     
    + +

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

    + + +
    +

    A top-down approach, recursive binary splitting

    + +

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

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

    + + +
    +

    Making a tree

    + +

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

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

     
    + +and +

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

     
    + +so that we obtain the lowest MSE, that is +

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

     
    + +

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

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

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

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

    + + +
    +

    Pruning the tree

    + +

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

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

    + + +
    +

    Cost complexity pruning

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

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

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

    +The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +com- plexity and its fit to the training data. When \( \alpha = 0 \), then the +subtree \( T \) will simply equal \( T_0 \), +because then the above equation just measures the +training error. +However, as \( \alpha \) increases, there is a price to pay for +having a tree with many terminal nodes. The above equation will +tend to be minimized for a smaller subtree. + +

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

    + + +
    +

    Schematic Regression Procedure

    + +

    +

    +Building a Regression Tree. +
      +

    1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
    2. +

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

    5. Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
    6. + +
        + +

      • repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
      • + +

      • Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
      • + +

      • Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
      • +
      +

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

    A Classification Tree

    + +

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

    + + +
    +

    Growing a classification tree

    + +

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

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

    + + +
    +

    Classification tree, how to split nodes

    + +

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

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

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

     
    + +

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

      +

    • Misclassification error
    • +
    +

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

     
    + + +

      +

    • Gini index \( g \)
    • +
    +

     
    +$$ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +$$ +

     
    + + +

      +

    • Information entropy or just entropy \( s \)
    • +
    +

     
    +$$ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +$$ +

     
    +

    + + +
    +

    Visualizing the Tree, Classification

    +

    + + +

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

    Visualizing the Tree, The Moons

    +

    + + +

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

    Algorithms for Setting up Decision Trees

    + +

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

      +

    1. The CART (Classification And Regression Tree) algorithm for both classification and regression
    2. +

    3. The ID3 algorithm based on the computation of the information gain for classification
    4. +
    +

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

    + + +
    +

    The CART algorithm for Classification

    +
    + + +
    +

    The CART algorithm for Regression

    +
    + + +
    +

    Computing the Gini index

    + +

    +The example we will look at is a classical one in many Machine +Learning applications. Based on various meteorological features, we +have several so-called attributes which decide whether we at the end +will do some outdoor activity like skiing, going for a bike ride etc +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +attributes for each feature are then sunny, overcast and rain for the +outlook, hot, cold and mild for temperature, high and normal for +humidity and weak and strong for wind. + +

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

    + + +
    +

    Simple Python Code to read in Data and perform Classification

    + +

    + + +

    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.model_selection import train_test_split
    +from sklearn.tree import export_graphviz
    +from sklearn.preprocessing import StandardScaler, OneHotEncoder
    +from sklearn.compose import ColumnTransformer
    +from IPython.display import Image 
    +from pydot import graph_from_dot_data
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +infile = open(data_path("rideclass.csv"),'r')
    +
    +# Read the experimental data with Pandas
    +from IPython.display import display
    +ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
    +ridedata = pd.DataFrame(ridedata)
    +
    +# Features and targets
    +X = ridedata.loc[:, ridedata.columns != 'Ride'].values
    +y = ridedata.loc[:, ridedata.columns == 'Ride'].values
    +
    +# Create the encoder.
    +encoder = OneHotEncoder(handle_unknown="ignore")
    +# Assume for simplicity all features are categorical.
    +encoder.fit(X)    
    +# Apply the encoder.
    +X = encoder.transform(X)
    +print(X)
    +# Then do a Classification tree
    +tree_clf = DecisionTreeClassifier(max_depth=2)
    +tree_clf.fit(X, y)
    +print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
    +#transfer to a decision tree graph
    +export_graphviz(
    +    tree_clf,
    +    out_file="DataFiles/ride.dot",
    +    rounded=True,
    +    filled=True
    +)
    +cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
    +os.system(cmd)
    +
    +
    + + +
    +

    Computing the Gini Factor

    + +

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

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

    + + +

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

    Entropy and the ID3 algorithm

    + +

    +ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? + +

      +

    1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
    2. +

    3. The best attribute is selected and used as the test at the root node of the tree.
    4. +

    5. A descendant of the root node is then created for each possible value of this attribute.
    6. +

    7. Training examples are sorted to the appropriate descendant node.
    8. +

    9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
    10. +

    11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
    12. +
    +

    + +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

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

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

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

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

    + + +
    +

    Implementing the ID3 Algorithm

    + +

    + + +

    import re
    +import math
    +from collections import deque
    +
    +# x is examples in training set
    +# y is set of targets
    +# label is target attributes
    +# Node is a class which has properties values, childs, and next
    +# root is top node in the decision tree
    +
    +class Node(object):
    +	def __init__(self):
    +		self.value = None
    +		self.next = None
    +		self.childs = None
    +
    +# Simple class of Decision Tree
    +# Aimed for who want to learn Decision Tree, so it is not optimized
    +class DecisionTree(object):
    +	def __init__(self, sample, attributes, labels):
    +		self.sample = sample
    +		self.attributes = attributes
    +		self.labels = labels
    +		self.labelCodes = None
    +		self.labelCodesCount = None
    +		self.initLabelCodes()
    +		# print(self.labelCodes)
    +		self.root = None
    +		self.entropy = self.getEntropy([x for x in range(len(self.labels))])
    +
    +	def initLabelCodes(self):
    +		self.labelCodes = []
    +		self.labelCodesCount = []
    +		for l in self.labels:
    +			if l not in self.labelCodes:
    +				self.labelCodes.append(l)
    +				self.labelCodesCount.append(0)
    +			self.labelCodesCount[self.labelCodes.index(l)] += 1
    +
    +	def getLabelCodeId(self, sampleId):
    +		return self.labelCodes.index(self.labels[sampleId])
    +
    +	def getAttributeValues(self, sampleIds, attributeId):
    +		vals = []
    +		for sid in sampleIds:
    +			val = self.sample[sid][attributeId]
    +			if val not in vals:
    +				vals.append(val)
    +		# print(vals)
    +		return vals
    +
    +	def getEntropy(self, sampleIds):
    +		entropy = 0
    +		labelCount = [0] * len(self.labelCodes)
    +		for sid in sampleIds:
    +			labelCount[self.getLabelCodeId(sid)] += 1
    +		# print("-ge", labelCount)
    +		for lv in labelCount:
    +			# print(lv)
    +			if lv != 0:
    +				entropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)
    +			else:
    +				entropy += 0
    +		return entropy
    +
    +	def getDominantLabel(self, sampleIds):
    +		labelCodesCount = [0] * len(self.labelCodes)
    +		for sid in sampleIds:
    +			labelCodesCount[self.labelCodes.index(self.labels[sid])] += 1
    +		return self.labelCodes[labelCodesCount.index(max(labelCodesCount))]
    +
    +	def getInformationGain(self, sampleIds, attributeId):
    +		gain = self.getEntropy(sampleIds)
    +		attributeVals = []
    +		attributeValsCount = []
    +		attributeValsIds = []
    +		for sid in sampleIds:
    +			val = self.sample[sid][attributeId]
    +			if val not in attributeVals:
    +				attributeVals.append(val)
    +				attributeValsCount.append(0)
    +				attributeValsIds.append([])
    +			vid = attributeVals.index(val)
    +			attributeValsCount[vid] += 1
    +			attributeValsIds[vid].append(sid)
    +		# print("-gig", self.attributes[attributeId])
    +		for vc, vids in zip(attributeValsCount, attributeValsIds):
    +			# print("-gig", vids)
    +			gain -= vc/len(sampleIds) * self.getEntropy(vids)
    +		return gain
    +
    +	def getAttributeMaxInformationGain(self, sampleIds, attributeIds):
    +		attributesEntropy = [0] * len(attributeIds)
    +		for i, attId in zip(range(len(attributeIds)), attributeIds):
    +			attributesEntropy[i] = self.getInformationGain(sampleIds, attId)
    +		maxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]
    +		return self.attributes[maxId], maxId
    +
    +	def isSingleLabeled(self, sampleIds):
    +		label = self.labels[sampleIds[0]]
    +		for sid in sampleIds:
    +			if self.labels[sid] != label:
    +				return False
    +		return True
    +
    +	def getLabel(self, sampleId):
    +		return self.labels[sampleId]
    +
    +	def id3(self):
    +		sampleIds = [x for x in range(len(self.sample))]
    +		attributeIds = [x for x in range(len(self.attributes))]
    +		self.root = self.id3Recv(sampleIds, attributeIds, self.root)
    +
    +	def id3Recv(self, sampleIds, attributeIds, root):
    +		root = Node() # Initialize current root
    +		if self.isSingleLabeled(sampleIds):
    +			root.value = self.labels[sampleIds[0]]
    +			return root
    +		# print(attributeIds)
    +		if len(attributeIds) == 0:
    +			root.value = self.getDominantLabel(sampleIds)
    +			return root
    +		bestAttrName, bestAttrId = self.getAttributeMaxInformationGain(
    +			sampleIds, attributeIds)
    +		# print(bestAttrName)
    +		root.value = bestAttrName
    +		root.childs = []  # Create list of children
    +		for value in self.getAttributeValues(sampleIds, bestAttrId):
    +			# print(value)
    +			child = Node()
    +			child.value = value
    +			root.childs.append(child)  # Append new child node to current
    +									   # root
    +			childSampleIds = []
    +			for sid in sampleIds:
    +				if self.sample[sid][bestAttrId] == value:
    +					childSampleIds.append(sid)
    +			if len(childSampleIds) == 0:
    +				child.next = self.getDominantLabel(sampleIds)
    +			else:
    +				# print(bestAttrName, bestAttrId)
    +				# print(attributeIds)
    +				if len(attributeIds) > 0 and bestAttrId in attributeIds:
    +					toRemove = attributeIds.index(bestAttrId)
    +					attributeIds.pop(toRemove)
    +				child.next = self.id3Recv(
    +					childSampleIds, attributeIds, child.next)
    +		return root
    +
    +	def printTree(self):
    +		if self.root:
    +			roots = deque()
    +			roots.append(self.root)
    +			while len(roots) > 0:
    +				root = roots.popleft()
    +				print(root.value)
    +				if root.childs:
    +					for child in root.childs:
    +						print('({})'.format(child.value))
    +						roots.append(child.next)
    +				elif root.next:
    +					print(root.next)
    +
    +
    +def test():
    +	f = open('DataFiles/rideclass.csv')
    +	attributes = f.readline().split(',')
    +	attributes = attributes[1:len(attributes)-1]
    +	print(attributes)
    +	sample = f.readlines()
    +	f.close()
    +	for i in range(len(sample)):
    +		sample[i] = re.sub('\d+,', '', sample[i])
    +		sample[i] = sample[i].strip().split(',')
    +	labels = []
    +	for s in sample:
    +		labels.append(s.pop())
    +	# print(sample)
    +	# print(labels)
    +	decisionTree = DecisionTree(sample, attributes, labels)
    +	print("System entropy {}".format(decisionTree.entropy))
    +	decisionTree.id3()
    +	decisionTree.printTree()
    +
    +
    +if __name__ == '__main__':
    +	test()
    +
    +
    + + +
    +

    Cancer Data again now with Decision Trees and other Methods

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.svm import SVC
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.tree import DecisionTreeClassifier
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +# Support vector machine
    +svm = SVC(gamma='auto', C=100)
    +svm.fit(X_train, y_train)
    +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
    +# Decision Trees
    +deep_tree_clf = DecisionTreeClassifier(max_depth=None)
    +deep_tree_clf.fit(X_train, y_train)
    +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +# Logistic Regression
    +logreg.fit(X_train_scaled, y_train)
    +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Support Vector Machine
    +svm.fit(X_train_scaled, y_train)
    +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Decision Trees
    +deep_tree_clf.fit(X_train_scaled, y_train)
    +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
    +
    +
    + + +
    +

    Another example, the moons again

    +

    + + +

    from __future__ import division, print_function, unicode_literals
    +
    +# Common imports
    +import numpy as np
    +import os
    +
    +# to make this notebook's output stable across runs
    +np.random.seed(42)
    +
    +# To plot pretty figures
    +import matplotlib
    +import matplotlib.pyplot as plt
    +from matplotlib.colors import ListedColormap
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
    +
    +
    +from sklearn.svm import SVC
    +from sklearn import datasets
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.datasets import make_moons
    +from sklearn.tree import export_graphviz
    +
    +Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
    +
    +deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
    +deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
    +deep_tree_clf1.fit(Xm, ym)
    +deep_tree_clf2.fit(Xm, ym)
    +
    +
    +def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
    +    x1s = np.linspace(axes[0], axes[1], 100)
    +    x2s = np.linspace(axes[2], axes[3], 100)
    +    x1, x2 = np.meshgrid(x1s, x2s)
    +    X_new = np.c_[x1.ravel(), x2.ravel()]
    +    y_pred = clf.predict(X_new).reshape(x1.shape)
    +    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    +    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    +    if not iris:
    +        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    +        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    +    if plot_training:
    +        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
    +        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
    +        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
    +        plt.axis(axes)
    +    if iris:
    +        plt.xlabel("Petal length", fontsize=14)
    +        plt.ylabel("Petal width", fontsize=14)
    +    else:
    +        plt.xlabel(r"$x_1$", fontsize=18)
    +        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    +    if legend:
    +        plt.legend(loc="lower right", fontsize=14)
    +plt.figure(figsize=(11, 4))
    +plt.subplot(121)
    +plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    +plt.title("No restrictions", fontsize=16)
    +plt.subplot(122)
    +plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    +plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
    +plt.show()
    +
    +
    + + +
    +

    Playing around with regions

    +

    + + +

    np.random.seed(6)
    +Xs = np.random.rand(100, 2) - 0.5
    +ys = (Xs[:, 0] > 0).astype(np.float32) * 2
    +
    +angle = np.pi/4
    +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
    +Xsr = Xs.dot(rotation_matrix)
    +
    +tree_clf_s = DecisionTreeClassifier(random_state=42)
    +tree_clf_s.fit(Xs, ys)
    +tree_clf_sr = DecisionTreeClassifier(random_state=42)
    +tree_clf_sr.fit(Xsr, ys)
    +
    +plt.figure(figsize=(11, 4))
    +plt.subplot(121)
    +plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    +plt.subplot(122)
    +plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    +
    +plt.show()
    +
    +
    + + +
    +

    Regression trees

    +

    + + +

    # Quadratic training set + noise
    +np.random.seed(42)
    +m = 200
    +X = np.random.rand(m, 1)
    +y = 4 * (X - 0.5) ** 2
    +y = y + np.random.randn(m, 1) / 10
    +
    +

    + + +

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

    Final regressor code

    +

    + + +

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

    + + +

    tree_reg1 = DecisionTreeRegressor(random_state=42)
    +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
    +tree_reg1.fit(X, y)
    +tree_reg2.fit(X, y)
    +
    +x1 = np.linspace(0, 1, 500).reshape(-1, 1)
    +y_pred1 = tree_reg1.predict(x1)
    +y_pred2 = tree_reg2.predict(x1)
    +
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plt.plot(X, y, "b.")
    +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
    +plt.axis([0, 1, -0.2, 1.1])
    +plt.xlabel("$x_1$", fontsize=18)
    +plt.ylabel("$y$", fontsize=18, rotation=0)
    +plt.legend(loc="upper center", fontsize=18)
    +plt.title("No restrictions", fontsize=14)
    +
    +plt.subplot(122)
    +plt.plot(X, y, "b.")
    +plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
    +plt.axis([0, 1, -0.2, 1.1])
    +plt.xlabel("$x_1$", fontsize=18)
    +plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
    +
    +plt.show()
    +
    +
    + + +
    +

    Pros and cons of trees, pros

    + +
      +

    • White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
    • +

    • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
    • +

    • No feature normalization needed
    • +

    • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
    • +

    • Can model nonlinear relationships
    • +

    • Can model interactions between the different descriptive features
    • +

    • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
    • +
    +
    + + +
    +

    Disadvantages

    + +
      +

    • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
    • +

    • If continuous features are used the tree may become quite large and hence less interpretable
    • +

    • Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
    • +

    • Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
    • +

    • Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
    • +

    • If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
    • +

    • Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
    • +
    +

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

    + + +
    +

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

    + +

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

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

      +

    1. Voting classifiers
    2. +

    3. Bagging and Pasting
    4. +

    5. Random forests
    6. +

    7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
    8. +
    +

    + +We discuss these methods here. +

    + + +
    +

    An Overview of Ensemble Methods

    + +

    +



    +
    + + +
    +

    Bagging

    + +

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

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

    + + +
    +

    More bagging

    + +

    +Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +

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

    + + +
    +

    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])
    +plt.show()
    +
    +
    + + +
    +

    Using the Voting Classifier

    +

    + + +

    from sklearn.model_selection import train_test_split
    +from sklearn.datasets import make_moons
    +
    +X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    +
    +from sklearn.ensemble import RandomForestClassifier
    +from sklearn.ensemble import VotingClassifier
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.svm import SVC
    +
    +log_clf = LogisticRegression(solver="liblinear", random_state=42)
    +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    +svm_clf = SVC(gamma="auto", random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='hard')
    +
    +voting_clf.fit(X_train, y_train)
    +
    +from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +log_clf = LogisticRegression(solver="liblinear", random_state=42)
    +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    +svm_clf = SVC(gamma="auto", probability=True, random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='soft')
    +voting_clf.fit(X_train, y_train)
    +
    +from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +
    + + +
    +

    Please, not the moons again! Voting and Bagging

    +

    + + +

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

    + + +

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

    + + +

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

    + + +

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

    Now Bagging

    + +

    + + +

    from sklearn.ensemble import BaggingClassifier
    +from sklearn.tree import DecisionTreeClassifier
    +
    +bag_clf = BaggingClassifier(
    +    DecisionTreeClassifier(random_state=42), n_estimators=500,
    +    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
    +bag_clf.fit(X_train, y_train)
    +y_pred = bag_clf.predict(X_test)
    +
    +

    + + +

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

    + + +

    tree_clf = DecisionTreeClassifier(random_state=42)
    +tree_clf.fit(X_train, y_train)
    +y_pred_tree = tree_clf.predict(X_test)
    +print(accuracy_score(y_test, y_pred_tree))
    +
    +

    + + +

    from matplotlib.colors import ListedColormap
    +
    +def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
    +    x1s = np.linspace(axes[0], axes[1], 100)
    +    x2s = np.linspace(axes[2], axes[3], 100)
    +    x1, x2 = np.meshgrid(x1s, x2s)
    +    X_new = np.c_[x1.ravel(), x2.ravel()]
    +    y_pred = clf.predict(X_new).reshape(x1.shape)
    +    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    +    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    +    if contour:
    +        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    +        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    +    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
    +    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
    +    plt.axis(axes)
    +    plt.xlabel(r"$x_1$", fontsize=18)
    +    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    +plt.figure(figsize=(11,4))
    +plt.subplot(121)
    +plot_decision_boundary(tree_clf, X, y)
    +plt.title("Decision Tree", fontsize=14)
    +plt.subplot(122)
    +plot_decision_boundary(bag_clf, X, y)
    +plt.title("Decision Trees with Bagging", fontsize=14)
    +plt.show()
    +
    +
    + + +
    +

    Making our own Bagging with Bootstrap

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.tree import DecisionTreeRegressor
    +
    +
    +np.random.seed(2018)
    +
    +n = 40
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = DecisionTreeRegressor(max_depth=5) 
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_)
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +
    + + +
    +

    Changing the Level of the Decision Tree

    + +

    + + +

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

    Random forests

    + +

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

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

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

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

     
    + +

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

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

    + + +
    +

    Random Forest Algorithm

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

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

      +

    1. For \( m=1:M \) we
    2. + +
        + +

      • Draw a bootstrap sample of from the training data organized in our \( \boldsymbol{X} \) matrix.
      • + +

      • We grow then a random forest tree \( T_m \) 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 \) varibales 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
        6. +
        +

        +

      +

    3. Output then the ensemble of trees \( \{T_m\}_1^{M} \) and make predictions for either a regression type of problem or a classification type of problem.
    4. +
    +
    + + +
    +

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    + +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.ensemble import RandomForestRegressor
    +
    +np.random.seed(2018)
    +
    +n = 100
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = RandomForestRegressor()
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_.ravel())
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +
    + + +
    +

    Random Forests Compared with other Methods on the Cancer Data

    +

    + + +

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

    Compare Bagging on Trees with Random Forests

    +

    + + +

    bag_clf = BaggingClassifier(
    +    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    +    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
    +
    +

    + + +

    bag_clf.fit(X_train, y_train)
    +y_pred = bag_clf.predict(X_test)
    +from sklearn.ensemble import RandomForestClassifier
    +rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
    +rnd_clf.fit(X_train, y_train)
    +y_pred_rf = rnd_clf.predict(X_test)
    +np.sum(y_pred == y_pred_rf) / len(y_pred) 
    +
    +
    + + +
    +

    Boosting, a Bird'e Eye

    + +

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

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

    + + +
    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    + +

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

    +We can then define the misclassification error \( \mathrm{err} \) as +

     
    +$$ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(\boldsymbol{X}_{i*}), +$$ +

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

    + + +
    +

    Basic Steps of AdaBoost

    + +

    +With the above definitions we are now ready to set up the algorithm for AdaBoost. +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 to see then that \( \sum_{i=0}^{n-1}w_i = 1 \).
    2. +

    3. We rewrite the misclassification error as
    4. +
    +

     
    +$$ +\mathrm{err}=\frac{\sum_{i=0}^{n-1}w_iI(y_i\ne G(\boldsymbol{X}_{i*})}{\sum_{i=0}^{n-1}w_i}, +$$ +

     
    + + +

      +

    1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. + +
        +

      1. Fit then a given classifier to the training 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{err})/\mathrm{err}}
      6. +

      7. Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(\boldsymbol{X}_{i*})}.
      8. +
      +

    2. Compute the new classifier $G(\boldsymbol{X})= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(\boldsymbol{X}_{i*}).
    3. +
    +

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

    + + +
    +

    AdaBoost Examples

    + +

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

    + + +

    from sklearn.ensemble import AdaBoostClassifier
    +
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    +ada_clf.fit(X_train, y_train)
    +
    +plot_decision_boundary(ada_clf, X, y)
    +
    +m = len(X_train)
    +
    +plt.figure(figsize=(11, 4))
    +for subplot, learning_rate in ((121, 1), (122, 0.5)):
    +    sample_weights = np.ones(m)
    +    plt.subplot(subplot)
    +    for i in range(5):
    +        svm_clf = SVC(kernel="rbf", C=0.05, gamma="auto", random_state=42)
    +        svm_clf.fit(X_train, y_train, sample_weight=sample_weights)
    +        y_pred = svm_clf.predict(X_train)
    +        sample_weights[y_pred != y_train] *= (1 + learning_rate)
    +        plot_decision_boundary(svm_clf, X, y, alpha=0.2)
    +        plt.title("learning_rate = {}".format(learning_rate), fontsize=16)
    +    if subplot == 121:
    +        plt.text(-0.7, -0.65, "1", fontsize=14)
    +        plt.text(-0.6, -0.10, "2", fontsize=14)
    +        plt.text(-0.5,  0.10, "3", fontsize=14)
    +        plt.text(-0.4,  0.55, "4", fontsize=14)
    +        plt.text(-0.3,  0.90, "5", fontsize=14)
    +
    +save_fig("boosting_plot")
    +plt.show()
    +
    +
    + + +
    +

    Gradient boosting: Basics

    + +

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

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

    + + +
    +

    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 least squares function +

     
    +$$ +C(\boldsymbol{y},\boldsymbol{f})=\frac{1}{n}\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ +

     
    + +

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

      +

    1. Initialize our estimate by \( f_0(x)=0 \).
    2. +

    3. For \( m=1:M \), we + +
        +

      1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at $f(x) = f_{m-1}(x);
      2. +

      3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      4. +

      5. update the estimate \( f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x) \);
      6. +
      +

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

    Gradient Boosting, Examples

    +

    + + +

    np.random.seed(42)
    +X = np.random.rand(100, 1) - 0.5
    +y = 3*X[:, 0]**2 + 0.05 * np.random.randn(100)
    +
    +from sklearn.tree import DecisionTreeRegressor
    +
    +tree_reg1 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg1.fit(X, y)
    +
    +y2 = y - tree_reg1.predict(X)
    +tree_reg2 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg2.fit(X, y2)
    +
    +y3 = y2 - tree_reg2.predict(X)
    +tree_reg3 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg3.fit(X, y3)
    +
    +X_new = np.array([[0.8]])
    +y_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3))
    +
    +def plot_predictions(regressors, X, y, axes, label=None, style="r-", data_style="b.", data_label=None):
    +    x1 = np.linspace(axes[0], axes[1], 500)
    +    y_pred = sum(regressor.predict(x1.reshape(-1, 1)) for regressor in regressors)
    +    plt.plot(X[:, 0], y, data_style, label=data_label)
    +    plt.plot(x1, y_pred, style, linewidth=2, label=label)
    +    if label or data_label:
    +        plt.legend(loc="upper center", fontsize=16)
    +    plt.axis(axes)
    +
    +plt.figure(figsize=(11,11))
    +
    +plt.subplot(321)
    +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h_1(x_1)$", style="g-", data_label="Training set")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +plt.title("Residuals and tree predictions", fontsize=16)
    +
    +plt.subplot(322)
    +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1)$", data_label="Training set")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +plt.title("Ensemble predictions", fontsize=16)
    +
    +plt.subplot(323)
    +plot_predictions([tree_reg2], X, y2, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_2(x_1)$", style="g-", data_style="k+", data_label="Residuals")
    +plt.ylabel("$y - h_1(x_1)$", fontsize=16)
    +
    +plt.subplot(324)
    +plot_predictions([tree_reg1, tree_reg2], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1)$")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +
    +plt.subplot(325)
    +plot_predictions([tree_reg3], X, y3, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_3(x_1)$", style="g-", data_style="k+")
    +plt.ylabel("$y - h_1(x_1) - h_2(x_1)$", fontsize=16)
    +plt.xlabel("$x_1$", fontsize=16)
    +
    +plt.subplot(326)
    +plot_predictions([tree_reg1, tree_reg2, tree_reg3], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1) + h_3(x_1)$")
    +plt.xlabel("$x_1$", fontsize=16)
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +
    +save_fig("gradient_boosting_plot")
    +plt.show()
    +
    +from sklearn.ensemble import GradientBoostingRegressor
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0, random_state=42)
    +gbrt.fit(X, y)
    +
    +gbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42)
    +gbrt_slow.fit(X, y)
    +
    +plt.figure(figsize=(11,4))
    +
    +plt.subplot(121)
    +plot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="Ensemble predictions")
    +plt.title("learning_rate={}, n_estimators={}".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14)
    +
    +plt.subplot(122)
    +plot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8])
    +plt.title("learning_rate={}, n_estimators={}".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14)
    +
    +save_fig("gbrt_learning_rate_plot")
    +plt.show()
    +
    +
    + + +
    +

    Gradient Boots with Early Stopping

    +

    + + +

    from sklearn.model_selection import train_test_split
    +from sklearn.metrics import mean_squared_error
    +
    +X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=49)
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120, random_state=42)
    +gbrt.fit(X_train, y_train)
    +
    +errors = [mean_squared_error(y_val, y_pred)
    +          for y_pred in gbrt.staged_predict(X_val)]
    +bst_n_estimators = np.argmin(errors) + 1
    +
    +gbrt_best = GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators, random_state=42)
    +gbrt_best.fit(X_train, y_train)
    +
    +min_error = np.min(errors)
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plt.plot(errors, "b.-")
    +plt.plot([bst_n_estimators, bst_n_estimators], [0, min_error], "k--")
    +plt.plot([0, 120], [min_error, min_error], "k--")
    +plt.plot(bst_n_estimators, min_error, "ko")
    +plt.text(bst_n_estimators, min_error*1.2, "Minimum", ha="center", fontsize=14)
    +plt.axis([0, 120, 0, 0.01])
    +plt.xlabel("Number of trees")
    +plt.title("Validation error", fontsize=14)
    +
    +plt.subplot(122)
    +plot_predictions([gbrt_best], X, y, axes=[-0.5, 0.5, -0.1, 0.8])
    +plt.title("Best model (%d trees)" % bst_n_estimators, fontsize=14)
    +
    +save_fig("early_stopping_gbrt_plot")
    +plt.show()
    +
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, warm_start=True, random_state=42)
    +
    +min_val_error = float("inf")
    +error_going_up = 0
    +for n_estimators in range(1, 120):
    +    gbrt.n_estimators = n_estimators
    +    gbrt.fit(X_train, y_train)
    +    y_pred = gbrt.predict(X_val)
    +    val_error = mean_squared_error(y_val, y_pred)
    +    if val_error < min_val_error:
    +        min_val_error = val_error
    +        error_going_up = 0
    +    else:
    +        error_going_up += 1
    +        if error_going_up == 5:
    +            break  # early stopping
    +
    +
    +print(gbrt.n_estimators)
    +print("Minimum validation MSE:", min_val_error)
    +
    +
    + + +
    +

    XGBoost: Extreme Gradient Boosting

    + +

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

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

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

    + + +
    +

    Regression Case

    + +

    + + +

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

    Xgboost on the Cancer Data

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +import scikitplot as skplt
    +import xgboost as xgb
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +
    +xg_clf = xgb.XGBClassifier()
    +xg_clf.fit(X_train_scaled,y_train)
    +xgb.plot_tree(xg_clf,num_trees=0)
    +plt.rcParams['figure.figsize'] = [50, 10]
    +plt.show()
    +xgb.plot_importance(xg_clf)
    +plt.rcParams['figure.figsize'] = [5, 5]
    +plt.show()
    +
    +
    + + + +
    +
    + + + + + + + + + + + + diff --git a/doc/src/DecisionTrees/DecisionTrees-solarized.html b/doc/src/DecisionTrees/DecisionTrees-solarized.html new file mode 100644 index 000000000..1d6e730c8 --- /dev/null +++ b/doc/src/DecisionTrees/DecisionTrees-solarized.html @@ -0,0 +1,2502 @@ + + + + + + + + +Data Analysis and Machine Learning: From Decision Trees to Forests and all that + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    Data Analysis and Machine Learning: From Decision Trees to Forests and all that

    + +

    + + +

    +Morten Hjorth-Jensen [1, 2] +
    + +

    + + +

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

    +

    Nov 7, 2019

    +
    +

    +









    + +

    Decision trees, overarching aims

    + +

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

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

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

    +A decision tree is typically divided into a root node, the interior nodes, +and the final leaf nodes or just leaves. These entities are then connected by so-called branches. + +

    +The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +

    +









    + +

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    + +

    +



    + +

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

    +









    + +

    General Features

    + +

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

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

    +









    + +

    How do we set it up?

    + +

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

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

    +









    + +

    Decision trees and Regression

    +

    + + +

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

    +









    + +

    Building a tree, regression

    + +

    +There are mainly two steps + +

      +
    1. We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
    2. +
    3. For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
    4. +
    + +How do we construct the regions \( R_1,\dots,R_J \)? In theory, the +regions could have any shape. However, we choose to divide the +predictor space into high-dimensional rectangles, or boxes, for +simplicity and for ease of interpretation of the resulting predictive +model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the +MSE, given by + +$$ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +$$ + +

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

    +









    + +

    A top-down approach, recursive binary splitting

    + +

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

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

    +









    + +

    Making a tree

    + +

    +In order to implement the recursive binary splitting we start by selecting +the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +$$ +\left\{X\vert x_j < s\right\}, +$$ + +and +$$ +\left\{X\vert x_j \geq s\right\}, +$$ + +so that we obtain the lowest MSE, that is +$$ +\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, +$$ + +

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

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

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

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

    + + +

    Pruning the tree

    + +

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

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

    +









    + +

    Cost complexity pruning

    +For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +$$ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +$$ + +is as small as possible. Here \( \overline{T} \) is +the number of terminal nodes of the tree \( T \) , \( R_m \) is the +rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. + +

    +The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +com- plexity and its fit to the training data. When \( \alpha = 0 \), then the +subtree \( T \) will simply equal \( T_0 \), +because then the above equation just measures the +training error. +However, as \( \alpha \) increases, there is a price to pay for +having a tree with many terminal nodes. The above equation will +tend to be minimized for a smaller subtree. + +

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

    +









    + +

    Schematic Regression Procedure

    + +

    +

    +Building a Regression Tree. +

    + +

      +
    1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
    2. +
    3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    4. +
    5. Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
    6. + +
        +
      • repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
      • +
      • Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
      • +
      • Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
      • +
      + +
    7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
    8. +
    +
    + + +

    +









    + +

    A Classification Tree

    + +

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

    +









    + +

    Growing a classification tree

    + +

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

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

    +









    + +

    Classification tree, how to split nodes

    + +

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

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

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

      +
    • Misclassification error
    • +
    + +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +$$ + + +
      +
    • Gini index \( g \)
    • +
    + +$$ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +$$ + + +
      +
    • Information entropy or just entropy \( s \)
    • +
    + +$$ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +$$ + +

    +









    + +

    Visualizing the Tree, Classification

    +

    + + +

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

    +









    + +

    Visualizing the Tree, The Moons

    +

    + + +

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

    +









    + +

    Algorithms for Setting up Decision Trees

    + +

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

      +
    1. The CART (Classification And Regression Tree) algorithm for both classification and regression
    2. +
    3. The ID3 algorithm based on the computation of the information gain for classification
    4. +
    + +We discuss both algorithms with applications here. The popular library Scikit-Learn uses the CART algorithm. For classification problems you can use either the gini index or the entropy to split a tree in two branches. + +

    +









    + +

    The CART algorithm for Classification

    + +

    +









    + +

    The CART algorithm for Regression

    + +

    +









    + +

    Computing the Gini index

    + +

    +The example we will look at is a classical one in many Machine +Learning applications. Based on various meteorological features, we +have several so-called attributes which decide whether we at the end +will do some outdoor activity like skiing, going for a bike ride etc +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +attributes for each feature are then sunny, overcast and rain for the +outlook, hot, cold and mild for temperature, high and normal for +humidity and weak and strong for wind. + +

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

    +









    + +

    Simple Python Code to read in Data and perform Classification

    + +

    + + +

    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.model_selection import train_test_split
    +from sklearn.tree import export_graphviz
    +from sklearn.preprocessing import StandardScaler, OneHotEncoder
    +from sklearn.compose import ColumnTransformer
    +from IPython.display import Image 
    +from pydot import graph_from_dot_data
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +infile = open(data_path("rideclass.csv"),'r')
    +
    +# Read the experimental data with Pandas
    +from IPython.display import display
    +ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
    +ridedata = pd.DataFrame(ridedata)
    +
    +# Features and targets
    +X = ridedata.loc[:, ridedata.columns != 'Ride'].values
    +y = ridedata.loc[:, ridedata.columns == 'Ride'].values
    +
    +# Create the encoder.
    +encoder = OneHotEncoder(handle_unknown="ignore")
    +# Assume for simplicity all features are categorical.
    +encoder.fit(X)    
    +# Apply the encoder.
    +X = encoder.transform(X)
    +print(X)
    +# Then do a Classification tree
    +tree_clf = DecisionTreeClassifier(max_depth=2)
    +tree_clf.fit(X, y)
    +print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
    +#transfer to a decision tree graph
    +export_graphviz(
    +    tree_clf,
    +    out_file="DataFiles/ride.dot",
    +    rounded=True,
    +    filled=True
    +)
    +cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
    +os.system(cmd)
    +
    +

    +









    + +

    Computing the Gini Factor

    + +

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

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

    + + +

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

    +









    + +

    Entropy and the ID3 algorithm

    + +

    +ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? + +

      +
    1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
    2. +
    3. The best attribute is selected and used as the test at the root node of the tree.
    4. +
    5. A descendant of the root node is then created for each possible value of this attribute.
    6. +
    7. Training examples are sorted to the appropriate descendant node.
    8. +
    9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
    10. +
    11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
    12. +
    + +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

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

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

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

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

    +









    + +

    Implementing the ID3 Algorithm

    + +

    + + +

    import re
    +import math
    +from collections import deque
    +
    +# x is examples in training set
    +# y is set of targets
    +# label is target attributes
    +# Node is a class which has properties values, childs, and next
    +# root is top node in the decision tree
    +
    +class Node(object):
    +	def __init__(self):
    +		self.value = None
    +		self.next = None
    +		self.childs = None
    +
    +# Simple class of Decision Tree
    +# Aimed for who want to learn Decision Tree, so it is not optimized
    +class DecisionTree(object):
    +	def __init__(self, sample, attributes, labels):
    +		self.sample = sample
    +		self.attributes = attributes
    +		self.labels = labels
    +		self.labelCodes = None
    +		self.labelCodesCount = None
    +		self.initLabelCodes()
    +		# print(self.labelCodes)
    +		self.root = None
    +		self.entropy = self.getEntropy([x for x in range(len(self.labels))])
    +
    +	def initLabelCodes(self):
    +		self.labelCodes = []
    +		self.labelCodesCount = []
    +		for l in self.labels:
    +			if l not in self.labelCodes:
    +				self.labelCodes.append(l)
    +				self.labelCodesCount.append(0)
    +			self.labelCodesCount[self.labelCodes.index(l)] += 1
    +
    +	def getLabelCodeId(self, sampleId):
    +		return self.labelCodes.index(self.labels[sampleId])
    +
    +	def getAttributeValues(self, sampleIds, attributeId):
    +		vals = []
    +		for sid in sampleIds:
    +			val = self.sample[sid][attributeId]
    +			if val not in vals:
    +				vals.append(val)
    +		# print(vals)
    +		return vals
    +
    +	def getEntropy(self, sampleIds):
    +		entropy = 0
    +		labelCount = [0] * len(self.labelCodes)
    +		for sid in sampleIds:
    +			labelCount[self.getLabelCodeId(sid)] += 1
    +		# print("-ge", labelCount)
    +		for lv in labelCount:
    +			# print(lv)
    +			if lv != 0:
    +				entropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)
    +			else:
    +				entropy += 0
    +		return entropy
    +
    +	def getDominantLabel(self, sampleIds):
    +		labelCodesCount = [0] * len(self.labelCodes)
    +		for sid in sampleIds:
    +			labelCodesCount[self.labelCodes.index(self.labels[sid])] += 1
    +		return self.labelCodes[labelCodesCount.index(max(labelCodesCount))]
    +
    +	def getInformationGain(self, sampleIds, attributeId):
    +		gain = self.getEntropy(sampleIds)
    +		attributeVals = []
    +		attributeValsCount = []
    +		attributeValsIds = []
    +		for sid in sampleIds:
    +			val = self.sample[sid][attributeId]
    +			if val not in attributeVals:
    +				attributeVals.append(val)
    +				attributeValsCount.append(0)
    +				attributeValsIds.append([])
    +			vid = attributeVals.index(val)
    +			attributeValsCount[vid] += 1
    +			attributeValsIds[vid].append(sid)
    +		# print("-gig", self.attributes[attributeId])
    +		for vc, vids in zip(attributeValsCount, attributeValsIds):
    +			# print("-gig", vids)
    +			gain -= vc/len(sampleIds) * self.getEntropy(vids)
    +		return gain
    +
    +	def getAttributeMaxInformationGain(self, sampleIds, attributeIds):
    +		attributesEntropy = [0] * len(attributeIds)
    +		for i, attId in zip(range(len(attributeIds)), attributeIds):
    +			attributesEntropy[i] = self.getInformationGain(sampleIds, attId)
    +		maxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]
    +		return self.attributes[maxId], maxId
    +
    +	def isSingleLabeled(self, sampleIds):
    +		label = self.labels[sampleIds[0]]
    +		for sid in sampleIds:
    +			if self.labels[sid] != label:
    +				return False
    +		return True
    +
    +	def getLabel(self, sampleId):
    +		return self.labels[sampleId]
    +
    +	def id3(self):
    +		sampleIds = [x for x in range(len(self.sample))]
    +		attributeIds = [x for x in range(len(self.attributes))]
    +		self.root = self.id3Recv(sampleIds, attributeIds, self.root)
    +
    +	def id3Recv(self, sampleIds, attributeIds, root):
    +		root = Node() # Initialize current root
    +		if self.isSingleLabeled(sampleIds):
    +			root.value = self.labels[sampleIds[0]]
    +			return root
    +		# print(attributeIds)
    +		if len(attributeIds) == 0:
    +			root.value = self.getDominantLabel(sampleIds)
    +			return root
    +		bestAttrName, bestAttrId = self.getAttributeMaxInformationGain(
    +			sampleIds, attributeIds)
    +		# print(bestAttrName)
    +		root.value = bestAttrName
    +		root.childs = []  # Create list of children
    +		for value in self.getAttributeValues(sampleIds, bestAttrId):
    +			# print(value)
    +			child = Node()
    +			child.value = value
    +			root.childs.append(child)  # Append new child node to current
    +									   # root
    +			childSampleIds = []
    +			for sid in sampleIds:
    +				if self.sample[sid][bestAttrId] == value:
    +					childSampleIds.append(sid)
    +			if len(childSampleIds) == 0:
    +				child.next = self.getDominantLabel(sampleIds)
    +			else:
    +				# print(bestAttrName, bestAttrId)
    +				# print(attributeIds)
    +				if len(attributeIds) > 0 and bestAttrId in attributeIds:
    +					toRemove = attributeIds.index(bestAttrId)
    +					attributeIds.pop(toRemove)
    +				child.next = self.id3Recv(
    +					childSampleIds, attributeIds, child.next)
    +		return root
    +
    +	def printTree(self):
    +		if self.root:
    +			roots = deque()
    +			roots.append(self.root)
    +			while len(roots) > 0:
    +				root = roots.popleft()
    +				print(root.value)
    +				if root.childs:
    +					for child in root.childs:
    +						print('({})'.format(child.value))
    +						roots.append(child.next)
    +				elif root.next:
    +					print(root.next)
    +
    +
    +def test():
    +	f = open('DataFiles/rideclass.csv')
    +	attributes = f.readline().split(',')
    +	attributes = attributes[1:len(attributes)-1]
    +	print(attributes)
    +	sample = f.readlines()
    +	f.close()
    +	for i in range(len(sample)):
    +		sample[i] = re.sub('\d+,', '', sample[i])
    +		sample[i] = sample[i].strip().split(',')
    +	labels = []
    +	for s in sample:
    +		labels.append(s.pop())
    +	# print(sample)
    +	# print(labels)
    +	decisionTree = DecisionTree(sample, attributes, labels)
    +	print("System entropy {}".format(decisionTree.entropy))
    +	decisionTree.id3()
    +	decisionTree.printTree()
    +
    +
    +if __name__ == '__main__':
    +	test()
    +
    +

    +









    + +

    Cancer Data again now with Decision Trees and other Methods

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.svm import SVC
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.tree import DecisionTreeClassifier
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +# Support vector machine
    +svm = SVC(gamma='auto', C=100)
    +svm.fit(X_train, y_train)
    +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
    +# Decision Trees
    +deep_tree_clf = DecisionTreeClassifier(max_depth=None)
    +deep_tree_clf.fit(X_train, y_train)
    +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +# Logistic Regression
    +logreg.fit(X_train_scaled, y_train)
    +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Support Vector Machine
    +svm.fit(X_train_scaled, y_train)
    +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Decision Trees
    +deep_tree_clf.fit(X_train_scaled, y_train)
    +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
    +
    +

    +









    + +

    Another example, the moons again

    +

    + + +

    from __future__ import division, print_function, unicode_literals
    +
    +# Common imports
    +import numpy as np
    +import os
    +
    +# to make this notebook's output stable across runs
    +np.random.seed(42)
    +
    +# To plot pretty figures
    +import matplotlib
    +import matplotlib.pyplot as plt
    +from matplotlib.colors import ListedColormap
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
    +
    +
    +from sklearn.svm import SVC
    +from sklearn import datasets
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.datasets import make_moons
    +from sklearn.tree import export_graphviz
    +
    +Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
    +
    +deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
    +deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
    +deep_tree_clf1.fit(Xm, ym)
    +deep_tree_clf2.fit(Xm, ym)
    +
    +
    +def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
    +    x1s = np.linspace(axes[0], axes[1], 100)
    +    x2s = np.linspace(axes[2], axes[3], 100)
    +    x1, x2 = np.meshgrid(x1s, x2s)
    +    X_new = np.c_[x1.ravel(), x2.ravel()]
    +    y_pred = clf.predict(X_new).reshape(x1.shape)
    +    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    +    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    +    if not iris:
    +        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    +        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    +    if plot_training:
    +        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
    +        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
    +        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
    +        plt.axis(axes)
    +    if iris:
    +        plt.xlabel("Petal length", fontsize=14)
    +        plt.ylabel("Petal width", fontsize=14)
    +    else:
    +        plt.xlabel(r"$x_1$", fontsize=18)
    +        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    +    if legend:
    +        plt.legend(loc="lower right", fontsize=14)
    +plt.figure(figsize=(11, 4))
    +plt.subplot(121)
    +plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    +plt.title("No restrictions", fontsize=16)
    +plt.subplot(122)
    +plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    +plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
    +plt.show()
    +
    +

    +









    + +

    Playing around with regions

    +

    + + +

    np.random.seed(6)
    +Xs = np.random.rand(100, 2) - 0.5
    +ys = (Xs[:, 0] > 0).astype(np.float32) * 2
    +
    +angle = np.pi/4
    +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
    +Xsr = Xs.dot(rotation_matrix)
    +
    +tree_clf_s = DecisionTreeClassifier(random_state=42)
    +tree_clf_s.fit(Xs, ys)
    +tree_clf_sr = DecisionTreeClassifier(random_state=42)
    +tree_clf_sr.fit(Xsr, ys)
    +
    +plt.figure(figsize=(11, 4))
    +plt.subplot(121)
    +plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    +plt.subplot(122)
    +plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    +
    +plt.show()
    +
    +

    +









    + +

    Regression trees

    +

    + + +

    # Quadratic training set + noise
    +np.random.seed(42)
    +m = 200
    +X = np.random.rand(m, 1)
    +y = 4 * (X - 0.5) ** 2
    +y = y + np.random.randn(m, 1) / 10
    +
    +

    + + +

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

    +









    + +

    Final regressor code

    +

    + + +

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

    + + +

    tree_reg1 = DecisionTreeRegressor(random_state=42)
    +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
    +tree_reg1.fit(X, y)
    +tree_reg2.fit(X, y)
    +
    +x1 = np.linspace(0, 1, 500).reshape(-1, 1)
    +y_pred1 = tree_reg1.predict(x1)
    +y_pred2 = tree_reg2.predict(x1)
    +
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plt.plot(X, y, "b.")
    +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
    +plt.axis([0, 1, -0.2, 1.1])
    +plt.xlabel("$x_1$", fontsize=18)
    +plt.ylabel("$y$", fontsize=18, rotation=0)
    +plt.legend(loc="upper center", fontsize=18)
    +plt.title("No restrictions", fontsize=14)
    +
    +plt.subplot(122)
    +plt.plot(X, y, "b.")
    +plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
    +plt.axis([0, 1, -0.2, 1.1])
    +plt.xlabel("$x_1$", fontsize=18)
    +plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
    +
    +plt.show()
    +
    +

    +









    + +

    Pros and cons of trees, pros

    + +
      +
    • White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
    • +
    • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
    • +
    • No feature normalization needed
    • +
    • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
    • +
    • Can model nonlinear relationships
    • +
    • Can model interactions between the different descriptive features
    • +
    • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
    • +
    + +









    + +

    Disadvantages

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

    +









    + +

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

    + +

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

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

      +
    1. Voting classifiers
    2. +
    3. Bagging and Pasting
    4. +
    5. Random forests
    6. +
    7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
    8. +
    + +We discuss these methods here. + +

    +









    + +

    An Overview of Ensemble Methods

    + +

    +



    + +

    +









    + +

    Bagging

    + +

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

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

    +









    + +

    More bagging

    + +

    +Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +

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

    +









    + +

    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])
    +plt.show()
    +
    +

    +









    + +

    Using the Voting Classifier

    +

    + + +

    from sklearn.model_selection import train_test_split
    +from sklearn.datasets import make_moons
    +
    +X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    +
    +from sklearn.ensemble import RandomForestClassifier
    +from sklearn.ensemble import VotingClassifier
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.svm import SVC
    +
    +log_clf = LogisticRegression(solver="liblinear", random_state=42)
    +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    +svm_clf = SVC(gamma="auto", random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='hard')
    +
    +voting_clf.fit(X_train, y_train)
    +
    +from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +log_clf = LogisticRegression(solver="liblinear", random_state=42)
    +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    +svm_clf = SVC(gamma="auto", probability=True, random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='soft')
    +voting_clf.fit(X_train, y_train)
    +
    +from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +

    +









    + +

    Please, not the moons again! Voting and Bagging

    +

    + + +

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

    + + +

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

    + + +

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

    + + +

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

    +









    + +

    Now Bagging

    + +

    + + +

    from sklearn.ensemble import BaggingClassifier
    +from sklearn.tree import DecisionTreeClassifier
    +
    +bag_clf = BaggingClassifier(
    +    DecisionTreeClassifier(random_state=42), n_estimators=500,
    +    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
    +bag_clf.fit(X_train, y_train)
    +y_pred = bag_clf.predict(X_test)
    +
    +

    + + +

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

    + + +

    tree_clf = DecisionTreeClassifier(random_state=42)
    +tree_clf.fit(X_train, y_train)
    +y_pred_tree = tree_clf.predict(X_test)
    +print(accuracy_score(y_test, y_pred_tree))
    +
    +

    + + +

    from matplotlib.colors import ListedColormap
    +
    +def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
    +    x1s = np.linspace(axes[0], axes[1], 100)
    +    x2s = np.linspace(axes[2], axes[3], 100)
    +    x1, x2 = np.meshgrid(x1s, x2s)
    +    X_new = np.c_[x1.ravel(), x2.ravel()]
    +    y_pred = clf.predict(X_new).reshape(x1.shape)
    +    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    +    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    +    if contour:
    +        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    +        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    +    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
    +    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
    +    plt.axis(axes)
    +    plt.xlabel(r"$x_1$", fontsize=18)
    +    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    +plt.figure(figsize=(11,4))
    +plt.subplot(121)
    +plot_decision_boundary(tree_clf, X, y)
    +plt.title("Decision Tree", fontsize=14)
    +plt.subplot(122)
    +plot_decision_boundary(bag_clf, X, y)
    +plt.title("Decision Trees with Bagging", fontsize=14)
    +plt.show()
    +
    +

    +









    + +

    Making our own Bagging with Bootstrap

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.tree import DecisionTreeRegressor
    +
    +
    +np.random.seed(2018)
    +
    +n = 40
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = DecisionTreeRegressor(max_depth=5) 
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_)
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +

    +









    + +

    Changing the Level of the Decision Tree

    + +

    + + +

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

    +









    + +

    Random forests

    + +

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

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

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

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

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

    +









    + +

    Random Forest Algorithm

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

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

      +
    1. For \( m=1:M \) we
    2. + +
        +
      • Draw a bootstrap sample of from the training data organized in our \( \boldsymbol{X} \) matrix.
      • +
      • We grow then a random forest tree \( T_m \) 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 \) varibales 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
        6. +
        + +
      + +
    3. Output then the ensemble of trees \( \{T_m\}_1^{M} \) and make predictions for either a regression type of problem or a classification type of problem.
    4. +
    + +









    + +

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    + +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.ensemble import RandomForestRegressor
    +
    +np.random.seed(2018)
    +
    +n = 100
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = RandomForestRegressor()
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_.ravel())
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +

    +









    + +

    Random Forests Compared with other Methods on the Cancer Data

    +

    + + +

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

    +









    + +

    Compare Bagging on Trees with Random Forests

    +

    + + +

    bag_clf = BaggingClassifier(
    +    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    +    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
    +
    +

    + + +

    bag_clf.fit(X_train, y_train)
    +y_pred = bag_clf.predict(X_test)
    +from sklearn.ensemble import RandomForestClassifier
    +rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
    +rnd_clf.fit(X_train, y_train)
    +y_pred_rf = rnd_clf.predict(X_test)
    +np.sum(y_pred == y_pred_rf) / len(y_pred) 
    +
    +

    +









    + +

    Boosting, a Bird'e Eye

    + +

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

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

    +









    + +

    Adaptive boosting: AdaBoost, Basic Algorithm

    + +

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

    +We can then define the misclassification error \( \mathrm{err} \) as +$$ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(\boldsymbol{X}_{i*}), +$$ + +where the function \( I() \) is one if we misclassify and zero if we classify correctly. + +

    +









    + +

    Basic Steps of AdaBoost

    + +

    +With the above definitions we are now ready to set up the algorithm for AdaBoost. +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 to see then that \( \sum_{i=0}^{n-1}w_i = 1 \).
    2. +
    3. We rewrite the misclassification error as
    4. +
    + +$$ +\mathrm{err}=\frac{\sum_{i=0}^{n-1}w_iI(y_i\ne G(\boldsymbol{X}_{i*})}{\sum_{i=0}^{n-1}w_i}, +$$ + + +
      +
    1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. + +
        +
      1. Fit then a given classifier to the training 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{err})/\mathrm{err}}
      6. +
      7. Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(\boldsymbol{X}_{i*})}.
      8. +
      + +
    2. Compute the new classifier $G(\boldsymbol{X})= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(\boldsymbol{X}_{i*}).
    3. +
    + +For the iterations with \( m \le 2 \) the weights are modified +individually at each steps. The obersvations which were misclassified +at iteration \( m-1 \) have a weight which is larger than those which were +classified properly. As this proceeds, the observations which were +difficult to classifiy correctly are given a larger influence. Each +new classification step \( m \) is then forced to concentrate on those +observations that are missed in the previous iterations. + +

    +









    + +

    AdaBoost Examples

    + +

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

    + + +

    from sklearn.ensemble import AdaBoostClassifier
    +
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    +ada_clf.fit(X_train, y_train)
    +
    +plot_decision_boundary(ada_clf, X, y)
    +
    +m = len(X_train)
    +
    +plt.figure(figsize=(11, 4))
    +for subplot, learning_rate in ((121, 1), (122, 0.5)):
    +    sample_weights = np.ones(m)
    +    plt.subplot(subplot)
    +    for i in range(5):
    +        svm_clf = SVC(kernel="rbf", C=0.05, gamma="auto", random_state=42)
    +        svm_clf.fit(X_train, y_train, sample_weight=sample_weights)
    +        y_pred = svm_clf.predict(X_train)
    +        sample_weights[y_pred != y_train] *= (1 + learning_rate)
    +        plot_decision_boundary(svm_clf, X, y, alpha=0.2)
    +        plt.title("learning_rate = {}".format(learning_rate), fontsize=16)
    +    if subplot == 121:
    +        plt.text(-0.7, -0.65, "1", fontsize=14)
    +        plt.text(-0.6, -0.10, "2", fontsize=14)
    +        plt.text(-0.5,  0.10, "3", fontsize=14)
    +        plt.text(-0.4,  0.55, "4", fontsize=14)
    +        plt.text(-0.3,  0.90, "5", fontsize=14)
    +
    +save_fig("boosting_plot")
    +plt.show()
    +
    +

    +









    + +

    Gradient boosting: Basics

    + +

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

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

    +









    + +

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

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

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









    + +

    Gradient Boosting, Examples

    +

    + + +

    np.random.seed(42)
    +X = np.random.rand(100, 1) - 0.5
    +y = 3*X[:, 0]**2 + 0.05 * np.random.randn(100)
    +
    +from sklearn.tree import DecisionTreeRegressor
    +
    +tree_reg1 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg1.fit(X, y)
    +
    +y2 = y - tree_reg1.predict(X)
    +tree_reg2 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg2.fit(X, y2)
    +
    +y3 = y2 - tree_reg2.predict(X)
    +tree_reg3 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg3.fit(X, y3)
    +
    +X_new = np.array([[0.8]])
    +y_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3))
    +
    +def plot_predictions(regressors, X, y, axes, label=None, style="r-", data_style="b.", data_label=None):
    +    x1 = np.linspace(axes[0], axes[1], 500)
    +    y_pred = sum(regressor.predict(x1.reshape(-1, 1)) for regressor in regressors)
    +    plt.plot(X[:, 0], y, data_style, label=data_label)
    +    plt.plot(x1, y_pred, style, linewidth=2, label=label)
    +    if label or data_label:
    +        plt.legend(loc="upper center", fontsize=16)
    +    plt.axis(axes)
    +
    +plt.figure(figsize=(11,11))
    +
    +plt.subplot(321)
    +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h_1(x_1)$", style="g-", data_label="Training set")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +plt.title("Residuals and tree predictions", fontsize=16)
    +
    +plt.subplot(322)
    +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1)$", data_label="Training set")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +plt.title("Ensemble predictions", fontsize=16)
    +
    +plt.subplot(323)
    +plot_predictions([tree_reg2], X, y2, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_2(x_1)$", style="g-", data_style="k+", data_label="Residuals")
    +plt.ylabel("$y - h_1(x_1)$", fontsize=16)
    +
    +plt.subplot(324)
    +plot_predictions([tree_reg1, tree_reg2], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1)$")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +
    +plt.subplot(325)
    +plot_predictions([tree_reg3], X, y3, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_3(x_1)$", style="g-", data_style="k+")
    +plt.ylabel("$y - h_1(x_1) - h_2(x_1)$", fontsize=16)
    +plt.xlabel("$x_1$", fontsize=16)
    +
    +plt.subplot(326)
    +plot_predictions([tree_reg1, tree_reg2, tree_reg3], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1) + h_3(x_1)$")
    +plt.xlabel("$x_1$", fontsize=16)
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +
    +save_fig("gradient_boosting_plot")
    +plt.show()
    +
    +from sklearn.ensemble import GradientBoostingRegressor
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0, random_state=42)
    +gbrt.fit(X, y)
    +
    +gbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42)
    +gbrt_slow.fit(X, y)
    +
    +plt.figure(figsize=(11,4))
    +
    +plt.subplot(121)
    +plot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="Ensemble predictions")
    +plt.title("learning_rate={}, n_estimators={}".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14)
    +
    +plt.subplot(122)
    +plot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8])
    +plt.title("learning_rate={}, n_estimators={}".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14)
    +
    +save_fig("gbrt_learning_rate_plot")
    +plt.show()
    +
    +

    +









    + +

    Gradient Boots with Early Stopping

    +

    + + +

    from sklearn.model_selection import train_test_split
    +from sklearn.metrics import mean_squared_error
    +
    +X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=49)
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120, random_state=42)
    +gbrt.fit(X_train, y_train)
    +
    +errors = [mean_squared_error(y_val, y_pred)
    +          for y_pred in gbrt.staged_predict(X_val)]
    +bst_n_estimators = np.argmin(errors) + 1
    +
    +gbrt_best = GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators, random_state=42)
    +gbrt_best.fit(X_train, y_train)
    +
    +min_error = np.min(errors)
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plt.plot(errors, "b.-")
    +plt.plot([bst_n_estimators, bst_n_estimators], [0, min_error], "k--")
    +plt.plot([0, 120], [min_error, min_error], "k--")
    +plt.plot(bst_n_estimators, min_error, "ko")
    +plt.text(bst_n_estimators, min_error*1.2, "Minimum", ha="center", fontsize=14)
    +plt.axis([0, 120, 0, 0.01])
    +plt.xlabel("Number of trees")
    +plt.title("Validation error", fontsize=14)
    +
    +plt.subplot(122)
    +plot_predictions([gbrt_best], X, y, axes=[-0.5, 0.5, -0.1, 0.8])
    +plt.title("Best model (%d trees)" % bst_n_estimators, fontsize=14)
    +
    +save_fig("early_stopping_gbrt_plot")
    +plt.show()
    +
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, warm_start=True, random_state=42)
    +
    +min_val_error = float("inf")
    +error_going_up = 0
    +for n_estimators in range(1, 120):
    +    gbrt.n_estimators = n_estimators
    +    gbrt.fit(X_train, y_train)
    +    y_pred = gbrt.predict(X_val)
    +    val_error = mean_squared_error(y_val, y_pred)
    +    if val_error < min_val_error:
    +        min_val_error = val_error
    +        error_going_up = 0
    +    else:
    +        error_going_up += 1
    +        if error_going_up == 5:
    +            break  # early stopping
    +
    +
    +print(gbrt.n_estimators)
    +print("Minimum validation MSE:", min_val_error)
    +
    +

    +









    + +

    XGBoost: Extreme Gradient Boosting

    + +

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

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

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

    +









    + +

    Regression Case

    + +

    + + +

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

    +









    + +

    Xgboost on the Cancer Data

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +import scikitplot as skplt
    +import xgboost as xgb
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +
    +xg_clf = xgb.XGBClassifier()
    +xg_clf.fit(X_train_scaled,y_train)
    +xgb.plot_tree(xg_clf,num_trees=0)
    +plt.rcParams['figure.figsize'] = [50, 10]
    +plt.show()
    +xgb.plot_importance(xg_clf)
    +plt.rcParams['figure.figsize'] = [5, 5]
    +plt.show()
    +
    +

    + + + + +

    + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
    + + + + + + diff --git a/doc/src/DecisionTrees/DecisionTrees.do.txt b/doc/src/DecisionTrees/DecisionTrees.do.txt index 59a5a1bf7..cbdaccecb 100644 --- a/doc/src/DecisionTrees/DecisionTrees.do.txt +++ b/doc/src/DecisionTrees/DecisionTrees.do.txt @@ -1567,6 +1567,70 @@ o For $m=1:M$ we o Output then the ensemble of trees $\{T_m\}_1^{M}$ and make predictions for either a regression type of problem or a classification type of problem. +!split +===== Bootstrap with Random Forests Instead of a Single Tree, own Bagging ===== + +!bc pycod + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.ensemble import RandomForestRegressor + +np.random.seed(2018) + +n = 100 +n_boostraps = 100 +maxdegree = 14 + +# 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) + +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) + +for degree in range(maxdegree): + model = RandomForestRegressor() + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_.ravel()) + y_pred[:, i] = model.predict(X_test_scaled).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + +!ec + + + + !split ===== Random Forests Compared with other Methods on the Cancer Data ===== !bc pycod @@ -1661,67 +1725,6 @@ np.sum(y_pred == y_pred_rf) / len(y_pred) -!split -===== Bootstrap with Random Forests Instead of a Single Tree, own Bagging ===== - -!bc pycod - -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.pipeline import make_pipeline -from sklearn.utils import resample -from sklearn.ensemble import RandomForestRegressor - -np.random.seed(2018) - -n = 100 -n_boostraps = 100 -maxdegree = 14 - -# 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) - -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) - -for degree in range(maxdegree): - model = RandomForestRegressor() - y_pred = np.empty((y_test.shape[0], n_boostraps)) - for i in range(n_boostraps): - x_, y_ = resample(X_train_scaled, y_train) - model.fit(x_, y_.ravel()) - y_pred[:, i] = model.predict(X_test_scaled).ravel() - - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) - variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) - print('Polynomial degree:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) - -plt.plot(polydegree, error, label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') -plt.legend() -plt.show() - - - -!ec - !split diff --git a/doc/src/DecisionTrees/DecisionTrees.html b/doc/src/DecisionTrees/DecisionTrees.html new file mode 100644 index 000000000..e66d392b2 --- /dev/null +++ b/doc/src/DecisionTrees/DecisionTrees.html @@ -0,0 +1,2507 @@ + + + + + + + + +Data Analysis and Machine Learning: From Decision Trees to Forests and all that + + + + + + + + + + + + + + + + + + + + + + + +

    Data Analysis and Machine Learning: From Decision Trees to Forests and all that

    + +

    + + +

    +Morten Hjorth-Jensen [1, 2] +
    + +

    + + +

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

    +

    Nov 7, 2019

    +
    +

    +









    + +

    Decision trees, overarching aims

    + +

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

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

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

    +A decision tree is typically divided into a root node, the interior nodes, +and the final leaf nodes or just leaves. These entities are then connected by so-called branches. + +

    +The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +

    +









    + +

    A typical Decision Tree with its pertinent Jargon, Classification Problem

    + +

    +



    + +

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

    +









    + +

    General Features

    + +

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

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

    +









    + +

    How do we set it up?

    + +

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

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

    +









    + +

    Decision trees and Regression

    +

    + + +

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

    +









    + +

    Building a tree, regression

    + +

    +There are mainly two steps + +

      +
    1. We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
    2. +
    3. For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
    4. +
    + +How do we construct the regions \( R_1,\dots,R_J \)? In theory, the +regions could have any shape. However, we choose to divide the +predictor space into high-dimensional rectangles, or boxes, for +simplicity and for ease of interpretation of the resulting predictive +model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the +MSE, given by + +$$ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +$$ + +

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

    +









    + +

    A top-down approach, recursive binary splitting

    + +

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

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

    +









    + +

    Making a tree

    + +

    +In order to implement the recursive binary splitting we start by selecting +the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +$$ +\left\{X\vert x_j < s\right\}, +$$ + +and +$$ +\left\{X\vert x_j \geq s\right\}, +$$ + +so that we obtain the lowest MSE, that is +$$ +\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, +$$ + +

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

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

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

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

    + + +

    Pruning the tree

    + +

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

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

    +









    + +

    Cost complexity pruning

    +For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +$$ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +$$ + +is as small as possible. Here \( \overline{T} \) is +the number of terminal nodes of the tree \( T \) , \( R_m \) is the +rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. + +

    +The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +com- plexity and its fit to the training data. When \( \alpha = 0 \), then the +subtree \( T \) will simply equal \( T_0 \), +because then the above equation just measures the +training error. +However, as \( \alpha \) increases, there is a price to pay for +having a tree with many terminal nodes. The above equation will +tend to be minimized for a smaller subtree. + +

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

    +









    + +

    Schematic Regression Procedure

    + +

    +

    +Building a Regression Tree. +

    + +

      +
    1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
    2. +
    3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
    4. +
    5. Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
    6. + +
        +
      • repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
      • +
      • Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
      • +
      • Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
      • +
      + +
    7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
    8. +
    +
    + + +

    +









    + +

    A Classification Tree

    + +

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

    +









    + +

    Growing a classification tree

    + +

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

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

    +









    + +

    Classification tree, how to split nodes

    + +

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

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

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

      +
    • Misclassification error
    • +
    + +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +$$ + + +
      +
    • Gini index \( g \)
    • +
    + +$$ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +$$ + + +
      +
    • Information entropy or just entropy \( s \)
    • +
    + +$$ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +$$ + +

    +









    + +

    Visualizing the Tree, Classification

    +

    + + +

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

    +









    + +

    Visualizing the Tree, The Moons

    +

    + + +

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

    +









    + +

    Algorithms for Setting up Decision Trees

    + +

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

      +
    1. The CART (Classification And Regression Tree) algorithm for both classification and regression
    2. +
    3. The ID3 algorithm based on the computation of the information gain for classification
    4. +
    + +We discuss both algorithms with applications here. The popular library Scikit-Learn uses the CART algorithm. For classification problems you can use either the gini index or the entropy to split a tree in two branches. + +

    +









    + +

    The CART algorithm for Classification

    + +

    +









    + +

    The CART algorithm for Regression

    + +

    +









    + +

    Computing the Gini index

    + +

    +The example we will look at is a classical one in many Machine +Learning applications. Based on various meteorological features, we +have several so-called attributes which decide whether we at the end +will do some outdoor activity like skiing, going for a bike ride etc +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +attributes for each feature are then sunny, overcast and rain for the +outlook, hot, cold and mild for temperature, high and normal for +humidity and weak and strong for wind. + +

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

    +









    + +

    Simple Python Code to read in Data and perform Classification

    + +

    + + +

    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.model_selection import train_test_split
    +from sklearn.tree import export_graphviz
    +from sklearn.preprocessing import StandardScaler, OneHotEncoder
    +from sklearn.compose import ColumnTransformer
    +from IPython.display import Image 
    +from pydot import graph_from_dot_data
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +infile = open(data_path("rideclass.csv"),'r')
    +
    +# Read the experimental data with Pandas
    +from IPython.display import display
    +ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
    +ridedata = pd.DataFrame(ridedata)
    +
    +# Features and targets
    +X = ridedata.loc[:, ridedata.columns != 'Ride'].values
    +y = ridedata.loc[:, ridedata.columns == 'Ride'].values
    +
    +# Create the encoder.
    +encoder = OneHotEncoder(handle_unknown="ignore")
    +# Assume for simplicity all features are categorical.
    +encoder.fit(X)    
    +# Apply the encoder.
    +X = encoder.transform(X)
    +print(X)
    +# Then do a Classification tree
    +tree_clf = DecisionTreeClassifier(max_depth=2)
    +tree_clf.fit(X, y)
    +print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
    +#transfer to a decision tree graph
    +export_graphviz(
    +    tree_clf,
    +    out_file="DataFiles/ride.dot",
    +    rounded=True,
    +    filled=True
    +)
    +cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
    +os.system(cmd)
    +
    +

    +









    + +

    Computing the Gini Factor

    + +

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

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

    + + +

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

    +









    + +

    Entropy and the ID3 algorithm

    + +

    +ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? + +

      +
    1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
    2. +
    3. The best attribute is selected and used as the test at the root node of the tree.
    4. +
    5. A descendant of the root node is then created for each possible value of this attribute.
    6. +
    7. Training examples are sorted to the appropriate descendant node.
    8. +
    9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
    10. +
    11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
    12. +
    + +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

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

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

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

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

    +









    + +

    Implementing the ID3 Algorithm

    + +

    + + +

    import re
    +import math
    +from collections import deque
    +
    +# x is examples in training set
    +# y is set of targets
    +# label is target attributes
    +# Node is a class which has properties values, childs, and next
    +# root is top node in the decision tree
    +
    +class Node(object):
    +	def __init__(self):
    +		self.value = None
    +		self.next = None
    +		self.childs = None
    +
    +# Simple class of Decision Tree
    +# Aimed for who want to learn Decision Tree, so it is not optimized
    +class DecisionTree(object):
    +	def __init__(self, sample, attributes, labels):
    +		self.sample = sample
    +		self.attributes = attributes
    +		self.labels = labels
    +		self.labelCodes = None
    +		self.labelCodesCount = None
    +		self.initLabelCodes()
    +		# print(self.labelCodes)
    +		self.root = None
    +		self.entropy = self.getEntropy([x for x in range(len(self.labels))])
    +
    +	def initLabelCodes(self):
    +		self.labelCodes = []
    +		self.labelCodesCount = []
    +		for l in self.labels:
    +			if l not in self.labelCodes:
    +				self.labelCodes.append(l)
    +				self.labelCodesCount.append(0)
    +			self.labelCodesCount[self.labelCodes.index(l)] += 1
    +
    +	def getLabelCodeId(self, sampleId):
    +		return self.labelCodes.index(self.labels[sampleId])
    +
    +	def getAttributeValues(self, sampleIds, attributeId):
    +		vals = []
    +		for sid in sampleIds:
    +			val = self.sample[sid][attributeId]
    +			if val not in vals:
    +				vals.append(val)
    +		# print(vals)
    +		return vals
    +
    +	def getEntropy(self, sampleIds):
    +		entropy = 0
    +		labelCount = [0] * len(self.labelCodes)
    +		for sid in sampleIds:
    +			labelCount[self.getLabelCodeId(sid)] += 1
    +		# print("-ge", labelCount)
    +		for lv in labelCount:
    +			# print(lv)
    +			if lv != 0:
    +				entropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)
    +			else:
    +				entropy += 0
    +		return entropy
    +
    +	def getDominantLabel(self, sampleIds):
    +		labelCodesCount = [0] * len(self.labelCodes)
    +		for sid in sampleIds:
    +			labelCodesCount[self.labelCodes.index(self.labels[sid])] += 1
    +		return self.labelCodes[labelCodesCount.index(max(labelCodesCount))]
    +
    +	def getInformationGain(self, sampleIds, attributeId):
    +		gain = self.getEntropy(sampleIds)
    +		attributeVals = []
    +		attributeValsCount = []
    +		attributeValsIds = []
    +		for sid in sampleIds:
    +			val = self.sample[sid][attributeId]
    +			if val not in attributeVals:
    +				attributeVals.append(val)
    +				attributeValsCount.append(0)
    +				attributeValsIds.append([])
    +			vid = attributeVals.index(val)
    +			attributeValsCount[vid] += 1
    +			attributeValsIds[vid].append(sid)
    +		# print("-gig", self.attributes[attributeId])
    +		for vc, vids in zip(attributeValsCount, attributeValsIds):
    +			# print("-gig", vids)
    +			gain -= vc/len(sampleIds) * self.getEntropy(vids)
    +		return gain
    +
    +	def getAttributeMaxInformationGain(self, sampleIds, attributeIds):
    +		attributesEntropy = [0] * len(attributeIds)
    +		for i, attId in zip(range(len(attributeIds)), attributeIds):
    +			attributesEntropy[i] = self.getInformationGain(sampleIds, attId)
    +		maxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]
    +		return self.attributes[maxId], maxId
    +
    +	def isSingleLabeled(self, sampleIds):
    +		label = self.labels[sampleIds[0]]
    +		for sid in sampleIds:
    +			if self.labels[sid] != label:
    +				return False
    +		return True
    +
    +	def getLabel(self, sampleId):
    +		return self.labels[sampleId]
    +
    +	def id3(self):
    +		sampleIds = [x for x in range(len(self.sample))]
    +		attributeIds = [x for x in range(len(self.attributes))]
    +		self.root = self.id3Recv(sampleIds, attributeIds, self.root)
    +
    +	def id3Recv(self, sampleIds, attributeIds, root):
    +		root = Node() # Initialize current root
    +		if self.isSingleLabeled(sampleIds):
    +			root.value = self.labels[sampleIds[0]]
    +			return root
    +		# print(attributeIds)
    +		if len(attributeIds) == 0:
    +			root.value = self.getDominantLabel(sampleIds)
    +			return root
    +		bestAttrName, bestAttrId = self.getAttributeMaxInformationGain(
    +			sampleIds, attributeIds)
    +		# print(bestAttrName)
    +		root.value = bestAttrName
    +		root.childs = []  # Create list of children
    +		for value in self.getAttributeValues(sampleIds, bestAttrId):
    +			# print(value)
    +			child = Node()
    +			child.value = value
    +			root.childs.append(child)  # Append new child node to current
    +									   # root
    +			childSampleIds = []
    +			for sid in sampleIds:
    +				if self.sample[sid][bestAttrId] == value:
    +					childSampleIds.append(sid)
    +			if len(childSampleIds) == 0:
    +				child.next = self.getDominantLabel(sampleIds)
    +			else:
    +				# print(bestAttrName, bestAttrId)
    +				# print(attributeIds)
    +				if len(attributeIds) > 0 and bestAttrId in attributeIds:
    +					toRemove = attributeIds.index(bestAttrId)
    +					attributeIds.pop(toRemove)
    +				child.next = self.id3Recv(
    +					childSampleIds, attributeIds, child.next)
    +		return root
    +
    +	def printTree(self):
    +		if self.root:
    +			roots = deque()
    +			roots.append(self.root)
    +			while len(roots) > 0:
    +				root = roots.popleft()
    +				print(root.value)
    +				if root.childs:
    +					for child in root.childs:
    +						print('({})'.format(child.value))
    +						roots.append(child.next)
    +				elif root.next:
    +					print(root.next)
    +
    +
    +def test():
    +	f = open('DataFiles/rideclass.csv')
    +	attributes = f.readline().split(',')
    +	attributes = attributes[1:len(attributes)-1]
    +	print(attributes)
    +	sample = f.readlines()
    +	f.close()
    +	for i in range(len(sample)):
    +		sample[i] = re.sub('\d+,', '', sample[i])
    +		sample[i] = sample[i].strip().split(',')
    +	labels = []
    +	for s in sample:
    +		labels.append(s.pop())
    +	# print(sample)
    +	# print(labels)
    +	decisionTree = DecisionTree(sample, attributes, labels)
    +	print("System entropy {}".format(decisionTree.entropy))
    +	decisionTree.id3()
    +	decisionTree.printTree()
    +
    +
    +if __name__ == '__main__':
    +	test()
    +
    +

    +









    + +

    Cancer Data again now with Decision Trees and other Methods

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.svm import SVC
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.tree import DecisionTreeClassifier
    +
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +# Support vector machine
    +svm = SVC(gamma='auto', C=100)
    +svm.fit(X_train, y_train)
    +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
    +# Decision Trees
    +deep_tree_clf = DecisionTreeClassifier(max_depth=None)
    +deep_tree_clf.fit(X_train, y_train)
    +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +# Logistic Regression
    +logreg.fit(X_train_scaled, y_train)
    +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Support Vector Machine
    +svm.fit(X_train_scaled, y_train)
    +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Decision Trees
    +deep_tree_clf.fit(X_train_scaled, y_train)
    +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
    +
    +

    +









    + +

    Another example, the moons again

    +

    + + +

    from __future__ import division, print_function, unicode_literals
    +
    +# Common imports
    +import numpy as np
    +import os
    +
    +# to make this notebook's output stable across runs
    +np.random.seed(42)
    +
    +# To plot pretty figures
    +import matplotlib
    +import matplotlib.pyplot as plt
    +from matplotlib.colors import ListedColormap
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
    +
    +
    +from sklearn.svm import SVC
    +from sklearn import datasets
    +from sklearn.tree import DecisionTreeClassifier
    +from sklearn.datasets import make_moons
    +from sklearn.tree import export_graphviz
    +
    +Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
    +
    +deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
    +deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
    +deep_tree_clf1.fit(Xm, ym)
    +deep_tree_clf2.fit(Xm, ym)
    +
    +
    +def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
    +    x1s = np.linspace(axes[0], axes[1], 100)
    +    x2s = np.linspace(axes[2], axes[3], 100)
    +    x1, x2 = np.meshgrid(x1s, x2s)
    +    X_new = np.c_[x1.ravel(), x2.ravel()]
    +    y_pred = clf.predict(X_new).reshape(x1.shape)
    +    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    +    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    +    if not iris:
    +        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    +        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    +    if plot_training:
    +        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
    +        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
    +        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
    +        plt.axis(axes)
    +    if iris:
    +        plt.xlabel("Petal length", fontsize=14)
    +        plt.ylabel("Petal width", fontsize=14)
    +    else:
    +        plt.xlabel(r"$x_1$", fontsize=18)
    +        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    +    if legend:
    +        plt.legend(loc="lower right", fontsize=14)
    +plt.figure(figsize=(11, 4))
    +plt.subplot(121)
    +plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    +plt.title("No restrictions", fontsize=16)
    +plt.subplot(122)
    +plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
    +plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
    +plt.show()
    +
    +

    +









    + +

    Playing around with regions

    +

    + + +

    np.random.seed(6)
    +Xs = np.random.rand(100, 2) - 0.5
    +ys = (Xs[:, 0] > 0).astype(np.float32) * 2
    +
    +angle = np.pi/4
    +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
    +Xsr = Xs.dot(rotation_matrix)
    +
    +tree_clf_s = DecisionTreeClassifier(random_state=42)
    +tree_clf_s.fit(Xs, ys)
    +tree_clf_sr = DecisionTreeClassifier(random_state=42)
    +tree_clf_sr.fit(Xsr, ys)
    +
    +plt.figure(figsize=(11, 4))
    +plt.subplot(121)
    +plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    +plt.subplot(122)
    +plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
    +
    +plt.show()
    +
    +

    +









    + +

    Regression trees

    +

    + + +

    # Quadratic training set + noise
    +np.random.seed(42)
    +m = 200
    +X = np.random.rand(m, 1)
    +y = 4 * (X - 0.5) ** 2
    +y = y + np.random.randn(m, 1) / 10
    +
    +

    + + +

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

    +









    + +

    Final regressor code

    +

    + + +

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

    + + +

    tree_reg1 = DecisionTreeRegressor(random_state=42)
    +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
    +tree_reg1.fit(X, y)
    +tree_reg2.fit(X, y)
    +
    +x1 = np.linspace(0, 1, 500).reshape(-1, 1)
    +y_pred1 = tree_reg1.predict(x1)
    +y_pred2 = tree_reg2.predict(x1)
    +
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plt.plot(X, y, "b.")
    +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
    +plt.axis([0, 1, -0.2, 1.1])
    +plt.xlabel("$x_1$", fontsize=18)
    +plt.ylabel("$y$", fontsize=18, rotation=0)
    +plt.legend(loc="upper center", fontsize=18)
    +plt.title("No restrictions", fontsize=14)
    +
    +plt.subplot(122)
    +plt.plot(X, y, "b.")
    +plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
    +plt.axis([0, 1, -0.2, 1.1])
    +plt.xlabel("$x_1$", fontsize=18)
    +plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
    +
    +plt.show()
    +
    +

    +









    + +

    Pros and cons of trees, pros

    + +
      +
    • White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
    • +
    • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
    • +
    • No feature normalization needed
    • +
    • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
    • +
    • Can model nonlinear relationships
    • +
    • Can model interactions between the different descriptive features
    • +
    • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
    • +
    + +









    + +

    Disadvantages

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

    +









    + +

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

    + +

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

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

      +
    1. Voting classifiers
    2. +
    3. Bagging and Pasting
    4. +
    5. Random forests
    6. +
    7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
    8. +
    + +We discuss these methods here. + +

    +









    + +

    An Overview of Ensemble Methods

    + +

    +



    + +

    +









    + +

    Bagging

    + +

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

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

    +









    + +

    More bagging

    + +

    +Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +

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

    +









    + +

    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])
    +plt.show()
    +
    +

    +









    + +

    Using the Voting Classifier

    +

    + + +

    from sklearn.model_selection import train_test_split
    +from sklearn.datasets import make_moons
    +
    +X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
    +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
    +
    +from sklearn.ensemble import RandomForestClassifier
    +from sklearn.ensemble import VotingClassifier
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.svm import SVC
    +
    +log_clf = LogisticRegression(solver="liblinear", random_state=42)
    +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    +svm_clf = SVC(gamma="auto", random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='hard')
    +
    +voting_clf.fit(X_train, y_train)
    +
    +from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +log_clf = LogisticRegression(solver="liblinear", random_state=42)
    +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
    +svm_clf = SVC(gamma="auto", probability=True, random_state=42)
    +
    +voting_clf = VotingClassifier(
    +    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    +    voting='soft')
    +voting_clf.fit(X_train, y_train)
    +
    +from sklearn.metrics import accuracy_score
    +
    +for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    +    clf.fit(X_train, y_train)
    +    y_pred = clf.predict(X_test)
    +    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
    +
    +

    +









    + +

    Please, not the moons again! Voting and Bagging

    +

    + + +

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

    + + +

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

    + + +

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

    + + +

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

    +









    + +

    Now Bagging

    + +

    + + +

    from sklearn.ensemble import BaggingClassifier
    +from sklearn.tree import DecisionTreeClassifier
    +
    +bag_clf = BaggingClassifier(
    +    DecisionTreeClassifier(random_state=42), n_estimators=500,
    +    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
    +bag_clf.fit(X_train, y_train)
    +y_pred = bag_clf.predict(X_test)
    +
    +

    + + +

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

    + + +

    tree_clf = DecisionTreeClassifier(random_state=42)
    +tree_clf.fit(X_train, y_train)
    +y_pred_tree = tree_clf.predict(X_test)
    +print(accuracy_score(y_test, y_pred_tree))
    +
    +

    + + +

    from matplotlib.colors import ListedColormap
    +
    +def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
    +    x1s = np.linspace(axes[0], axes[1], 100)
    +    x2s = np.linspace(axes[2], axes[3], 100)
    +    x1, x2 = np.meshgrid(x1s, x2s)
    +    X_new = np.c_[x1.ravel(), x2.ravel()]
    +    y_pred = clf.predict(X_new).reshape(x1.shape)
    +    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    +    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    +    if contour:
    +        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
    +        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    +    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
    +    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
    +    plt.axis(axes)
    +    plt.xlabel(r"$x_1$", fontsize=18)
    +    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    +plt.figure(figsize=(11,4))
    +plt.subplot(121)
    +plot_decision_boundary(tree_clf, X, y)
    +plt.title("Decision Tree", fontsize=14)
    +plt.subplot(122)
    +plot_decision_boundary(bag_clf, X, y)
    +plt.title("Decision Trees with Bagging", fontsize=14)
    +plt.show()
    +
    +

    +









    + +

    Making our own Bagging with Bootstrap

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.tree import DecisionTreeRegressor
    +
    +
    +np.random.seed(2018)
    +
    +n = 40
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = DecisionTreeRegressor(max_depth=5) 
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_)
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +

    +









    + +

    Changing the Level of the Decision Tree

    + +

    + + +

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

    +









    + +

    Random forests

    + +

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

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

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

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

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

    +









    + +

    Random Forest Algorithm

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

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

      +
    1. For \( m=1:M \) we
    2. + +
        +
      • Draw a bootstrap sample of from the training data organized in our \( \boldsymbol{X} \) matrix.
      • +
      • We grow then a random forest tree \( T_m \) 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 \) varibales 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
        6. +
        + +
      + +
    3. Output then the ensemble of trees \( \{T_m\}_1^{M} \) and make predictions for either a regression type of problem or a classification type of problem.
    4. +
    + +









    + +

    Bootstrap with Random Forests Instead of a Single Tree, own Bagging

    + +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +from sklearn.ensemble import RandomForestRegressor
    +
    +np.random.seed(2018)
    +
    +n = 100
    +n_boostraps = 100
    +maxdegree = 14
    +
    +# 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)
    +
    +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)
    +
    +for degree in range(maxdegree):
    +    model = RandomForestRegressor()
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(X_train_scaled, y_train)
    +        model.fit(x_, y_.ravel())
    +        y_pred[:, i] = model.predict(X_test_scaled).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, error, label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    +

    +









    + +

    Random Forests Compared with other Methods on the Cancer Data

    +

    + + +

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

    +









    + +

    Compare Bagging on Trees with Random Forests

    +

    + + +

    bag_clf = BaggingClassifier(
    +    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    +    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
    +
    +

    + + +

    bag_clf.fit(X_train, y_train)
    +y_pred = bag_clf.predict(X_test)
    +from sklearn.ensemble import RandomForestClassifier
    +rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
    +rnd_clf.fit(X_train, y_train)
    +y_pred_rf = rnd_clf.predict(X_test)
    +np.sum(y_pred == y_pred_rf) / len(y_pred) 
    +
    +

    +









    + +

    Boosting, a Bird'e Eye

    + +

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

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

    +









    + +

    Adaptive boosting: AdaBoost, Basic Algorithm

    + +

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

    +We can then define the misclassification error \( \mathrm{err} \) as +$$ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(\boldsymbol{X}_{i*}), +$$ + +where the function \( I() \) is one if we misclassify and zero if we classify correctly. + +

    +









    + +

    Basic Steps of AdaBoost

    + +

    +With the above definitions we are now ready to set up the algorithm for AdaBoost. +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 to see then that \( \sum_{i=0}^{n-1}w_i = 1 \).
    2. +
    3. We rewrite the misclassification error as
    4. +
    + +$$ +\mathrm{err}=\frac{\sum_{i=0}^{n-1}w_iI(y_i\ne G(\boldsymbol{X}_{i*})}{\sum_{i=0}^{n-1}w_i}, +$$ + + +
      +
    1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. + +
        +
      1. Fit then a given classifier to the training 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{err})/\mathrm{err}}
      6. +
      7. Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(\boldsymbol{X}_{i*})}.
      8. +
      + +
    2. Compute the new classifier $G(\boldsymbol{X})= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(\boldsymbol{X}_{i*}).
    3. +
    + +For the iterations with \( m \le 2 \) the weights are modified +individually at each steps. The obersvations which were misclassified +at iteration \( m-1 \) have a weight which is larger than those which were +classified properly. As this proceeds, the observations which were +difficult to classifiy correctly are given a larger influence. Each +new classification step \( m \) is then forced to concentrate on those +observations that are missed in the previous iterations. + +

    +









    + +

    AdaBoost Examples

    + +

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

    + + +

    from sklearn.ensemble import AdaBoostClassifier
    +
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    +ada_clf.fit(X_train, y_train)
    +
    +plot_decision_boundary(ada_clf, X, y)
    +
    +m = len(X_train)
    +
    +plt.figure(figsize=(11, 4))
    +for subplot, learning_rate in ((121, 1), (122, 0.5)):
    +    sample_weights = np.ones(m)
    +    plt.subplot(subplot)
    +    for i in range(5):
    +        svm_clf = SVC(kernel="rbf", C=0.05, gamma="auto", random_state=42)
    +        svm_clf.fit(X_train, y_train, sample_weight=sample_weights)
    +        y_pred = svm_clf.predict(X_train)
    +        sample_weights[y_pred != y_train] *= (1 + learning_rate)
    +        plot_decision_boundary(svm_clf, X, y, alpha=0.2)
    +        plt.title("learning_rate = {}".format(learning_rate), fontsize=16)
    +    if subplot == 121:
    +        plt.text(-0.7, -0.65, "1", fontsize=14)
    +        plt.text(-0.6, -0.10, "2", fontsize=14)
    +        plt.text(-0.5,  0.10, "3", fontsize=14)
    +        plt.text(-0.4,  0.55, "4", fontsize=14)
    +        plt.text(-0.3,  0.90, "5", fontsize=14)
    +
    +save_fig("boosting_plot")
    +plt.show()
    +
    +

    +









    + +

    Gradient boosting: Basics

    + +

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

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

    +









    + +

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

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

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









    + +

    Gradient Boosting, Examples

    +

    + + +

    np.random.seed(42)
    +X = np.random.rand(100, 1) - 0.5
    +y = 3*X[:, 0]**2 + 0.05 * np.random.randn(100)
    +
    +from sklearn.tree import DecisionTreeRegressor
    +
    +tree_reg1 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg1.fit(X, y)
    +
    +y2 = y - tree_reg1.predict(X)
    +tree_reg2 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg2.fit(X, y2)
    +
    +y3 = y2 - tree_reg2.predict(X)
    +tree_reg3 = DecisionTreeRegressor(max_depth=2, random_state=42)
    +tree_reg3.fit(X, y3)
    +
    +X_new = np.array([[0.8]])
    +y_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3))
    +
    +def plot_predictions(regressors, X, y, axes, label=None, style="r-", data_style="b.", data_label=None):
    +    x1 = np.linspace(axes[0], axes[1], 500)
    +    y_pred = sum(regressor.predict(x1.reshape(-1, 1)) for regressor in regressors)
    +    plt.plot(X[:, 0], y, data_style, label=data_label)
    +    plt.plot(x1, y_pred, style, linewidth=2, label=label)
    +    if label or data_label:
    +        plt.legend(loc="upper center", fontsize=16)
    +    plt.axis(axes)
    +
    +plt.figure(figsize=(11,11))
    +
    +plt.subplot(321)
    +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h_1(x_1)$", style="g-", data_label="Training set")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +plt.title("Residuals and tree predictions", fontsize=16)
    +
    +plt.subplot(322)
    +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1)$", data_label="Training set")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +plt.title("Ensemble predictions", fontsize=16)
    +
    +plt.subplot(323)
    +plot_predictions([tree_reg2], X, y2, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_2(x_1)$", style="g-", data_style="k+", data_label="Residuals")
    +plt.ylabel("$y - h_1(x_1)$", fontsize=16)
    +
    +plt.subplot(324)
    +plot_predictions([tree_reg1, tree_reg2], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1)$")
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +
    +plt.subplot(325)
    +plot_predictions([tree_reg3], X, y3, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_3(x_1)$", style="g-", data_style="k+")
    +plt.ylabel("$y - h_1(x_1) - h_2(x_1)$", fontsize=16)
    +plt.xlabel("$x_1$", fontsize=16)
    +
    +plt.subplot(326)
    +plot_predictions([tree_reg1, tree_reg2, tree_reg3], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1) + h_3(x_1)$")
    +plt.xlabel("$x_1$", fontsize=16)
    +plt.ylabel("$y$", fontsize=16, rotation=0)
    +
    +save_fig("gradient_boosting_plot")
    +plt.show()
    +
    +from sklearn.ensemble import GradientBoostingRegressor
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0, random_state=42)
    +gbrt.fit(X, y)
    +
    +gbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42)
    +gbrt_slow.fit(X, y)
    +
    +plt.figure(figsize=(11,4))
    +
    +plt.subplot(121)
    +plot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="Ensemble predictions")
    +plt.title("learning_rate={}, n_estimators={}".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14)
    +
    +plt.subplot(122)
    +plot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8])
    +plt.title("learning_rate={}, n_estimators={}".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14)
    +
    +save_fig("gbrt_learning_rate_plot")
    +plt.show()
    +
    +

    +









    + +

    Gradient Boots with Early Stopping

    +

    + + +

    from sklearn.model_selection import train_test_split
    +from sklearn.metrics import mean_squared_error
    +
    +X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=49)
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120, random_state=42)
    +gbrt.fit(X_train, y_train)
    +
    +errors = [mean_squared_error(y_val, y_pred)
    +          for y_pred in gbrt.staged_predict(X_val)]
    +bst_n_estimators = np.argmin(errors) + 1
    +
    +gbrt_best = GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators, random_state=42)
    +gbrt_best.fit(X_train, y_train)
    +
    +min_error = np.min(errors)
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plt.plot(errors, "b.-")
    +plt.plot([bst_n_estimators, bst_n_estimators], [0, min_error], "k--")
    +plt.plot([0, 120], [min_error, min_error], "k--")
    +plt.plot(bst_n_estimators, min_error, "ko")
    +plt.text(bst_n_estimators, min_error*1.2, "Minimum", ha="center", fontsize=14)
    +plt.axis([0, 120, 0, 0.01])
    +plt.xlabel("Number of trees")
    +plt.title("Validation error", fontsize=14)
    +
    +plt.subplot(122)
    +plot_predictions([gbrt_best], X, y, axes=[-0.5, 0.5, -0.1, 0.8])
    +plt.title("Best model (%d trees)" % bst_n_estimators, fontsize=14)
    +
    +save_fig("early_stopping_gbrt_plot")
    +plt.show()
    +
    +
    +gbrt = GradientBoostingRegressor(max_depth=2, warm_start=True, random_state=42)
    +
    +min_val_error = float("inf")
    +error_going_up = 0
    +for n_estimators in range(1, 120):
    +    gbrt.n_estimators = n_estimators
    +    gbrt.fit(X_train, y_train)
    +    y_pred = gbrt.predict(X_val)
    +    val_error = mean_squared_error(y_val, y_pred)
    +    if val_error < min_val_error:
    +        min_val_error = val_error
    +        error_going_up = 0
    +    else:
    +        error_going_up += 1
    +        if error_going_up == 5:
    +            break  # early stopping
    +
    +
    +print(gbrt.n_estimators)
    +print("Minimum validation MSE:", min_val_error)
    +
    +

    +









    + +

    XGBoost: Extreme Gradient Boosting

    + +

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

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

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

    +









    + +

    Regression Case

    + +

    + + +

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

    +









    + +

    Xgboost on the Cancer Data

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +import scikitplot as skplt
    +import xgboost as xgb
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +
    +xg_clf = xgb.XGBClassifier()
    +xg_clf.fit(X_train_scaled,y_train)
    +xgb.plot_tree(xg_clf,num_trees=0)
    +plt.rcParams['figure.figsize'] = [50, 10]
    +plt.show()
    +xgb.plot_importance(xg_clf)
    +plt.rcParams['figure.figsize'] = [5, 5]
    +plt.show()
    +
    +

    + + + + +

    + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
    + + + + + + diff --git a/doc/src/DecisionTrees/DecisionTrees.ipynb b/doc/src/DecisionTrees/DecisionTrees.ipynb new file mode 100644 index 000000000..1161b80b6 --- /dev/null +++ b/doc/src/DecisionTrees/DecisionTrees.ipynb @@ -0,0 +1,2602 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Data Analysis and Machine Learning: From Decision Trees to Forests and all that\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Nov 7, 2019**\n", + "\n", + "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "\n", + "## Decision trees, overarching aims\n", + "\n", + "\n", + "Decision trees are supervised learning algorithms used for both,\n", + "classification and regression tasks.\n", + "\n", + "\n", + "The main idea of decision trees\n", + "is to find those descriptive features which contain the most\n", + "**information** regarding the target feature and then split the dataset\n", + "along the values of these features such that the target feature values\n", + "for the resulting underlying datasets are as pure as possible.\n", + "\n", + "The descriptive features which reproduce best the target/output features are normally said\n", + "to be the most informative ones. The process of finding the **most\n", + "informative** feature is done until we accomplish a stopping criteria\n", + "where we then finally end up in so called **leaf nodes**. \n", + "\n", + "A decision tree is typically divided into a **root node**, the **interior nodes**,\n", + "and the final **leaf nodes** or just **leaves**. These entities are then connected by so-called **branches**.\n", + "\n", + "The leaf nodes\n", + "contain the predictions we will make for new query instances presented\n", + "to our trained model. This is possible since the model has \n", + "learned the underlying structure of the training data and hence can,\n", + "given some assumptions, make predictions about the target feature value\n", + "(class) of unseen query instances.\n", + "\n", + "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n", + "\n", + "\n", + "\n", + "\n", + "

    \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using **Scikit-Learn**'s decision tree classifier. Here we have used the so-called **gini** index (see below) to split the various branches.\n", + "\n", + "\n", + "\n", + "## General Features\n", + "\n", + "The overarching approach to decision trees is a top-down approach.\n", + "\n", + "* A leaf provides the classification of a given instance.\n", + "\n", + "* A node specifies a test of some attribute of the instance.\n", + "\n", + "* A branch corresponds to a possible values of an attribute.\n", + "\n", + "* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.\n", + "\n", + "This process is then repeated for the subtree rooted at the new\n", + "node.\n", + "\n", + "\n", + "## How do we set it up?\n", + "\n", + "\n", + "In simplified terms, the process of training a decision tree and\n", + "predicting the target features of query instances is as follows:\n", + "\n", + "1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature\n", + "\n", + "2. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process\n", + "\n", + "3. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances\n", + "\n", + "4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n", + "\n", + "Then we are essentially done!\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Decision trees and Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "steps=250\n", + "\n", + "distance=0\n", + "x=0\n", + "distance_list=[]\n", + "steps_list=[]\n", + "while x\n", + "## Pruning the tree\n", + "\n", + "The above procedure is rather straightforward, but leads often to\n", + "overfitting and unnecessarily large and complicated trees. The basic\n", + "idea is to grow a large tree $T_0$ and then prune it back in order to\n", + "obtain a subtree. A smaller tree with fewer splits (fewer regions) can\n", + "lead to smaller variance and better interpretation at the cost of a\n", + "little more bias.\n", + "\n", + "The so-called Cost complexity pruning algorithm gives us a\n", + "way to do just this. Rather than considering every possible subtree,\n", + "we consider a sequence of trees indexed by a nonnegative tuning\n", + "parameter $\\alpha$.\n", + "\n", + "## Cost complexity pruning\n", + "For each value of $\\alpha$ there corresponds a subtree $T \\in T_0$ such that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\sum_{m=1}^{\\overline{T}}\\sum_{i:x_i\\in R_m}(y_i-\\overline{y}_{R_m})^2+\\alpha\\overline{T},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is as small as possible. Here $\\overline{T}$ is \n", + "the number of terminal nodes of the tree $T$ , $R_m$ is the\n", + "rectangle (i.e. the subset of predictor space) corresponding to the $m$-th terminal node.\n", + "\n", + "The tuning parameter $\\alpha$ controls a trade-off between the subtree’s\n", + "com- plexity and its fit to the training data. When $\\alpha = 0$, then the\n", + "subtree $T$ will simply equal $T_0$, \n", + "because then the above equation just measures the\n", + "training error. \n", + "However, as $\\alpha$ increases, there is a price to pay for\n", + "having a tree with many terminal nodes. The above equation will\n", + "tend to be minimized for a smaller subtree. \n", + "\n", + "\n", + "It turns out that as we increase $\\alpha$ from zero\n", + "branches get pruned from the tree in a nested and predictable fashion,\n", + "so obtaining the whole sequence of subtrees as a function of $\\alpha$ is\n", + "easy. We can select a value of $\\alpha$ using a validation set or using\n", + "cross-validation. We then return to the full data set and obtain the\n", + "subtree corresponding to $\\alpha$. \n", + "\n", + "\n", + "## Schematic Regression Procedure\n", + "\n", + "**Building a Regression Tree.**\n", + "\n", + "1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.\n", + "\n", + "2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of $\\alpha$.\n", + "\n", + "3. Use for example $K$-fold cross-validation to choose $\\alpha$. Divide the training observations into $K$ folds. For each $k=1,2,\\dots,K$ we: \n", + "\n", + " * repeat steps 1 and 2 on all but the $k$-th fold of the training data. \n", + "\n", + " * Then we valuate the mean squared prediction error on the data in the left-out $k$-th fold, as a function of $\\alpha$.\n", + "\n", + " * Finally we average the results for each value of $\\alpha$, and pick $\\alpha$ to minimize the average error.\n", + "\n", + "\n", + "4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$.\n", + "\n", + "\n", + "\n", + "\n", + "## A Classification Tree\n", + "\n", + "A classification tree is very similar to a regression tree, except\n", + "that it is used to predict a qualitative response rather than a\n", + "quantitative one. Recall that for a regression tree, the predicted\n", + "response for an observation is given by the mean response of the\n", + "training observations that belong to the same terminal node. In\n", + "contrast, for a classification tree, we predict that each observation\n", + "belongs to the most commonly occurring class of training observations\n", + "in the region to which it belongs. In interpreting the results of a\n", + "classification tree, we are often interested not only in the class\n", + "prediction corresponding to a particular terminal node region, but\n", + "also in the class proportions among the training observations that\n", + "fall into that region. \n", + "\n", + "## Growing a classification tree\n", + "\n", + "The task of growing a\n", + "classification tree is quite similar to the task of growing a\n", + "regression tree. Just as in the regression setting, we use recursive\n", + "binary splitting to grow a classification tree. However, in the\n", + "classification setting, the MSE cannot be used as a criterion for making\n", + "the binary splits. A natural alternative to MSE is the **classification\n", + "error rate**. Since we plan to assign an observation in a given region\n", + "to the most commonly occurring error rate class of training\n", + "observations in that region, the classification error rate is simply\n", + "the fraction of the training observations in that region that do not\n", + "belong to the most common class. \n", + "\n", + "When building a classification tree, either the Gini index or the\n", + "entropy are typically used to evaluate the quality of a particular\n", + "split, since these two approaches are more sensitive to node purity\n", + "than is the classification error rate. \n", + "\n", + "\n", + "## Classification tree, how to split nodes\n", + "\n", + "If our targets are the outcome of a classification process that takes\n", + "for example $k=1,2,\\dots,K$ values, the only thing we need to think of\n", + "is to set up the splitting criteria for each node.\n", + "\n", + "We define a PDF $p_{mk}$ that represents the number of observations of\n", + "a class $k$ in a region $R_m$ with $N_m$ observations. We represent\n", + "this likelihood function in terms of the proportion $I(y_i=k)$ of\n", + "observations of this class in the region $R_m$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i=k).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We let $p_{mk}$ represent the majority class of observations in region\n", + "$m$. The three most common ways of splitting a node are given by\n", + "\n", + "* Misclassification error" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Gini index $g$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "g = \\sum_{k=1}^K p_{mk}(1-p_{mk}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Information entropy or just entropy $s$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Visualizing the Tree, Classification" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.metrics import confusion_matrix\n", + "from sklearn.tree import export_graphviz\n", + "\n", + "from IPython.display import Image \n", + "from pydot import graph_from_dot_data\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "\n", + "cancer = load_breast_cancer()\n", + "X = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n", + "print(X)\n", + "y = pd.Categorical.from_codes(cancer.target, cancer.target_names)\n", + "y = pd.get_dummies(y)\n", + "print(y)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n", + "tree_clf = DecisionTreeClassifier(max_depth=5)\n", + "tree_clf.fit(X_train, y_train)\n", + "\n", + "export_graphviz(\n", + " tree_clf,\n", + " out_file=\"DataFiles/cancer.dot\",\n", + " feature_names=cancer.feature_names,\n", + " class_names=cancer.target_names,\n", + " rounded=True,\n", + " filled=True\n", + ")\n", + "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n", + "os.system(cmd)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Visualizing the Tree, The Moons" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Common imports\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.datasets import make_moons\n", + "from sklearn.tree import export_graphviz\n", + "from pydot import graph_from_dot_data\n", + "import pandas as pd\n", + "import os\n", + "\n", + "np.random.seed(42)\n", + "X, y = make_moons(n_samples=100, noise=0.25, random_state=53)\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)\n", + "tree_clf = DecisionTreeClassifier(max_depth=5)\n", + "tree_clf.fit(X_train, y_train)\n", + "\n", + "export_graphviz(\n", + " tree_clf,\n", + " out_file=\"DataFiles/moons.dot\",\n", + " rounded=True,\n", + " filled=True\n", + ")\n", + "cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'\n", + "os.system(cmd)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Algorithms for Setting up Decision Trees\n", + "\n", + "Two algorithms stand out in the set up of decision trees:\n", + "1. The CART (Classification And Regression Tree) algorithm for both classification and regression\n", + "\n", + "2. The ID3 algorithm based on the computation of the information gain for classification\n", + "\n", + "We discuss both algorithms with applications here. The popular library **Scikit-Learn** uses the CART algorithm. For classification problems you can use either the **gini** index or the **entropy** to split a tree in two branches.\n", + "\n", + "## The CART algorithm for Classification\n", + "\n", + "\n", + "## The CART algorithm for Regression\n", + "\n", + "\n", + "\n", + "## Computing the Gini index\n", + "\n", + "The example we will look at is a classical one in many Machine\n", + "Learning applications. Based on various meteorological features, we\n", + "have several so-called attributes which decide whether we at the end\n", + "will do some outdoor activity like skiing, going for a bike ride etc\n", + "etc. The table here contains the feautures **outlook**, **temperature**,\n", + "**humidity** and **wind**. The target or output is whether we ride\n", + "(True=1) or whether we do something else that day (False=0). The\n", + "attributes for each feature are then sunny, overcast and rain for the\n", + "outlook, hot, cold and mild for temperature, high and normal for\n", + "humidity and weak and strong for wind.\n", + "\n", + "The table here summarizes the various attributes and\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
    Day Outlook Temperature Humidity Wind Ride
    1 Sunny Hot High Weak 0
    2 Sunny Hot High Strong 1
    3 Overcast Hot High Weak 1
    4 Rain Mild High Weak 1
    5 Rain Cool Normal Weak 1
    6 Rain Cool Normal Strong 0
    7 Overcast Cool Normal Strong 1
    8 Sunny Mild High Weak 0
    9 Sunny Cool Normal Weak 1
    10 Rain Mild Normal Weak 1
    11 Sunny Mild Normal Strong 1
    12 Overcast Mild High Strong 1
    13 Overcast Hot Normal Weak 1
    14 Rain Mild High Strong 0
    \n", + "\n", + "## Simple Python Code to read in Data and perform Classification" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Common imports\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.tree import export_graphviz\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", + "from sklearn.compose import ColumnTransformer\n", + "from IPython.display import Image \n", + "from pydot import graph_from_dot_data\n", + "import os\n", + "\n", + "# Where to save the figures and data files\n", + "PROJECT_ROOT_DIR = \"Results\"\n", + "FIGURE_ID = \"Results/FigureFiles\"\n", + "DATA_ID = \"DataFiles/\"\n", + "\n", + "if not os.path.exists(PROJECT_ROOT_DIR):\n", + " os.mkdir(PROJECT_ROOT_DIR)\n", + "\n", + "if not os.path.exists(FIGURE_ID):\n", + " os.makedirs(FIGURE_ID)\n", + "\n", + "if not os.path.exists(DATA_ID):\n", + " os.makedirs(DATA_ID)\n", + "\n", + "def image_path(fig_id):\n", + " return os.path.join(FIGURE_ID, fig_id)\n", + "\n", + "def data_path(dat_id):\n", + " return os.path.join(DATA_ID, dat_id)\n", + "\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "\n", + "infile = open(data_path(\"rideclass.csv\"),'r')\n", + "\n", + "# Read the experimental data with Pandas\n", + "from IPython.display import display\n", + "ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))\n", + "ridedata = pd.DataFrame(ridedata)\n", + "\n", + "# Features and targets\n", + "X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n", + "y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n", + "\n", + "# Create the encoder.\n", + "encoder = OneHotEncoder(handle_unknown=\"ignore\")\n", + "# Assume for simplicity all features are categorical.\n", + "encoder.fit(X) \n", + "# Apply the encoder.\n", + "X = encoder.transform(X)\n", + "print(X)\n", + "# Then do a Classification tree\n", + "tree_clf = DecisionTreeClassifier(max_depth=2)\n", + "tree_clf.fit(X, y)\n", + "print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n", + "#transfer to a decision tree graph\n", + "export_graphviz(\n", + " tree_clf,\n", + " out_file=\"DataFiles/ride.dot\",\n", + " rounded=True,\n", + " filled=True\n", + ")\n", + "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n", + "os.system(cmd)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Computing the Gini Factor\n", + "\n", + "The above functions (gini, entropy and misclassification error) are\n", + "important components of the so-called CART algorithm. We will discuss\n", + "this algorithm below after we have discussed the information gain\n", + "algorithm ID3.\n", + "\n", + "In the example here we have converted all our attributes into numerical values $0,1,2$ etc." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Split a dataset based on an attribute and an attribute value\n", + "def test_split(index, value, dataset):\n", + "\tleft, right = list(), list()\n", + "\tfor row in dataset:\n", + "\t\tif row[index] < value:\n", + "\t\t\tleft.append(row)\n", + "\t\telse:\n", + "\t\t\tright.append(row)\n", + "\treturn left, right\n", + " \n", + "# Calculate the Gini index for a split dataset\n", + "def gini_index(groups, classes):\n", + "\t# count all samples at split point\n", + "\tn_instances = float(sum([len(group) for group in groups]))\n", + "\t# sum weighted Gini index for each group\n", + "\tgini = 0.0\n", + "\tfor group in groups:\n", + "\t\tsize = float(len(group))\n", + "\t\t# avoid divide by zero\n", + "\t\tif size == 0:\n", + "\t\t\tcontinue\n", + "\t\tscore = 0.0\n", + "\t\t# score the group based on the score for each class\n", + "\t\tfor class_val in classes:\n", + "\t\t\tp = [row[-1] for row in group].count(class_val) / size\n", + "\t\t\tscore += p * p\n", + "\t\t# weight the group score by its relative size\n", + "\t\tgini += (1.0 - score) * (size / n_instances)\n", + "\treturn gini\n", + "\n", + "# Select the best split point for a dataset\n", + "def get_split(dataset):\n", + "\tclass_values = list(set(row[-1] for row in dataset))\n", + "\tb_index, b_value, b_score, b_groups = 999, 999, 999, None\n", + "\tfor index in range(len(dataset[0])-1):\n", + "\t\tfor row in dataset:\n", + "\t\t\tgroups = test_split(index, row[index], dataset)\n", + "\t\t\tgini = gini_index(groups, class_values)\n", + "\t\t\tprint('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))\n", + "\t\t\tif gini < b_score:\n", + "\t\t\t\tb_index, b_value, b_score, b_groups = index, row[index], gini, groups\n", + "\treturn {'index':b_index, 'value':b_value, 'groups':b_groups}\n", + " \n", + "dataset = [[0,0,0,0,0],\n", + " [0,0,0,1,1],\n", + " [1,0,0,0,1],\n", + " [2,1,0,0,1],\n", + " [2,2,1,0,1],\n", + " [2,2,1,1,0],\n", + " [1,2,1,1,1],\n", + " [0,1,0,0,0],\n", + " [0,2,1,0,1],\n", + " [2,1,1,0,1],\n", + " [0,1,1,1,1],\n", + " [1,1,0,1,1],\n", + " [1,0,1,0,1],\n", + " [2,1,0,1,0]]\n", + "\n", + "split = get_split(dataset)\n", + "print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Entropy and the ID3 algorithm\n", + "\n", + "ID3, learns decision trees by constructing\n", + "them topdown, beginning with the question **which attribute should be tested at the root of the tree**?\n", + "\n", + "1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.\n", + "\n", + "2. The best attribute is selected and used as the test at the root node of the tree.\n", + "\n", + "3. A descendant of the root node is then created for each possible value of this attribute.\n", + "\n", + "4. Training examples are sorted to the appropriate descendant node.\n", + "\n", + "5. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.\n", + "\n", + "6. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices. \n", + "\n", + "The ID3 algorithm selects, which attribute to test at each node in the\n", + "tree.\n", + "\n", + "We would like to select the attribute that is most useful for classifying\n", + "examples.\n", + "\n", + "What is a good quantitative measure of the worth of an attribute?\n", + "\n", + "Information gain measures how well a given attribute separates the\n", + "training examples according to their target classification.\n", + "\n", + "The ID3 algorithm uses this information gain measure to select among the candidate\n", + "attributes at each step while growing the tree.\n", + "\n", + "## Implementing the ID3 Algorithm" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import re\n", + "import math\n", + "from collections import deque\n", + "\n", + "# x is examples in training set\n", + "# y is set of targets\n", + "# label is target attributes\n", + "# Node is a class which has properties values, childs, and next\n", + "# root is top node in the decision tree\n", + "\n", + "class Node(object):\n", + "\tdef __init__(self):\n", + "\t\tself.value = None\n", + "\t\tself.next = None\n", + "\t\tself.childs = None\n", + "\n", + "# Simple class of Decision Tree\n", + "# Aimed for who want to learn Decision Tree, so it is not optimized\n", + "class DecisionTree(object):\n", + "\tdef __init__(self, sample, attributes, labels):\n", + "\t\tself.sample = sample\n", + "\t\tself.attributes = attributes\n", + "\t\tself.labels = labels\n", + "\t\tself.labelCodes = None\n", + "\t\tself.labelCodesCount = None\n", + "\t\tself.initLabelCodes()\n", + "\t\t# print(self.labelCodes)\n", + "\t\tself.root = None\n", + "\t\tself.entropy = self.getEntropy([x for x in range(len(self.labels))])\n", + "\n", + "\tdef initLabelCodes(self):\n", + "\t\tself.labelCodes = []\n", + "\t\tself.labelCodesCount = []\n", + "\t\tfor l in self.labels:\n", + "\t\t\tif l not in self.labelCodes:\n", + "\t\t\t\tself.labelCodes.append(l)\n", + "\t\t\t\tself.labelCodesCount.append(0)\n", + "\t\t\tself.labelCodesCount[self.labelCodes.index(l)] += 1\n", + "\n", + "\tdef getLabelCodeId(self, sampleId):\n", + "\t\treturn self.labelCodes.index(self.labels[sampleId])\n", + "\n", + "\tdef getAttributeValues(self, sampleIds, attributeId):\n", + "\t\tvals = []\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tval = self.sample[sid][attributeId]\n", + "\t\t\tif val not in vals:\n", + "\t\t\t\tvals.append(val)\n", + "\t\t# print(vals)\n", + "\t\treturn vals\n", + "\n", + "\tdef getEntropy(self, sampleIds):\n", + "\t\tentropy = 0\n", + "\t\tlabelCount = [0] * len(self.labelCodes)\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tlabelCount[self.getLabelCodeId(sid)] += 1\n", + "\t\t# print(\"-ge\", labelCount)\n", + "\t\tfor lv in labelCount:\n", + "\t\t\t# print(lv)\n", + "\t\t\tif lv != 0:\n", + "\t\t\t\tentropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)\n", + "\t\t\telse:\n", + "\t\t\t\tentropy += 0\n", + "\t\treturn entropy\n", + "\n", + "\tdef getDominantLabel(self, sampleIds):\n", + "\t\tlabelCodesCount = [0] * len(self.labelCodes)\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tlabelCodesCount[self.labelCodes.index(self.labels[sid])] += 1\n", + "\t\treturn self.labelCodes[labelCodesCount.index(max(labelCodesCount))]\n", + "\n", + "\tdef getInformationGain(self, sampleIds, attributeId):\n", + "\t\tgain = self.getEntropy(sampleIds)\n", + "\t\tattributeVals = []\n", + "\t\tattributeValsCount = []\n", + "\t\tattributeValsIds = []\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tval = self.sample[sid][attributeId]\n", + "\t\t\tif val not in attributeVals:\n", + "\t\t\t\tattributeVals.append(val)\n", + "\t\t\t\tattributeValsCount.append(0)\n", + "\t\t\t\tattributeValsIds.append([])\n", + "\t\t\tvid = attributeVals.index(val)\n", + "\t\t\tattributeValsCount[vid] += 1\n", + "\t\t\tattributeValsIds[vid].append(sid)\n", + "\t\t# print(\"-gig\", self.attributes[attributeId])\n", + "\t\tfor vc, vids in zip(attributeValsCount, attributeValsIds):\n", + "\t\t\t# print(\"-gig\", vids)\n", + "\t\t\tgain -= vc/len(sampleIds) * self.getEntropy(vids)\n", + "\t\treturn gain\n", + "\n", + "\tdef getAttributeMaxInformationGain(self, sampleIds, attributeIds):\n", + "\t\tattributesEntropy = [0] * len(attributeIds)\n", + "\t\tfor i, attId in zip(range(len(attributeIds)), attributeIds):\n", + "\t\t\tattributesEntropy[i] = self.getInformationGain(sampleIds, attId)\n", + "\t\tmaxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]\n", + "\t\treturn self.attributes[maxId], maxId\n", + "\n", + "\tdef isSingleLabeled(self, sampleIds):\n", + "\t\tlabel = self.labels[sampleIds[0]]\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tif self.labels[sid] != label:\n", + "\t\t\t\treturn False\n", + "\t\treturn True\n", + "\n", + "\tdef getLabel(self, sampleId):\n", + "\t\treturn self.labels[sampleId]\n", + "\n", + "\tdef id3(self):\n", + "\t\tsampleIds = [x for x in range(len(self.sample))]\n", + "\t\tattributeIds = [x for x in range(len(self.attributes))]\n", + "\t\tself.root = self.id3Recv(sampleIds, attributeIds, self.root)\n", + "\n", + "\tdef id3Recv(self, sampleIds, attributeIds, root):\n", + "\t\troot = Node() # Initialize current root\n", + "\t\tif self.isSingleLabeled(sampleIds):\n", + "\t\t\troot.value = self.labels[sampleIds[0]]\n", + "\t\t\treturn root\n", + "\t\t# print(attributeIds)\n", + "\t\tif len(attributeIds) == 0:\n", + "\t\t\troot.value = self.getDominantLabel(sampleIds)\n", + "\t\t\treturn root\n", + "\t\tbestAttrName, bestAttrId = self.getAttributeMaxInformationGain(\n", + "\t\t\tsampleIds, attributeIds)\n", + "\t\t# print(bestAttrName)\n", + "\t\troot.value = bestAttrName\n", + "\t\troot.childs = [] # Create list of children\n", + "\t\tfor value in self.getAttributeValues(sampleIds, bestAttrId):\n", + "\t\t\t# print(value)\n", + "\t\t\tchild = Node()\n", + "\t\t\tchild.value = value\n", + "\t\t\troot.childs.append(child) # Append new child node to current\n", + "\t\t\t\t\t\t\t\t\t # root\n", + "\t\t\tchildSampleIds = []\n", + "\t\t\tfor sid in sampleIds:\n", + "\t\t\t\tif self.sample[sid][bestAttrId] == value:\n", + "\t\t\t\t\tchildSampleIds.append(sid)\n", + "\t\t\tif len(childSampleIds) == 0:\n", + "\t\t\t\tchild.next = self.getDominantLabel(sampleIds)\n", + "\t\t\telse:\n", + "\t\t\t\t# print(bestAttrName, bestAttrId)\n", + "\t\t\t\t# print(attributeIds)\n", + "\t\t\t\tif len(attributeIds) > 0 and bestAttrId in attributeIds:\n", + "\t\t\t\t\ttoRemove = attributeIds.index(bestAttrId)\n", + "\t\t\t\t\tattributeIds.pop(toRemove)\n", + "\t\t\t\tchild.next = self.id3Recv(\n", + "\t\t\t\t\tchildSampleIds, attributeIds, child.next)\n", + "\t\treturn root\n", + "\n", + "\tdef printTree(self):\n", + "\t\tif self.root:\n", + "\t\t\troots = deque()\n", + "\t\t\troots.append(self.root)\n", + "\t\t\twhile len(roots) > 0:\n", + "\t\t\t\troot = roots.popleft()\n", + "\t\t\t\tprint(root.value)\n", + "\t\t\t\tif root.childs:\n", + "\t\t\t\t\tfor child in root.childs:\n", + "\t\t\t\t\t\tprint('({})'.format(child.value))\n", + "\t\t\t\t\t\troots.append(child.next)\n", + "\t\t\t\telif root.next:\n", + "\t\t\t\t\tprint(root.next)\n", + "\n", + "\n", + "def test():\n", + "\tf = open('DataFiles/rideclass.csv')\n", + "\tattributes = f.readline().split(',')\n", + "\tattributes = attributes[1:len(attributes)-1]\n", + "\tprint(attributes)\n", + "\tsample = f.readlines()\n", + "\tf.close()\n", + "\tfor i in range(len(sample)):\n", + "\t\tsample[i] = re.sub('\\d+,', '', sample[i])\n", + "\t\tsample[i] = sample[i].strip().split(',')\n", + "\tlabels = []\n", + "\tfor s in sample:\n", + "\t\tlabels.append(s.pop())\n", + "\t# print(sample)\n", + "\t# print(labels)\n", + "\tdecisionTree = DecisionTree(sample, attributes, labels)\n", + "\tprint(\"System entropy {}\".format(decisionTree.entropy))\n", + "\tdecisionTree.id3()\n", + "\tdecisionTree.printTree()\n", + "\n", + "\n", + "if __name__ == '__main__':\n", + "\ttest()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Cancer Data again now with Decision Trees and other Methods" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.svm import SVC\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "\n", + "# Load the data\n", + "cancer = load_breast_cancer()\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "# Logistic Regression\n", + "logreg = LogisticRegression(solver='lbfgs')\n", + "logreg.fit(X_train, y_train)\n", + "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", + "# Support vector machine\n", + "svm = SVC(gamma='auto', C=100)\n", + "svm.fit(X_train, y_train)\n", + "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n", + "# Decision Trees\n", + "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n", + "deep_tree_clf.fit(X_train, y_train)\n", + "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n", + "#now scale the data\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "# Logistic Regression\n", + "logreg.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", + "# Support Vector Machine\n", + "svm.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", + "# Decision Trees\n", + "deep_tree_clf.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Another example, the moons again" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from __future__ import division, print_function, unicode_literals\n", + "\n", + "# Common imports\n", + "import numpy as np\n", + "import os\n", + "\n", + "# to make this notebook's output stable across runs\n", + "np.random.seed(42)\n", + "\n", + "# To plot pretty figures\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "from matplotlib.colors import ListedColormap\n", + "plt.rcParams['axes.labelsize'] = 14\n", + "plt.rcParams['xtick.labelsize'] = 12\n", + "plt.rcParams['ytick.labelsize'] = 12\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "from sklearn import datasets\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.datasets import make_moons\n", + "from sklearn.tree import export_graphviz\n", + "\n", + "Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)\n", + "\n", + "deep_tree_clf1 = DecisionTreeClassifier(random_state=42)\n", + "deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)\n", + "deep_tree_clf1.fit(Xm, ym)\n", + "deep_tree_clf2.fit(Xm, ym)\n", + "\n", + "\n", + "def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):\n", + " x1s = np.linspace(axes[0], axes[1], 100)\n", + " x2s = np.linspace(axes[2], axes[3], 100)\n", + " x1, x2 = np.meshgrid(x1s, x2s)\n", + " X_new = np.c_[x1.ravel(), x2.ravel()]\n", + " y_pred = clf.predict(X_new).reshape(x1.shape)\n", + " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n", + " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n", + " if not iris:\n", + " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n", + " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n", + " if plot_training:\n", + " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", label=\"Iris-Setosa\")\n", + " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", label=\"Iris-Versicolor\")\n", + " plt.plot(X[:, 0][y==2], X[:, 1][y==2], \"g^\", label=\"Iris-Virginica\")\n", + " plt.axis(axes)\n", + " if iris:\n", + " plt.xlabel(\"Petal length\", fontsize=14)\n", + " plt.ylabel(\"Petal width\", fontsize=14)\n", + " else:\n", + " plt.xlabel(r\"$x_1$\", fontsize=18)\n", + " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n", + " if legend:\n", + " plt.legend(loc=\"lower right\", fontsize=14)\n", + "plt.figure(figsize=(11, 4))\n", + "plt.subplot(121)\n", + "plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n", + "plt.title(\"No restrictions\", fontsize=16)\n", + "plt.subplot(122)\n", + "plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n", + "plt.title(\"min_samples_leaf = {}\".format(deep_tree_clf2.min_samples_leaf), fontsize=14)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Playing around with regions" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.random.seed(6)\n", + "Xs = np.random.rand(100, 2) - 0.5\n", + "ys = (Xs[:, 0] > 0).astype(np.float32) * 2\n", + "\n", + "angle = np.pi/4\n", + "rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n", + "Xsr = Xs.dot(rotation_matrix)\n", + "\n", + "tree_clf_s = DecisionTreeClassifier(random_state=42)\n", + "tree_clf_s.fit(Xs, ys)\n", + "tree_clf_sr = DecisionTreeClassifier(random_state=42)\n", + "tree_clf_sr.fit(Xsr, ys)\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "plt.subplot(121)\n", + "plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n", + "plt.subplot(122)\n", + "plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Regression trees" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Quadratic training set + noise\n", + "np.random.seed(42)\n", + "m = 200\n", + "X = np.random.rand(m, 1)\n", + "y = 4 * (X - 0.5) ** 2\n", + "y = y + np.random.randn(m, 1) / 10" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n", + "tree_reg.fit(X, y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Final regressor code" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n", + "tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n", + "tree_reg1.fit(X, y)\n", + "tree_reg2.fit(X, y)\n", + "\n", + "def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n", + " x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n", + " y_pred = tree_reg.predict(x1)\n", + " plt.axis(axes)\n", + " plt.xlabel(\"$x_1$\", fontsize=18)\n", + " if ylabel:\n", + " plt.ylabel(ylabel, fontsize=18, rotation=0)\n", + " plt.plot(X, y, \"b.\")\n", + " plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "plt.subplot(121)\n", + "plot_regression_predictions(tree_reg1, X, y)\n", + "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n", + " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n", + "plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n", + "plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n", + "plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n", + "plt.legend(loc=\"upper center\", fontsize=18)\n", + "plt.title(\"max_depth=2\", fontsize=14)\n", + "\n", + "plt.subplot(122)\n", + "plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n", + "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n", + " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n", + "for split in (0.0458, 0.1298, 0.2873, 0.9040):\n", + " plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n", + "plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n", + "plt.title(\"max_depth=3\", fontsize=14)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "tree_reg1 = DecisionTreeRegressor(random_state=42)\n", + "tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n", + "tree_reg1.fit(X, y)\n", + "tree_reg2.fit(X, y)\n", + "\n", + "x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n", + "y_pred1 = tree_reg1.predict(x1)\n", + "y_pred2 = tree_reg2.predict(x1)\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plt.plot(X, y, \"b.\")\n", + "plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", + "plt.axis([0, 1, -0.2, 1.1])\n", + "plt.xlabel(\"$x_1$\", fontsize=18)\n", + "plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n", + "plt.legend(loc=\"upper center\", fontsize=18)\n", + "plt.title(\"No restrictions\", fontsize=14)\n", + "\n", + "plt.subplot(122)\n", + "plt.plot(X, y, \"b.\")\n", + "plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", + "plt.axis([0, 1, -0.2, 1.1])\n", + "plt.xlabel(\"$x_1$\", fontsize=18)\n", + "plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Pros and cons of trees, pros\n", + "\n", + "* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)\n", + "\n", + "* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n", + "\n", + "* No feature normalization needed\n", + "\n", + "* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n", + "\n", + "* Can model nonlinear relationships\n", + "\n", + "* Can model interactions between the different descriptive features\n", + "\n", + "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)\n", + "\n", + "## Disadvantages\n", + "\n", + "* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n", + "\n", + "* If continuous features are used the tree may become quite large and hence less interpretable\n", + "\n", + "* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented\n", + "\n", + "* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests\n", + "\n", + "* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. \n", + "\n", + "* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n", + "\n", + "* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain\n", + "\n", + "However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved. \n", + "\n", + "\n", + "## Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n", + "\n", + "As stated above and seen in many of the examples discussed here about\n", + "a single decision tree, we often end up overfitting our training\n", + "data. This normally means that we have a high variance. Can we reduce\n", + "the variance of a statistical learning method?\n", + "\n", + "This leads us to a set of different methods that can combine different\n", + "machine learning algorithms or just use one of them to construct forests and jungles of trees, homogeneous ones or heterogenous ones. These methods are recognized by different names which we will try to explain here. These are\n", + "1. Voting classifiers\n", + "\n", + "2. Bagging and Pasting\n", + "\n", + "3. Random forests\n", + "\n", + "4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n", + "\n", + "We discuss these methods here.\n", + "\n", + "\n", + "## An Overview of Ensemble Methods\n", + "\n", + "\n", + "\n", + "\n", + "

    \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Bagging\n", + "\n", + "The **plain** decision trees suffer from high\n", + "variance. This means that if we split the training data into two parts\n", + "at random, and fit a decision tree to both halves, the results that we\n", + "get could be quite different. In contrast, a procedure with low\n", + "variance will yield similar results if applied repeatedly to distinct\n", + "data sets; linear regression tends to have low variance, if the ratio\n", + "of $n$ to $p$ is moderately large. \n", + "\n", + "**Bootstrap aggregation**, or just **bagging**, is a\n", + "general-purpose procedure for reducing the variance of a statistical\n", + "learning method. \n", + "\n", + "\n", + "## More bagging\n", + "\n", + "Bagging typically results in improved accuracy\n", + "over prediction using a single tree. Unfortunately, however, it can be\n", + "difficult to interpret the resulting model. Recall that one of the\n", + "advantages of decision trees is the attractive and easily interpreted\n", + "diagram that results.\n", + "\n", + "However, when we bag a large number of trees, it is no longer\n", + "possible to represent the resulting statistical learning procedure\n", + "using a single tree, and it is no longer clear which variables are\n", + "most important to the procedure. Thus, bagging improves prediction\n", + "accuracy at the expense of interpretability. Although the collection\n", + "of bagged trees is much more difficult to interpret than a single\n", + "tree, one can obtain an overall summary of the importance of each\n", + "predictor using the MSE (for bagging regression trees) or the Gini\n", + "index (for bagging classification trees). In the case of bagging\n", + "regression trees, we can record the total amount that the MSE is\n", + "decreased due to splits over a given predictor, averaged over all $B$ possible\n", + "trees. A large value indicates an important predictor. Similarly, in\n", + "the context of bagging classification trees, we can add up the total\n", + "amount that the Gini index is decreased by splits over a given\n", + "predictor, averaged over all $B$ trees.\n", + "\n", + "## Simple Voting Example, head or tail" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "heads_proba = 0.51\n", + "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n", + "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n", + "plt.figure(figsize=(8,3.5))\n", + "plt.plot(cumulative_heads_ratio)\n", + "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n", + "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n", + "plt.xlabel(\"Number of coin tosses\")\n", + "plt.ylabel(\"Heads ratio\")\n", + "plt.legend(loc=\"lower right\")\n", + "plt.axis([0, 10000, 0.42, 0.58])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using the Voting Classifier" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "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", + "\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": 16, + "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": 17, + "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": 18, + "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": 19, + "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": [ + "## Now Bagging" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.ensemble import BaggingClassifier\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "\n", + "bag_clf = BaggingClassifier(\n", + " DecisionTreeClassifier(random_state=42), n_estimators=500,\n", + " max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)\n", + "bag_clf.fit(X_train, y_train)\n", + "y_pred = bag_clf.predict(X_test)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.metrics import accuracy_score\n", + "print(accuracy_score(y_test, y_pred))" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "tree_clf = DecisionTreeClassifier(random_state=42)\n", + "tree_clf.fit(X_train, y_train)\n", + "y_pred_tree = tree_clf.predict(X_test)\n", + "print(accuracy_score(y_test, y_pred_tree))" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from matplotlib.colors import ListedColormap\n", + "\n", + "def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):\n", + " x1s = np.linspace(axes[0], axes[1], 100)\n", + " x2s = np.linspace(axes[2], axes[3], 100)\n", + " x1, x2 = np.meshgrid(x1s, x2s)\n", + " X_new = np.c_[x1.ravel(), x2.ravel()]\n", + " y_pred = clf.predict(X_new).reshape(x1.shape)\n", + " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n", + " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n", + " if contour:\n", + " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n", + " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n", + " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=alpha)\n", + " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=alpha)\n", + " plt.axis(axes)\n", + " plt.xlabel(r\"$x_1$\", fontsize=18)\n", + " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n", + "plt.figure(figsize=(11,4))\n", + "plt.subplot(121)\n", + "plot_decision_boundary(tree_clf, X, y)\n", + "plt.title(\"Decision Tree\", fontsize=14)\n", + "plt.subplot(122)\n", + "plot_decision_boundary(bag_clf, X, y)\n", + "plt.title(\"Decision Trees with Bagging\", fontsize=14)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Making our own Bagging with Bootstrap" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "\n", + "np.random.seed(2018)\n", + "\n", + "n = 40\n", + "n_boostraps = 100\n", + "maxdegree = 14\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "error = np.zeros(maxdegree)\n", + "bias = np.zeros(maxdegree)\n", + "variance = np.zeros(maxdegree)\n", + "polydegree = np.zeros(maxdegree)\n", + "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "for degree in range(maxdegree):\n", + " model = DecisionTreeRegressor(max_depth=5) \n", + " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", + " for i in range(n_boostraps):\n", + " x_, y_ = resample(X_train_scaled, y_train)\n", + " model.fit(x_, y_)\n", + " y_pred[:, i] = model.predict(X_test_scaled).ravel()\n", + "\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", + " print('Polynomial degree:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "plt.plot(polydegree, error, label='Error')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Changing the Level of the Decision Tree" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "n = 100\n", + "n_boostraps = 100\n", + "maxdepth = 8\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "error = np.zeros(maxdepth)\n", + "bias = np.zeros(maxdepth)\n", + "variance = np.zeros(maxdepth)\n", + "polydegree = np.zeros(maxdepth)\n", + "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "for degree in range(1,maxdepth):\n", + " model = DecisionTreeRegressor(max_depth=degree) \n", + " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", + " for i in range(n_boostraps):\n", + " x_, y_ = resample(X_train_scaled, y_train)\n", + " model.fit(x_, y_)\n", + " y_pred[:, i] = model.predict(X_test_scaled)#.ravel()\n", + "\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", + " print('Polynomial degree:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "plt.xlim(1,maxdepth)\n", + "plt.plot(polydegree, error, label='Error')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Random forests\n", + "\n", + "Random forests provide an improvement over bagged trees by way of a\n", + "small tweak that decorrelates the trees. \n", + "\n", + "As in bagging, we build a\n", + "number of decision trees on bootstrapped training samples. But when\n", + "building these decision trees, each time a split in a tree is\n", + "considered, a random sample of $m$ predictors is chosen as split\n", + "candidates from the full set of $p$ predictors. The split is allowed to\n", + "use only one of those $m$ predictors. \n", + "\n", + "A fresh sample of $m$ predictors is\n", + "taken at each split, and typically we choose" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "m\\approx \\sqrt{p}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In building a random forest, at\n", + "each split in the tree, the algorithm is not even allowed to consider\n", + "a majority of the available predictors. \n", + "\n", + "The reason for this is rather clever. Suppose that there is one very\n", + "strong predictor in the data set, along with a number of other\n", + "moderately strong predictors. Then in the collection of bagged\n", + "variable importance random forest trees, most or all of the trees will\n", + "use this strong predictor in the top split. Consequently, all of the\n", + "bagged trees will look quite similar to each other. Hence the\n", + "predictions from the bagged trees will be highly correlated.\n", + "Unfortunately, averaging many highly correlated quantities does not\n", + "lead to as large of a reduction in variance as averaging many\n", + "uncorrelated quanti- ties. In particular, this means that bagging will\n", + "not lead to a substantial reduction in variance over a single tree in\n", + "this setting.\n", + "\n", + "\n", + "## Random Forest Algorithm\n", + "The algorithm described here can be applied to both classification and regression problems.\n", + "\n", + "We will grow of forest of say $M$ trees.\n", + "1. For $m=1:M$ we\n", + "\n", + " * Draw a bootstrap sample of from the training data organized in our $\\boldsymbol{X}$ matrix.\n", + "\n", + " * We grow then a random forest tree $T_m$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached\n", + "\n", + "1. we select $m \\le p$ varibales at random from the $p$ predictors/features\n", + "\n", + "2. pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node\n", + "\n", + "3. split the node into daughter nodes\n", + "\n", + "\n", + "\n", + "4. Output then the ensemble of trees $\\{T_m\\}_1^{M}$ and make predictions for either a regression type of problem or a classification type of problem. \n", + "\n", + "## Bootstrap with Random Forests Instead of a Single Tree, own Bagging" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "np.random.seed(2018)\n", + "\n", + "n = 100\n", + "n_boostraps = 100\n", + "maxdegree = 14\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "error = np.zeros(maxdegree)\n", + "bias = np.zeros(maxdegree)\n", + "variance = np.zeros(maxdegree)\n", + "polydegree = np.zeros(maxdegree)\n", + "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "for degree in range(maxdegree):\n", + " model = RandomForestRegressor()\n", + " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", + " for i in range(n_boostraps):\n", + " x_, y_ = resample(X_train_scaled, y_train)\n", + " model.fit(x_, y_.ravel())\n", + " y_pred[:, i] = model.predict(X_test_scaled).ravel()\n", + "\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", + " print('Polynomial degree:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "plt.plot(polydegree, error, label='Error')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Random Forests Compared with other Methods on the Cancer Data" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.svm import SVC\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "\n", + "# Load the data\n", + "cancer = load_breast_cancer()\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "# Logistic Regression\n", + "logreg = LogisticRegression(solver='lbfgs')\n", + "logreg.fit(X_train, y_train)\n", + "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", + "# Support vector machine\n", + "svm = SVC(gamma='auto', C=100)\n", + "svm.fit(X_train, y_train)\n", + "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n", + "# Decision Trees\n", + "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n", + "deep_tree_clf.fit(X_train, y_train)\n", + "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n", + "#now scale the data\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "# Logistic Regression\n", + "logreg.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", + "# Support Vector Machine\n", + "svm.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", + "# Decision Trees\n", + "deep_tree_clf.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))\n", + "\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.model_selection import cross_validate\n", + "# Data set not specificied\n", + "#Instantiate the model with 500 trees and entropy as splitting criteria\n", + "Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion=\"entropy\")\n", + "Random_Forest_model.fit(X_train_scaled, y_train)\n", + "#Cross validation\n", + "accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']\n", + "print(accuracy)\n", + "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(Random_Forest_model.score(X_test_scaled,y_test)))\n", + "\n", + "\n", + "import scikitplot as skplt\n", + "y_pred = Random_Forest_model.predict(X_test_scaled)\n", + "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", + "plt.show()\n", + "y_probas = Random_Forest_model.predict_proba(X_test_scaled)\n", + "skplt.metrics.plot_roc(y_test, y_probas)\n", + "plt.show()\n", + "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Compare Bagging on Trees with Random Forests" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "bag_clf = BaggingClassifier(\n", + " DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n", + " n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "bag_clf.fit(X_train, y_train)\n", + "y_pred = bag_clf.predict(X_test)\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)\n", + "rnd_clf.fit(X_train, y_train)\n", + "y_pred_rf = rnd_clf.predict(X_test)\n", + "np.sum(y_pred == y_pred_rf) / len(y_pred)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Boosting, a Bird'e Eye\n", + "\n", + "The basic idea is to combine weak classifiers in order to create a good\n", + "classifier. With a weak classifier we often intend a classifier which\n", + "produces results which are only slightly better than we would get by\n", + "random guesses.\n", + "\n", + "This is done by applying in an iterative way a weak (or a standard\n", + "classifier like decision trees) to modify the data. In each iteration\n", + "we emphasize those observations which are misclassified by weighting\n", + "them with a factor.\n", + "\n", + "\n", + "## Adaptive boosting: AdaBoost, Basic Algorithm\n", + "\n", + "The algorithm here is rather straightforward. Assume that our weak\n", + "classifier is a decision tree and we consider a binary set of outputs\n", + "with $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n", + "observations. Our design matrix is given in terms of the\n", + "feature/predictor vectors\n", + "$\\boldsymbol{X}=[\\boldsymbol{x}_0\\boldsymbol{x}_1\\dots\\boldsymbol{x}_{p-1}$. Finally, we define also a\n", + "classifier determined by our data via a function $G(\\boldsymbol{X})$. This function tells us how well we are able to classify our outputs/targets $\\boldsymbol{y}$. \n", + "\n", + "We can then define the misclassification error $\\mathrm{err}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(\\boldsymbol{X}_{i*}),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the function $I()$ is one if we misclassify and zero if we classify correctly. \n", + "\n", + "## Basic Steps of AdaBoost\n", + "\n", + "With the above definitions we are now ready to set up the algorithm for AdaBoost.\n", + "The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.\n", + "1. We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\\dots n-1$. It is to see then that $\\sum_{i=0}^{n-1}w_i = 1$.\n", + "\n", + "2. We rewrite the misclassification error as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{err}=\\frac{\\sum_{i=0}^{n-1}w_iI(y_i\\ne G(\\boldsymbol{X}_{i*})}{\\sum_{i=0}^{n-1}w_i},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.\n", + "\n", + "a. Fit then a given classifier to the training using the weights $w_i$.\n", + "\n", + "b. Compute then $\\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.\n", + "\n", + "c. Define a quantity $\\alpha_{m} = \\log{(1-\\mathrm{err})/\\mathrm{err}}\n", + "\n", + "d. Set the new weights to $w_i = w_i\\times \\exp{(\\alpha_m I(y_i\\ne G(\\boldsymbol{X}_{i*})}.\n", + "\n", + "\n", + "5. Compute the new classifier $G(\\boldsymbol{X})= \\sum_{i=0}^{n-1}\\alpha_m I(y_i\\ne G(\\boldsymbol{X}_{i*}).\n", + "\n", + "For the iterations with $m \\le 2$ the weights are modified\n", + "individually at each steps. The obersvations which were misclassified\n", + "at iteration $m-1$ have a weight which is larger than those which were\n", + "classified properly. As this proceeds, the observations which were\n", + "difficult to classifiy correctly are given a larger influence. Each\n", + "new classification step $m$ is then forced to concentrate on those\n", + "observations that are missed in the previous iterations.\n", + "\n", + "\n", + "\n", + "## AdaBoost Examples\n", + "\n", + "Using **Scikit-Learn** it is easy to appply the adaptive boosting algorithm, as done here." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.ensemble import AdaBoostClassifier\n", + "\n", + "ada_clf = AdaBoostClassifier(\n", + " DecisionTreeClassifier(max_depth=1), n_estimators=200,\n", + " algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n", + "ada_clf.fit(X_train, y_train)\n", + "\n", + "plot_decision_boundary(ada_clf, X, y)\n", + "\n", + "m = len(X_train)\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "for subplot, learning_rate in ((121, 1), (122, 0.5)):\n", + " sample_weights = np.ones(m)\n", + " plt.subplot(subplot)\n", + " for i in range(5):\n", + " svm_clf = SVC(kernel=\"rbf\", C=0.05, gamma=\"auto\", random_state=42)\n", + " svm_clf.fit(X_train, y_train, sample_weight=sample_weights)\n", + " y_pred = svm_clf.predict(X_train)\n", + " sample_weights[y_pred != y_train] *= (1 + learning_rate)\n", + " plot_decision_boundary(svm_clf, X, y, alpha=0.2)\n", + " plt.title(\"learning_rate = {}\".format(learning_rate), fontsize=16)\n", + " if subplot == 121:\n", + " plt.text(-0.7, -0.65, \"1\", fontsize=14)\n", + " plt.text(-0.6, -0.10, \"2\", fontsize=14)\n", + " plt.text(-0.5, 0.10, \"3\", fontsize=14)\n", + " plt.text(-0.4, 0.55, \"4\", fontsize=14)\n", + " plt.text(-0.3, 0.90, \"5\", fontsize=14)\n", + "\n", + "save_fig(\"boosting_plot\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Gradient boosting: Basics\n", + "\n", + "Gradient boosting is again a similar technique to Adapative boosting,\n", + "it combines so-called weak classifiers or regressors into a strong\n", + "method via a series of iterations.\n", + "\n", + "In order to understand the method, let us illustrate its basics by\n", + "bringing back the essential steps in linear regression, where our cost\n", + "function was the least squares function.\n", + "\n", + "## Gradient Boosting, algorithm\n", + "\n", + "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 least squares function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{y},\\boldsymbol{f})=\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The way we proceed in an iterative fashion is to\n", + "1. Initialize our estimate by $f_0(x)=0$.\n", + "\n", + "2. For $m=1:M$, we\n", + "\n", + "a. 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);\n", + "\n", + "b. fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;\n", + "\n", + "c. update the estimate $f_m(x) = f_{m-1}(x)+\\nu h_m(u_m,x)$;\n", + "\n", + "\n", + "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M\\nu h_m(u_m,x)$.\n", + "\n", + "## Gradient Boosting, Examples" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.random.seed(42)\n", + "X = np.random.rand(100, 1) - 0.5\n", + "y = 3*X[:, 0]**2 + 0.05 * np.random.randn(100)\n", + "\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "tree_reg1 = DecisionTreeRegressor(max_depth=2, random_state=42)\n", + "tree_reg1.fit(X, y)\n", + "\n", + "y2 = y - tree_reg1.predict(X)\n", + "tree_reg2 = DecisionTreeRegressor(max_depth=2, random_state=42)\n", + "tree_reg2.fit(X, y2)\n", + "\n", + "y3 = y2 - tree_reg2.predict(X)\n", + "tree_reg3 = DecisionTreeRegressor(max_depth=2, random_state=42)\n", + "tree_reg3.fit(X, y3)\n", + "\n", + "X_new = np.array([[0.8]])\n", + "y_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3))\n", + "\n", + "def plot_predictions(regressors, X, y, axes, label=None, style=\"r-\", data_style=\"b.\", data_label=None):\n", + " x1 = np.linspace(axes[0], axes[1], 500)\n", + " y_pred = sum(regressor.predict(x1.reshape(-1, 1)) for regressor in regressors)\n", + " plt.plot(X[:, 0], y, data_style, label=data_label)\n", + " plt.plot(x1, y_pred, style, linewidth=2, label=label)\n", + " if label or data_label:\n", + " plt.legend(loc=\"upper center\", fontsize=16)\n", + " plt.axis(axes)\n", + "\n", + "plt.figure(figsize=(11,11))\n", + "\n", + "plt.subplot(321)\n", + "plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"$h_1(x_1)$\", style=\"g-\", data_label=\"Training set\")\n", + "plt.ylabel(\"$y$\", fontsize=16, rotation=0)\n", + "plt.title(\"Residuals and tree predictions\", fontsize=16)\n", + "\n", + "plt.subplot(322)\n", + "plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"$h(x_1) = h_1(x_1)$\", data_label=\"Training set\")\n", + "plt.ylabel(\"$y$\", fontsize=16, rotation=0)\n", + "plt.title(\"Ensemble predictions\", fontsize=16)\n", + "\n", + "plt.subplot(323)\n", + "plot_predictions([tree_reg2], X, y2, axes=[-0.5, 0.5, -0.5, 0.5], label=\"$h_2(x_1)$\", style=\"g-\", data_style=\"k+\", data_label=\"Residuals\")\n", + "plt.ylabel(\"$y - h_1(x_1)$\", fontsize=16)\n", + "\n", + "plt.subplot(324)\n", + "plot_predictions([tree_reg1, tree_reg2], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"$h(x_1) = h_1(x_1) + h_2(x_1)$\")\n", + "plt.ylabel(\"$y$\", fontsize=16, rotation=0)\n", + "\n", + "plt.subplot(325)\n", + "plot_predictions([tree_reg3], X, y3, axes=[-0.5, 0.5, -0.5, 0.5], label=\"$h_3(x_1)$\", style=\"g-\", data_style=\"k+\")\n", + "plt.ylabel(\"$y - h_1(x_1) - h_2(x_1)$\", fontsize=16)\n", + "plt.xlabel(\"$x_1$\", fontsize=16)\n", + "\n", + "plt.subplot(326)\n", + "plot_predictions([tree_reg1, tree_reg2, tree_reg3], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"$h(x_1) = h_1(x_1) + h_2(x_1) + h_3(x_1)$\")\n", + "plt.xlabel(\"$x_1$\", fontsize=16)\n", + "plt.ylabel(\"$y$\", fontsize=16, rotation=0)\n", + "\n", + "save_fig(\"gradient_boosting_plot\")\n", + "plt.show()\n", + "\n", + "from sklearn.ensemble import GradientBoostingRegressor\n", + "\n", + "gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0, random_state=42)\n", + "gbrt.fit(X, y)\n", + "\n", + "gbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42)\n", + "gbrt_slow.fit(X, y)\n", + "\n", + "plt.figure(figsize=(11,4))\n", + "\n", + "plt.subplot(121)\n", + "plot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"Ensemble predictions\")\n", + "plt.title(\"learning_rate={}, n_estimators={}\".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14)\n", + "\n", + "plt.subplot(122)\n", + "plot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8])\n", + "plt.title(\"learning_rate={}, n_estimators={}\".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14)\n", + "\n", + "save_fig(\"gbrt_learning_rate_plot\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Gradient Boots with Early Stopping" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=49)\n", + "\n", + "gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120, random_state=42)\n", + "gbrt.fit(X_train, y_train)\n", + "\n", + "errors = [mean_squared_error(y_val, y_pred)\n", + " for y_pred in gbrt.staged_predict(X_val)]\n", + "bst_n_estimators = np.argmin(errors) + 1\n", + "\n", + "gbrt_best = GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators, random_state=42)\n", + "gbrt_best.fit(X_train, y_train)\n", + "\n", + "min_error = np.min(errors)\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plt.plot(errors, \"b.-\")\n", + "plt.plot([bst_n_estimators, bst_n_estimators], [0, min_error], \"k--\")\n", + "plt.plot([0, 120], [min_error, min_error], \"k--\")\n", + "plt.plot(bst_n_estimators, min_error, \"ko\")\n", + "plt.text(bst_n_estimators, min_error*1.2, \"Minimum\", ha=\"center\", fontsize=14)\n", + "plt.axis([0, 120, 0, 0.01])\n", + "plt.xlabel(\"Number of trees\")\n", + "plt.title(\"Validation error\", fontsize=14)\n", + "\n", + "plt.subplot(122)\n", + "plot_predictions([gbrt_best], X, y, axes=[-0.5, 0.5, -0.1, 0.8])\n", + "plt.title(\"Best model (%d trees)\" % bst_n_estimators, fontsize=14)\n", + "\n", + "save_fig(\"early_stopping_gbrt_plot\")\n", + "plt.show()\n", + "\n", + "\n", + "gbrt = GradientBoostingRegressor(max_depth=2, warm_start=True, random_state=42)\n", + "\n", + "min_val_error = float(\"inf\")\n", + "error_going_up = 0\n", + "for n_estimators in range(1, 120):\n", + " gbrt.n_estimators = n_estimators\n", + " gbrt.fit(X_train, y_train)\n", + " y_pred = gbrt.predict(X_val)\n", + " val_error = mean_squared_error(y_val, y_pred)\n", + " if val_error < min_val_error:\n", + " min_val_error = val_error\n", + " error_going_up = 0\n", + " else:\n", + " error_going_up += 1\n", + " if error_going_up == 5:\n", + " break # early stopping\n", + "\n", + "\n", + "print(gbrt.n_estimators)\n", + "print(\"Minimum validation MSE:\", min_val_error)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## XGBoost: Extreme Gradient Boosting\n", + "\n", + "\n", + "[XGBoost](https://github.com/dmlc/xgboost) or Extreme Gradient\n", + "Boosting, is an optimized distributed gradient boosting library\n", + "designed to be highly efficient, flexible and portable. It implements\n", + "machine learning algorithms under the Gradient Boosting\n", + "framework. XGBoost provides a parallel tree boosting that solve many\n", + "data science problems in a fast and accurate way. See the [article by Chen and Guestrin](https://arxiv.org/abs/1603.02754).\n", + "\n", + "The authors design and build a highly scalable end-to-end tree\n", + "boosting system. It has a theoretically justified weighted quantile\n", + "sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.\n", + "\n", + "It is now the algorithm which wins essentially all ML competitions!!!\n", + "\n", + "## Regression Case" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "import xgboost as xgb\n", + "from sklearn.preprocessing import StandardScaler\n", + "import scikitplot as skplt\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "n = 100\n", + "maxdegree = 6\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "\n", + "error = np.zeros(maxdegree)\n", + "bias = np.zeros(maxdegree)\n", + "variance = np.zeros(maxdegree)\n", + "polydegree = np.zeros(maxdegree)\n", + "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "for degree in range(maxdegree):\n", + " model = xgb.XGBRegressor(objective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,\n", + " max_depth = degree, alpha = 10, n_estimators = 10)\n", + " model.fit(X_train_scaled,y_train)\n", + " y_pred = model.predict(X_test_scaled)\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred) )\n", + " print('Max depth:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "plt.xlim(1,maxdegree-1)\n", + "plt.plot(polydegree, error, label='Error')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Xgboost on the Cancer Data" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.model_selection import cross_validate\n", + "import scikitplot as skplt\n", + "import xgboost as xgb\n", + "# Load the data\n", + "cancer = load_breast_cancer()\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "#now scale the data\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "xg_clf = xgb.XGBClassifier()\n", + "xg_clf.fit(X_train_scaled,y_train)\n", + "xgb.plot_tree(xg_clf,num_trees=0)\n", + "plt.rcParams['figure.figsize'] = [50, 10]\n", + "plt.show()\n", + "xgb.plot_importance(xg_clf)\n", + "plt.rcParams['figure.figsize'] = [5, 5]\n", + "plt.show()" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/src/DecisionTrees/DecisionTrees.p.tex b/doc/src/DecisionTrees/DecisionTrees.p.tex new file mode 100644 index 000000000..1005fdb09 --- /dev/null +++ b/doc/src/DecisionTrees/DecisionTrees.p.tex @@ -0,0 +1,2425 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/hplgit/doconce/) +%% +%% +% #ifdef PTEX2TEX_EXPLANATION +%% +%% The file follows the ptex2tex extended LaTeX format, see +%% ptex2tex: http://code.google.com/p/ptex2tex/ +%% +%% Run +%% ptex2tex myfile +%% or +%% doconce ptex2tex myfile +%% +%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex. +%% (The ptex2tex program: http://code.google.com/p/ptex2tex) +%% Many preprocess options can be added to ptex2tex or doconce ptex2tex +%% +%% ptex2tex -DMINTED myfile +%% doconce ptex2tex myfile envir=minted +%% +%% ptex2tex will typeset code environments according to a global or local +%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code +%% according to options on the command line (just type doconce ptex2tex to +%% see examples). If doconce ptex2tex has envir=minted, it enables the +%% minted style without needing -DMINTED. +% #endif + +% #define PREAMBLE + +% #ifdef PREAMBLE +%-------------------- begin preamble ---------------------- + +\documentclass[% +oneside, % oneside: electronic viewing, twoside: printing +final, % draft: marks overfull hboxes, figures with paths +10pt]{article} + +\listfiles % print all files needed to compile this document + +\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} +\usepackage[table]{xcolor} +\usepackage{bm,ltablex,microtype} + +\usepackage[pdftex]{graphicx} + +\usepackage{ptex2tex} +% #ifdef MINTED +\usepackage{minted} +\usemintedstyle{default} +% #endif + +\usepackage[T1]{fontenc} +%\usepackage[latin1]{inputenc} +\usepackage{ucs} +\usepackage[utf8x]{inputenc} + +\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern + +% Hyperlinks in PDF: +\definecolor{linkcolor}{rgb}{0,0,0.4} +\usepackage{hyperref} +\hypersetup{ + breaklinks=true, + colorlinks=true, + linkcolor=linkcolor, + urlcolor=linkcolor, + citecolor=black, + filecolor=black, + %filecolor=blue, + pdfmenubar=true, + pdftoolbar=true, + bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC + } +%\hyperbaseurl{} % hyperlinks are relative to this root + +\setcounter{tocdepth}{2} % levels in table of contents + +% Tricks for having figures close to where they are defined: +% 1. define less restrictive rules for where to put figures +\setcounter{topnumber}{2} +\setcounter{bottomnumber}{2} +\setcounter{totalnumber}{4} +\renewcommand{\topfraction}{0.95} +\renewcommand{\bottomfraction}{0.95} +\renewcommand{\textfraction}{0} +\renewcommand{\floatpagefraction}{0.75} +% floatpagefraction must always be less than topfraction! +% 2. ensure all figures are flushed before next section +\usepackage[section]{placeins} +% 3. enable begin{figure}[H] (often leads to ugly pagebreaks) +%\usepackage{float}\restylefloat{figure} + +% --- fancyhdr package for fancy headers --- +\usepackage{fancyhdr} +\fancyhf{} % sets both header and footer to nothing +\renewcommand{\headrulewidth}{0pt} +\fancyfoot[LE,RO]{\thepage} +% Ensure copyright on titlepage (article style) and chapter pages (book style) +\fancypagestyle{plain}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} +% \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} +% Ensure copyright on titlepages with \thispagestyle{empty} +\fancypagestyle{empty}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} + \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} + +\pagestyle{fancy} + + +\usepackage[framemethod=TikZ]{mdframed} + +% --- begin definitions of admonition environments --- + +% --- end of definitions of admonition environments --- + +% prevent orhpans and widows +\clubpenalty = 10000 +\widowpenalty = 10000 + +% --- end of standard preamble for documents --- + + +% insert custom LaTeX commands... + +\raggedbottom +\makeindex +\usepackage[totoc]{idxlayout} % for index in the toc +\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc + +%-------------------- end preamble ---------------------- + +\begin{document} + +% matching end for #ifdef PREAMBLE +% #endif + +\newcommand{\exercisesection}[1]{\subsection*{#1}} + + +% ------------------- main content ---------------------- + + + +% ----------------- title ------------------------- + +\thispagestyle{empty} + +\begin{center} +{\LARGE\bf +\begin{spacing}{1.25} +Data Analysis and Machine Learning: From Decision Trees to Forests and all that +\end{spacing} +} +\end{center} + +% ----------------- author(s) ------------------------- + +\begin{center} +{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] +\end{center} + +\begin{center} +% List of all institutions: +\centerline{{\small ${}^1$Department of Physics, University of Oslo}} +\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} +\end{center} + +% ----------------- end author(s) ------------------------- + +% --- begin date --- +\begin{center} +Nov 7, 2019 +\end{center} +% --- end date --- + +\vspace{1cm} + + +% !split +\subsection{Decision trees, overarching aims} + + +Decision trees are supervised learning algorithms used for both, +classification and regression tasks. + + +The main idea of decision trees +is to find those descriptive features which contain the most +\textbf{information} regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. + +The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the \textbf{most +informative} feature is done until we accomplish a stopping criteria +where we then finally end up in so called \textbf{leaf nodes}. + +A decision tree is typically divided into a \textbf{root node}, the \textbf{interior nodes}, +and the final \textbf{leaf nodes} or just \textbf{leaves}. These entities are then connected by so-called \textbf{branches}. + +The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +% !split +\subsection{A typical Decision Tree with its pertinent Jargon, Classification Problem} + + + +\vspace{6mm} + +% inline figure +\centerline{\includegraphics[width=0.8\linewidth]{DataFiles/cancer.png}} + +\vspace{6mm} + + + +This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using \textbf{Scikit-Learn}'s decision tree classifier. Here we have used the so-called \textbf{gini} index (see below) to split the various branches. + + + +% !split +\subsection{General Features} + +The overarching approach to decision trees is a top-down approach. + +\begin{itemize} +\item A leaf provides the classification of a given instance. + +\item A node specifies a test of some attribute of the instance. + +\item A branch corresponds to a possible values of an attribute. + +\item An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example. +\end{itemize} + +\noindent +This process is then repeated for the subtree rooted at the new +node. + + +% !split +\subsection{How do we set it up?} + + +In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: + +\begin{enumerate} +\item Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature + +\item Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process + +\item Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the \emph{predictions} we want to make for new query instances + +\item Show query instances to the tree and run down the tree until we arrive at leaf nodes +\end{enumerate} + +\noindent +Then we are essentially done! + + + + + +% !split +\subsection{Decision trees and Regression} +\bpycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.preprocessing import PolynomialFeatures +from sklearn.linear_model import LinearRegression + +steps=250 + +distance=0 +x=0 +distance_list=[] +steps_list=[] +while x 0 and bestAttrId in attributeIds: + toRemove = attributeIds.index(bestAttrId) + attributeIds.pop(toRemove) + child.next = self.id3Recv( + childSampleIds, attributeIds, child.next) + return root + + def printTree(self): + if self.root: + roots = deque() + roots.append(self.root) + while len(roots) > 0: + root = roots.popleft() + print(root.value) + if root.childs: + for child in root.childs: + print('({})'.format(child.value)) + roots.append(child.next) + elif root.next: + print(root.next) + + +def test(): + f = open('DataFiles/rideclass.csv') + attributes = f.readline().split(',') + attributes = attributes[1:len(attributes)-1] + print(attributes) + sample = f.readlines() + f.close() + for i in range(len(sample)): + sample[i] = re.sub('\d+,', '', sample[i]) + sample[i] = sample[i].strip().split(',') + labels = [] + for s in sample: + labels.append(s.pop()) + # print(sample) + # print(labels) + decisionTree = DecisionTree(sample, attributes, labels) + print("System entropy {}".format(decisionTree.entropy)) + decisionTree.id3() + decisionTree.printTree() + + +if __name__ == '__main__': + test() +\epycod + +% !split +\subsection{Cancer Data again now with Decision Trees and other Methods} +\bpycod +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))) + +\epycod + + +% !split +\subsection{Another example, the moons again} +\bpycod +from __future__ import division, print_function, unicode_literals + +# Common imports +import numpy as np +import os + +# to make this notebook's output stable across runs +np.random.seed(42) + +# To plot pretty figures +import matplotlib +import matplotlib.pyplot as plt +from matplotlib.colors import ListedColormap +plt.rcParams['axes.labelsize'] = 14 +plt.rcParams['xtick.labelsize'] = 12 +plt.rcParams['ytick.labelsize'] = 12 + + +from sklearn.svm import SVC +from sklearn import datasets +from sklearn.tree import DecisionTreeClassifier +from sklearn.datasets import make_moons +from sklearn.tree import export_graphviz + +Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53) + +deep_tree_clf1 = DecisionTreeClassifier(random_state=42) +deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42) +deep_tree_clf1.fit(Xm, ym) +deep_tree_clf2.fit(Xm, ym) + + +def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True): + x1s = np.linspace(axes[0], axes[1], 100) + x2s = np.linspace(axes[2], axes[3], 100) + x1, x2 = np.meshgrid(x1s, x2s) + X_new = np.c_[x1.ravel(), x2.ravel()] + y_pred = clf.predict(X_new).reshape(x1.shape) + custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) + plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) + if not iris: + custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) + plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) + if plot_training: + plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa") + plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor") + plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica") + plt.axis(axes) + if iris: + plt.xlabel("Petal length", fontsize=14) + plt.ylabel("Petal width", fontsize=14) + else: + plt.xlabel(r"$x_1$", fontsize=18) + plt.ylabel(r"$x_2$", fontsize=18, rotation=0) + if legend: + plt.legend(loc="lower right", fontsize=14) +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False) +plt.title("No restrictions", fontsize=16) +plt.subplot(122) +plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False) +plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14) +plt.show() + +\epycod + +% !split +\subsection{Playing around with regions} +\bpycod +np.random.seed(6) +Xs = np.random.rand(100, 2) - 0.5 +ys = (Xs[:, 0] > 0).astype(np.float32) * 2 + +angle = np.pi/4 +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) +Xsr = Xs.dot(rotation_matrix) + +tree_clf_s = DecisionTreeClassifier(random_state=42) +tree_clf_s.fit(Xs, ys) +tree_clf_sr = DecisionTreeClassifier(random_state=42) +tree_clf_sr.fit(Xsr, ys) + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) +plt.subplot(122) +plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) + +plt.show() +\epycod + +% !split +\subsection{Regression trees} +\bpycod +# Quadratic training set + noise +np.random.seed(42) +m = 200 +X = np.random.rand(m, 1) +y = 4 * (X - 0.5) ** 2 +y = y + np.random.randn(m, 1) / 10 +\epycod + +\bpycod +from sklearn.tree import DecisionTreeRegressor + +tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg.fit(X, y) +\epycod + +% !split +\subsection{Final regressor code} +\bpycod +from sklearn.tree import DecisionTreeRegressor + +tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2) +tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"): + x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1) + y_pred = tree_reg.predict(x1) + plt.axis(axes) + plt.xlabel("$x_1$", fontsize=18) + if ylabel: + plt.ylabel(ylabel, fontsize=18, rotation=0) + plt.plot(X, y, "b.") + plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$") + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_regression_predictions(tree_reg1, X, y) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +plt.text(0.21, 0.65, "Depth=0", fontsize=15) +plt.text(0.01, 0.2, "Depth=1", fontsize=13) +plt.text(0.65, 0.8, "Depth=1", fontsize=13) +plt.legend(loc="upper center", fontsize=18) +plt.title("max_depth=2", fontsize=14) + +plt.subplot(122) +plot_regression_predictions(tree_reg2, X, y, ylabel=None) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +for split in (0.0458, 0.1298, 0.2873, 0.9040): + plt.plot([split, split], [-0.2, 1], "k:", linewidth=1) +plt.text(0.3, 0.5, "Depth=2", fontsize=13) +plt.title("max_depth=3", fontsize=14) + +plt.show() +\epycod + +\bpycod +tree_reg1 = DecisionTreeRegressor(random_state=42) +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +x1 = np.linspace(0, 1, 500).reshape(-1, 1) +y_pred1 = tree_reg1.predict(x1) +y_pred2 = tree_reg2.predict(x1) + +plt.figure(figsize=(11, 4)) + +plt.subplot(121) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.ylabel("$y$", fontsize=18, rotation=0) +plt.legend(loc="upper center", fontsize=18) +plt.title("No restrictions", fontsize=14) + +plt.subplot(122) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14) + +plt.show() +\epycod + + + +% !split +\subsection{Pros and cons of trees, pros} + +\begin{itemize} +\item White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines) + +\item Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression! + +\item No feature normalization needed + +\item Tree models can handle both continuous and categorical data (Classification and Regression Trees) + +\item Can model nonlinear relationships + +\item Can model interactions between the different descriptive features + +\item Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small) +\end{itemize} + +\noindent +% !split +\subsection{Disadvantages} + +\begin{itemize} +\item Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches + +\item If continuous features are used the tree may become quite large and hence less interpretable + +\item Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented + +\item Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests + +\item Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. + +\item If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data + +\item Features with many levels may be preferred over features with less levels since for them it is \emph{more easy} to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain +\end{itemize} + +\noindent +However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved. + + +% !split +\subsection{Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods} + +As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct forests and jungles of trees, homogeneous ones or heterogenous ones. These methods are recognized by different names which we will try to explain here. These are +\begin{enumerate} +\item Voting classifiers + +\item Bagging and Pasting + +\item Random forests + +\item Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost) +\end{enumerate} + +\noindent +We discuss these methods here. + + +% !split +\subsection{An Overview of Ensemble Methods} + + + +\vspace{6mm} + +% inline figure +\centerline{\includegraphics[width=0.8\linewidth]{DataFiles/ensembleoverview.png}} + +\vspace{6mm} + + + + + +% !split +\subsection{Bagging} + +The \textbf{plain} decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of $n$ to $p$ is moderately large. + +\textbf{Bootstrap aggregation}, or just \textbf{bagging}, is a +general-purpose procedure for reducing the variance of a statistical +learning method. + + +% !split +\subsection{More bagging} + +Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all $B$ possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all $B$ trees. + +% !split +\subsection{Simple Voting Example, head or tail} +\bpycod +heads_proba = 0.51 +coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32) +cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1) +plt.figure(figsize=(8,3.5)) +plt.plot(cumulative_heads_ratio) +plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%") +plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%") +plt.xlabel("Number of coin tosses") +plt.ylabel("Heads ratio") +plt.legend(loc="lower right") +plt.axis([0, 10000, 0.42, 0.58]) +plt.show() + +\epycod + +% !split +\subsection{Using the Voting Classifier} +\bpycod +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) + +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(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)) + +\epycod + +% !split +\subsection{Please, not the moons again! Voting and Bagging} +\bpycod +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='hard') +voting_clf.fit(X_train, y_train) +\epycod + +\bpycod +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +\epycod + +\bpycod +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(probability=True, random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='soft') +voting_clf.fit(X_train, y_train) +\epycod + +\bpycod +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +\epycod + +% !split +\subsection{Now Bagging} + +\bpycod +from sklearn.ensemble import BaggingClassifier +from sklearn.tree import DecisionTreeClassifier + +bag_clf = BaggingClassifier( + DecisionTreeClassifier(random_state=42), n_estimators=500, + max_samples=100, bootstrap=True, n_jobs=-1, random_state=42) +bag_clf.fit(X_train, y_train) +y_pred = bag_clf.predict(X_test) +\epycod + + +\bpycod +from sklearn.metrics import accuracy_score +print(accuracy_score(y_test, y_pred)) +\epycod + +\bpycod +tree_clf = DecisionTreeClassifier(random_state=42) +tree_clf.fit(X_train, y_train) +y_pred_tree = tree_clf.predict(X_test) +print(accuracy_score(y_test, y_pred_tree)) +\epycod + +\bpycod +from matplotlib.colors import ListedColormap + +def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True): + x1s = np.linspace(axes[0], axes[1], 100) + x2s = np.linspace(axes[2], axes[3], 100) + x1, x2 = np.meshgrid(x1s, x2s) + X_new = np.c_[x1.ravel(), x2.ravel()] + y_pred = clf.predict(X_new).reshape(x1.shape) + custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) + plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) + if contour: + custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) + plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) + plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha) + plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha) + plt.axis(axes) + plt.xlabel(r"$x_1$", fontsize=18) + plt.ylabel(r"$x_2$", fontsize=18, rotation=0) +plt.figure(figsize=(11,4)) +plt.subplot(121) +plot_decision_boundary(tree_clf, X, y) +plt.title("Decision Tree", fontsize=14) +plt.subplot(122) +plot_decision_boundary(bag_clf, X, y) +plt.title("Decision Trees with Bagging", fontsize=14) +plt.show() +\epycod + + +% !split +\subsection{Making our own Bagging with Bootstrap} +\bpycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.tree import DecisionTreeRegressor + + +np.random.seed(2018) + +n = 40 +n_boostraps = 100 +maxdegree = 14 + +# 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) + +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) + +for degree in range(maxdegree): + model = DecisionTreeRegressor(max_depth=5) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_) + y_pred[:, i] = model.predict(X_test_scaled).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + +\epycod + + +% !split +\subsection{Changing the Level of the Decision Tree} + +\bpycod + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.tree import DecisionTreeRegressor + +n = 100 +n_boostraps = 100 +maxdepth = 8 + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +error = np.zeros(maxdepth) +bias = np.zeros(maxdepth) +variance = np.zeros(maxdepth) +polydegree = np.zeros(maxdepth) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +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) + +for degree in range(1,maxdepth): + model = DecisionTreeRegressor(max_depth=degree) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_) + y_pred[:, i] = model.predict(X_test_scaled)#.ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.xlim(1,maxdepth) +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + + +\epycod + + + + +% !split +\subsection{Random forests} + +Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. + +As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of $m$ predictors is chosen as split +candidates from the full set of $p$ predictors. The split is allowed to +use only one of those $m$ predictors. + +A fresh sample of $m$ predictors is +taken at each split, and typically we choose + +\[ +m\approx \sqrt{p}. +\] + +In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. + +The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quanti- ties. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. + + +% !split +\subsection{Random Forest Algorithm} +The algorithm described here can be applied to both classification and regression problems. + +We will grow of forest of say $M$ trees. +\begin{enumerate} +\item For $m=1:M$ we +\begin{itemize} + + \item Draw a bootstrap sample of from the training data organized in our $\bm{X}$ matrix. + + \item We grow then a random forest tree $T_m$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached +\begin{enumerate} + + \item we select $m \le p$ varibales at random from the $p$ predictors/features + + \item pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node + + \item split the node into daughter nodes + +\end{enumerate} + +\noindent +\end{itemize} + +\noindent +\item Output then the ensemble of trees $\{T_m\}_1^{M}$ and make predictions for either a regression type of problem or a classification type of problem. +\end{enumerate} + +\noindent +% !split +\subsection{Bootstrap with Random Forests Instead of a Single Tree, own Bagging} + +\bpycod + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.ensemble import RandomForestRegressor + +np.random.seed(2018) + +n = 100 +n_boostraps = 100 +maxdegree = 14 + +# 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) + +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) + +for degree in range(maxdegree): + model = RandomForestRegressor() + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_.ravel()) + y_pred[:, i] = model.predict(X_test_scaled).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + +\epycod + + + + +% !split +\subsection{Random Forests Compared with other Methods on the Cancer Data} +\bpycod +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) +plt.show() + +\epycod + + +% !split +\subsection{Compare Bagging on Trees with Random Forests} +\bpycod +bag_clf = BaggingClassifier( + DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42), + n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42) +\epycod + + + +\bpycod +bag_clf.fit(X_train, y_train) +y_pred = bag_clf.predict(X_test) +from sklearn.ensemble import RandomForestClassifier +rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42) +rnd_clf.fit(X_train, y_train) +y_pred_rf = rnd_clf.predict(X_test) +np.sum(y_pred == y_pred_rf) / len(y_pred) +\epycod + + + + + +% !split +\subsection{Boosting, a Bird'e Eye} + +The basic idea is to combine weak classifiers in order to create a good +classifier. With a weak classifier we often intend a classifier which +produces results which are only slightly better than we would get by +random guesses. + +This is done by applying in an iterative way a weak (or a standard +classifier like decision trees) to modify the data. In each iteration +we emphasize those observations which are misclassified by weighting +them with a factor. + + +% !split +\subsection{Adaptive boosting: AdaBoost, Basic Algorithm} + +The algorithm here is rather straightforward. Assume that our weak +classifier is a decision tree and we consider a binary set of outputs +with $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of +observations. Our design matrix is given in terms of the +feature/predictor vectors +$\bm{X}=[\bm{x}_0\bm{x}_1\dots\bm{x}_{p-1}$. Finally, we define also a +classifier determined by our data via a function $G(\bm{X})$. This function tells us how well we are able to classify our outputs/targets $\bm{y}$. + +We can then define the misclassification error $\mathrm{err}$ as +\[ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(\bm{X}_{i*}), +\] +where the function $I()$ is one if we misclassify and zero if we classify correctly. + +% !split +\subsection{Basic Steps of AdaBoost} + +With the above definitions we are now ready to set up the algorithm for AdaBoost. +The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. +\begin{enumerate} +\item We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\dots n-1$. It is to see then that $\sum_{i=0}^{n-1}w_i = 1$. + +\item We rewrite the misclassification error as +\end{enumerate} + +\noindent +\[ +\mathrm{err}=\frac{\sum_{i=0}^{n-1}w_iI(y_i\ne G(\bm{X}_{i*})}{\sum_{i=0}^{n-1}w_i}, +\] +\begin{enumerate} +\item 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. +\begin{enumerate} + + \item Fit then a given classifier to the training using the weights $w_i$. + + \item Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly. + + \item Define a quantity $\alpha_{m} = \log{(1-\mathrm{err})/\mathrm{err}} + + \item Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(\bm{X}_{i*})}. + +\end{enumerate} + +\noindent +\item Compute the new classifier $G(\bm{X})= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(\bm{X}_{i*}). +\end{enumerate} + +\noindent +For the iterations with $m \le 2$ the weights are modified +individually at each steps. The obersvations 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. + + + +% !split +\subsection{AdaBoost Examples} + +Using \textbf{Scikit-Learn} it is easy to appply the adaptive boosting algorithm, as done here. + +\bpycod +from sklearn.ensemble import AdaBoostClassifier + +ada_clf = AdaBoostClassifier( + DecisionTreeClassifier(max_depth=1), n_estimators=200, + algorithm="SAMME.R", learning_rate=0.5, random_state=42) +ada_clf.fit(X_train, y_train) + +plot_decision_boundary(ada_clf, X, y) + +m = len(X_train) + +plt.figure(figsize=(11, 4)) +for subplot, learning_rate in ((121, 1), (122, 0.5)): + sample_weights = np.ones(m) + plt.subplot(subplot) + for i in range(5): + svm_clf = SVC(kernel="rbf", C=0.05, gamma="auto", random_state=42) + svm_clf.fit(X_train, y_train, sample_weight=sample_weights) + y_pred = svm_clf.predict(X_train) + sample_weights[y_pred != y_train] *= (1 + learning_rate) + plot_decision_boundary(svm_clf, X, y, alpha=0.2) + plt.title("learning_rate = {}".format(learning_rate), fontsize=16) + if subplot == 121: + plt.text(-0.7, -0.65, "1", fontsize=14) + plt.text(-0.6, -0.10, "2", fontsize=14) + plt.text(-0.5, 0.10, "3", fontsize=14) + plt.text(-0.4, 0.55, "4", fontsize=14) + plt.text(-0.3, 0.90, "5", fontsize=14) + +save_fig("boosting_plot") +plt.show() +\epycod + + +% !split +\subsection{Gradient boosting: Basics} + +Gradient boosting is again a similar technique to Adapative boosting, +it combines so-called weak classifiers or regressors into a strong +method via a series of iterations. + +In order to understand the method, let us illustrate its basics by +bringing back the essential steps in linear regression, where our cost +function was the least squares function. + +% !split +\subsection{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 least squares function +\[ +C(\bm{y},\bm{f})=\frac{1}{n}\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +\] + +The way we proceed in an iterative fashion is to +\begin{enumerate} +\item Initialize our estimate by $f_0(x)=0$. + +\item For $m=1:M$, we +\begin{enumerate} + + \item compute the negative gradient vector $\bm{u}_m = -\partial C(\bm{y},\bm{f})/\partial \bm{f}(x)$ at $f(x) = f_{m-1}(x); + + \item fit the so-called base-learner to the negative gradient $h_m(u_m,x)$; + + \item update the estimate $f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x)$; + +\end{enumerate} + +\noindent +\item The final estimate is then $f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x)$. +\end{enumerate} + +\noindent +% !split +\subsection{Gradient Boosting, Examples} +\bpycod +np.random.seed(42) +X = np.random.rand(100, 1) - 0.5 +y = 3*X[:, 0]**2 + 0.05 * np.random.randn(100) + +from sklearn.tree import DecisionTreeRegressor + +tree_reg1 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg1.fit(X, y) + +y2 = y - tree_reg1.predict(X) +tree_reg2 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg2.fit(X, y2) + +y3 = y2 - tree_reg2.predict(X) +tree_reg3 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg3.fit(X, y3) + +X_new = np.array([[0.8]]) +y_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3)) + +def plot_predictions(regressors, X, y, axes, label=None, style="r-", data_style="b.", data_label=None): + x1 = np.linspace(axes[0], axes[1], 500) + y_pred = sum(regressor.predict(x1.reshape(-1, 1)) for regressor in regressors) + plt.plot(X[:, 0], y, data_style, label=data_label) + plt.plot(x1, y_pred, style, linewidth=2, label=label) + if label or data_label: + plt.legend(loc="upper center", fontsize=16) + plt.axis(axes) + +plt.figure(figsize=(11,11)) + +plt.subplot(321) +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h_1(x_1)$", style="g-", data_label="Training set") +plt.ylabel("$y$", fontsize=16, rotation=0) +plt.title("Residuals and tree predictions", fontsize=16) + +plt.subplot(322) +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1)$", data_label="Training set") +plt.ylabel("$y$", fontsize=16, rotation=0) +plt.title("Ensemble predictions", fontsize=16) + +plt.subplot(323) +plot_predictions([tree_reg2], X, y2, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_2(x_1)$", style="g-", data_style="k+", data_label="Residuals") +plt.ylabel("$y - h_1(x_1)$", fontsize=16) + +plt.subplot(324) +plot_predictions([tree_reg1, tree_reg2], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1)$") +plt.ylabel("$y$", fontsize=16, rotation=0) + +plt.subplot(325) +plot_predictions([tree_reg3], X, y3, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_3(x_1)$", style="g-", data_style="k+") +plt.ylabel("$y - h_1(x_1) - h_2(x_1)$", fontsize=16) +plt.xlabel("$x_1$", fontsize=16) + +plt.subplot(326) +plot_predictions([tree_reg1, tree_reg2, tree_reg3], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1) + h_3(x_1)$") +plt.xlabel("$x_1$", fontsize=16) +plt.ylabel("$y$", fontsize=16, rotation=0) + +save_fig("gradient_boosting_plot") +plt.show() + +from sklearn.ensemble import GradientBoostingRegressor + +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0, random_state=42) +gbrt.fit(X, y) + +gbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42) +gbrt_slow.fit(X, y) + +plt.figure(figsize=(11,4)) + +plt.subplot(121) +plot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="Ensemble predictions") +plt.title("learning_rate={}, n_estimators={}".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14) + +plt.subplot(122) +plot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8]) +plt.title("learning_rate={}, n_estimators={}".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14) + +save_fig("gbrt_learning_rate_plot") +plt.show() + +\epycod + + +% !split +\subsection{Gradient Boots with Early Stopping} +\bpycod + +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error + +X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=49) + +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120, random_state=42) +gbrt.fit(X_train, y_train) + +errors = [mean_squared_error(y_val, y_pred) + for y_pred in gbrt.staged_predict(X_val)] +bst_n_estimators = np.argmin(errors) + 1 + +gbrt_best = GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators, random_state=42) +gbrt_best.fit(X_train, y_train) + +min_error = np.min(errors) +plt.figure(figsize=(11, 4)) + +plt.subplot(121) +plt.plot(errors, "b.-") +plt.plot([bst_n_estimators, bst_n_estimators], [0, min_error], "k--") +plt.plot([0, 120], [min_error, min_error], "k--") +plt.plot(bst_n_estimators, min_error, "ko") +plt.text(bst_n_estimators, min_error*1.2, "Minimum", ha="center", fontsize=14) +plt.axis([0, 120, 0, 0.01]) +plt.xlabel("Number of trees") +plt.title("Validation error", fontsize=14) + +plt.subplot(122) +plot_predictions([gbrt_best], X, y, axes=[-0.5, 0.5, -0.1, 0.8]) +plt.title("Best model (%d trees)" % bst_n_estimators, fontsize=14) + +save_fig("early_stopping_gbrt_plot") +plt.show() + + +gbrt = GradientBoostingRegressor(max_depth=2, warm_start=True, random_state=42) + +min_val_error = float("inf") +error_going_up = 0 +for n_estimators in range(1, 120): + gbrt.n_estimators = n_estimators + gbrt.fit(X_train, y_train) + y_pred = gbrt.predict(X_val) + val_error = mean_squared_error(y_val, y_pred) + if val_error < min_val_error: + min_val_error = val_error + error_going_up = 0 + else: + error_going_up += 1 + if error_going_up == 5: + break # early stopping + + +print(gbrt.n_estimators) +print("Minimum validation MSE:", min_val_error) +\epycod + +% !split +\subsection{XGBoost: Extreme Gradient Boosting} + + +\href{{https://github.com/dmlc/xgboost}}{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 \href{{https://arxiv.org/abs/1603.02754}}{article by Chen and Guestrin}. + +The authors design and build a highly scalable end-to-end tree +boosting system. It has a theoretically justified weighted quantile +sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. + +It is now the algorithm which wins essentially all ML competitions!!! + +% !split +\subsection{Regression Case} + +\bpycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +import xgboost as xgb +from sklearn.preprocessing import StandardScaler +import scikitplot as skplt +from sklearn.metrics import mean_squared_error + +n = 100 +maxdegree = 6 + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) + +error = np.zeros(maxdegree) +bias = np.zeros(maxdegree) +variance = np.zeros(maxdegree) +polydegree = np.zeros(maxdegree) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +for degree in range(maxdegree): + model = xgb.XGBRegressor(objective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1, + max_depth = degree, alpha = 10, n_estimators = 10) + model.fit(X_train_scaled,y_train) + y_pred = model.predict(X_test_scaled) + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) + variance[degree] = np.mean( np.var(y_pred) ) + print('Max depth:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.xlim(1,maxdegree-1) +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + +\epycod + + + +% !split +\subsection{Xgboost on the Cancer Data} +\bpycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.datasets import load_breast_cancer +from sklearn.preprocessing import LabelEncoder +from sklearn.model_selection import cross_validate +import scikitplot as skplt +import xgboost as xgb +# Load the data +cancer = load_breast_cancer() + +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) +print(X_train.shape) +print(X_test.shape) +#now scale the data +from sklearn.preprocessing import StandardScaler +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +xg_clf = xgb.XGBClassifier() +xg_clf.fit(X_train_scaled,y_train) +xgb.plot_tree(xg_clf,num_trees=0) +plt.rcParams['figure.figsize'] = [50, 10] +plt.show() +xgb.plot_importance(xg_clf) +plt.rcParams['figure.figsize'] = [5, 5] +plt.show() +\epycod + +% ------------------- end of main content --------------- + +% #ifdef PREAMBLE +\end{document} +% #endif + diff --git a/doc/src/DecisionTrees/DecisionTrees.tex b/doc/src/DecisionTrees/DecisionTrees.tex new file mode 100644 index 000000000..5ab09d845 --- /dev/null +++ b/doc/src/DecisionTrees/DecisionTrees.tex @@ -0,0 +1,2395 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/hplgit/doconce/) +%% +%% + + +%-------------------- begin preamble ---------------------- + +\documentclass[% +oneside, % oneside: electronic viewing, twoside: printing +final, % draft: marks overfull hboxes, figures with paths +10pt]{article} + +\listfiles % print all files needed to compile this document + +\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} +\usepackage[table]{xcolor} +\usepackage{bm,ltablex,microtype} + +\usepackage[pdftex]{graphicx} + +\usepackage{fancyvrb} % packages needed for verbatim environments +\usepackage{minted} +\usemintedstyle{default} + +\usepackage[T1]{fontenc} +%\usepackage[latin1]{inputenc} +\usepackage{ucs} +\usepackage[utf8x]{inputenc} + +\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern + +% Hyperlinks in PDF: +\definecolor{linkcolor}{rgb}{0,0,0.4} +\usepackage{hyperref} +\hypersetup{ + breaklinks=true, + colorlinks=true, + linkcolor=linkcolor, + urlcolor=linkcolor, + citecolor=black, + filecolor=black, + %filecolor=blue, + pdfmenubar=true, + pdftoolbar=true, + bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC + } +%\hyperbaseurl{} % hyperlinks are relative to this root + +\setcounter{tocdepth}{2} % levels in table of contents + +% Tricks for having figures close to where they are defined: +% 1. define less restrictive rules for where to put figures +\setcounter{topnumber}{2} +\setcounter{bottomnumber}{2} +\setcounter{totalnumber}{4} +\renewcommand{\topfraction}{0.95} +\renewcommand{\bottomfraction}{0.95} +\renewcommand{\textfraction}{0} +\renewcommand{\floatpagefraction}{0.75} +% floatpagefraction must always be less than topfraction! +% 2. ensure all figures are flushed before next section +\usepackage[section]{placeins} +% 3. enable begin{figure}[H] (often leads to ugly pagebreaks) +%\usepackage{float}\restylefloat{figure} + +% --- fancyhdr package for fancy headers --- +\usepackage{fancyhdr} +\fancyhf{} % sets both header and footer to nothing +\renewcommand{\headrulewidth}{0pt} +\fancyfoot[LE,RO]{\thepage} +% Ensure copyright on titlepage (article style) and chapter pages (book style) +\fancypagestyle{plain}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} +% \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} +% Ensure copyright on titlepages with \thispagestyle{empty} +\fancypagestyle{empty}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} + \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} + +\pagestyle{fancy} + + +\usepackage[framemethod=TikZ]{mdframed} + +% --- begin definitions of admonition environments --- + +% --- end of definitions of admonition environments --- + +% prevent orhpans and widows +\clubpenalty = 10000 +\widowpenalty = 10000 + +% --- end of standard preamble for documents --- + + +% insert custom LaTeX commands... + +\raggedbottom +\makeindex +\usepackage[totoc]{idxlayout} % for index in the toc +\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc + +%-------------------- end preamble ---------------------- + +\begin{document} + +% matching end for #ifdef PREAMBLE + +\newcommand{\exercisesection}[1]{\subsection*{#1}} + + +% ------------------- main content ---------------------- + + + +% ----------------- title ------------------------- + +\thispagestyle{empty} + +\begin{center} +{\LARGE\bf +\begin{spacing}{1.25} +Data Analysis and Machine Learning: From Decision Trees to Forests and all that +\end{spacing} +} +\end{center} + +% ----------------- author(s) ------------------------- + +\begin{center} +{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] +\end{center} + +\begin{center} +% List of all institutions: +\centerline{{\small ${}^1$Department of Physics, University of Oslo}} +\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} +\end{center} + +% ----------------- end author(s) ------------------------- + +% --- begin date --- +\begin{center} +Nov 7, 2019 +\end{center} +% --- end date --- + +\vspace{1cm} + + +% !split +\subsection*{Decision trees, overarching aims} + + +Decision trees are supervised learning algorithms used for both, +classification and regression tasks. + + +The main idea of decision trees +is to find those descriptive features which contain the most +\textbf{information} regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. + +The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the \textbf{most +informative} feature is done until we accomplish a stopping criteria +where we then finally end up in so called \textbf{leaf nodes}. + +A decision tree is typically divided into a \textbf{root node}, the \textbf{interior nodes}, +and the final \textbf{leaf nodes} or just \textbf{leaves}. These entities are then connected by so-called \textbf{branches}. + +The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +% !split +\subsection*{A typical Decision Tree with its pertinent Jargon, Classification Problem} + + + +\vspace{6mm} + +% inline figure +\centerline{\includegraphics[width=0.8\linewidth]{DataFiles/cancer.png}} + +\vspace{6mm} + + + +This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using \textbf{Scikit-Learn}'s decision tree classifier. Here we have used the so-called \textbf{gini} index (see below) to split the various branches. + + + +% !split +\subsection*{General Features} + +The overarching approach to decision trees is a top-down approach. + +\begin{itemize} +\item A leaf provides the classification of a given instance. + +\item A node specifies a test of some attribute of the instance. + +\item A branch corresponds to a possible values of an attribute. + +\item An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example. +\end{itemize} + +\noindent +This process is then repeated for the subtree rooted at the new +node. + + +% !split +\subsection*{How do we set it up?} + + +In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: + +\begin{enumerate} +\item Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature + +\item Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process + +\item Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the \emph{predictions} we want to make for new query instances + +\item Show query instances to the tree and run down the tree until we arrive at leaf nodes +\end{enumerate} + +\noindent +Then we are essentially done! + + + + + +% !split +\subsection*{Decision trees and Regression} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +import numpy as np +import matplotlib.pyplot as plt +from sklearn.preprocessing import PolynomialFeatures +from sklearn.linear_model import LinearRegression + +steps=250 + +distance=0 +x=0 +distance_list=[] +steps_list=[] +while x 0 and bestAttrId in attributeIds: + toRemove = attributeIds.index(bestAttrId) + attributeIds.pop(toRemove) + child.next = self.id3Recv( + childSampleIds, attributeIds, child.next) + return root + + def printTree(self): + if self.root: + roots = deque() + roots.append(self.root) + while len(roots) > 0: + root = roots.popleft() + print(root.value) + if root.childs: + for child in root.childs: + print('({})'.format(child.value)) + roots.append(child.next) + elif root.next: + print(root.next) + + +def test(): + f = open('DataFiles/rideclass.csv') + attributes = f.readline().split(',') + attributes = attributes[1:len(attributes)-1] + print(attributes) + sample = f.readlines() + f.close() + for i in range(len(sample)): + sample[i] = re.sub('\d+,', '', sample[i]) + sample[i] = sample[i].strip().split(',') + labels = [] + for s in sample: + labels.append(s.pop()) + # print(sample) + # print(labels) + decisionTree = DecisionTree(sample, attributes, labels) + print("System entropy {}".format(decisionTree.entropy)) + decisionTree.id3() + decisionTree.printTree() + + +if __name__ == '__main__': + test() +\end{minted} + +% !split +\subsection*{Cancer Data again now with Decision Trees and other Methods} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +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))) + +\end{minted} + + +% !split +\subsection*{Another example, the moons again} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from __future__ import division, print_function, unicode_literals + +# Common imports +import numpy as np +import os + +# to make this notebook's output stable across runs +np.random.seed(42) + +# To plot pretty figures +import matplotlib +import matplotlib.pyplot as plt +from matplotlib.colors import ListedColormap +plt.rcParams['axes.labelsize'] = 14 +plt.rcParams['xtick.labelsize'] = 12 +plt.rcParams['ytick.labelsize'] = 12 + + +from sklearn.svm import SVC +from sklearn import datasets +from sklearn.tree import DecisionTreeClassifier +from sklearn.datasets import make_moons +from sklearn.tree import export_graphviz + +Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53) + +deep_tree_clf1 = DecisionTreeClassifier(random_state=42) +deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42) +deep_tree_clf1.fit(Xm, ym) +deep_tree_clf2.fit(Xm, ym) + + +def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True): + x1s = np.linspace(axes[0], axes[1], 100) + x2s = np.linspace(axes[2], axes[3], 100) + x1, x2 = np.meshgrid(x1s, x2s) + X_new = np.c_[x1.ravel(), x2.ravel()] + y_pred = clf.predict(X_new).reshape(x1.shape) + custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) + plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) + if not iris: + custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) + plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) + if plot_training: + plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa") + plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor") + plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica") + plt.axis(axes) + if iris: + plt.xlabel("Petal length", fontsize=14) + plt.ylabel("Petal width", fontsize=14) + else: + plt.xlabel(r"$x_1$", fontsize=18) + plt.ylabel(r"$x_2$", fontsize=18, rotation=0) + if legend: + plt.legend(loc="lower right", fontsize=14) +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False) +plt.title("No restrictions", fontsize=16) +plt.subplot(122) +plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False) +plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14) +plt.show() + +\end{minted} + +% !split +\subsection*{Playing around with regions} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +np.random.seed(6) +Xs = np.random.rand(100, 2) - 0.5 +ys = (Xs[:, 0] > 0).astype(np.float32) * 2 + +angle = np.pi/4 +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) +Xsr = Xs.dot(rotation_matrix) + +tree_clf_s = DecisionTreeClassifier(random_state=42) +tree_clf_s.fit(Xs, ys) +tree_clf_sr = DecisionTreeClassifier(random_state=42) +tree_clf_sr.fit(Xsr, ys) + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) +plt.subplot(122) +plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) + +plt.show() +\end{minted} + +% !split +\subsection*{Regression trees} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +# Quadratic training set + noise +np.random.seed(42) +m = 200 +X = np.random.rand(m, 1) +y = 4 * (X - 0.5) ** 2 +y = y + np.random.randn(m, 1) / 10 +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.tree import DecisionTreeRegressor + +tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg.fit(X, y) +\end{minted} + +% !split +\subsection*{Final regressor code} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.tree import DecisionTreeRegressor + +tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2) +tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"): + x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1) + y_pred = tree_reg.predict(x1) + plt.axis(axes) + plt.xlabel("$x_1$", fontsize=18) + if ylabel: + plt.ylabel(ylabel, fontsize=18, rotation=0) + plt.plot(X, y, "b.") + plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$") + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_regression_predictions(tree_reg1, X, y) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +plt.text(0.21, 0.65, "Depth=0", fontsize=15) +plt.text(0.01, 0.2, "Depth=1", fontsize=13) +plt.text(0.65, 0.8, "Depth=1", fontsize=13) +plt.legend(loc="upper center", fontsize=18) +plt.title("max_depth=2", fontsize=14) + +plt.subplot(122) +plot_regression_predictions(tree_reg2, X, y, ylabel=None) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +for split in (0.0458, 0.1298, 0.2873, 0.9040): + plt.plot([split, split], [-0.2, 1], "k:", linewidth=1) +plt.text(0.3, 0.5, "Depth=2", fontsize=13) +plt.title("max_depth=3", fontsize=14) + +plt.show() +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +tree_reg1 = DecisionTreeRegressor(random_state=42) +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +x1 = np.linspace(0, 1, 500).reshape(-1, 1) +y_pred1 = tree_reg1.predict(x1) +y_pred2 = tree_reg2.predict(x1) + +plt.figure(figsize=(11, 4)) + +plt.subplot(121) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.ylabel("$y$", fontsize=18, rotation=0) +plt.legend(loc="upper center", fontsize=18) +plt.title("No restrictions", fontsize=14) + +plt.subplot(122) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14) + +plt.show() +\end{minted} + + + +% !split +\subsection*{Pros and cons of trees, pros} + +\begin{itemize} +\item White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines) + +\item Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression! + +\item No feature normalization needed + +\item Tree models can handle both continuous and categorical data (Classification and Regression Trees) + +\item Can model nonlinear relationships + +\item Can model interactions between the different descriptive features + +\item Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small) +\end{itemize} + +\noindent +% !split +\subsection*{Disadvantages} + +\begin{itemize} +\item Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches + +\item If continuous features are used the tree may become quite large and hence less interpretable + +\item Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented + +\item Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests + +\item Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. + +\item If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data + +\item Features with many levels may be preferred over features with less levels since for them it is \emph{more easy} to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain +\end{itemize} + +\noindent +However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved. + + +% !split +\subsection*{Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods} + +As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct forests and jungles of trees, homogeneous ones or heterogenous ones. These methods are recognized by different names which we will try to explain here. These are +\begin{enumerate} +\item Voting classifiers + +\item Bagging and Pasting + +\item Random forests + +\item Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost) +\end{enumerate} + +\noindent +We discuss these methods here. + + +% !split +\subsection*{An Overview of Ensemble Methods} + + + +\vspace{6mm} + +% inline figure +\centerline{\includegraphics[width=0.8\linewidth]{DataFiles/ensembleoverview.png}} + +\vspace{6mm} + + + + + +% !split +\subsection*{Bagging} + +The \textbf{plain} decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of $n$ to $p$ is moderately large. + +\textbf{Bootstrap aggregation}, or just \textbf{bagging}, is a +general-purpose procedure for reducing the variance of a statistical +learning method. + + +% !split +\subsection*{More bagging} + +Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all $B$ possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all $B$ trees. + +% !split +\subsection*{Simple Voting Example, head or tail} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +heads_proba = 0.51 +coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32) +cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1) +plt.figure(figsize=(8,3.5)) +plt.plot(cumulative_heads_ratio) +plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%") +plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%") +plt.xlabel("Number of coin tosses") +plt.ylabel("Heads ratio") +plt.legend(loc="lower right") +plt.axis([0, 10000, 0.42, 0.58]) +plt.show() + +\end{minted} + +% !split +\subsection*{Using the Voting Classifier} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) + +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(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)) + +\end{minted} + +% !split +\subsection*{Please, not the moons again! Voting and Bagging} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='hard') +voting_clf.fit(X_train, y_train) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(probability=True, random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='soft') +voting_clf.fit(X_train, y_train) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +\end{minted} + +% !split +\subsection*{Now Bagging} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.ensemble import BaggingClassifier +from sklearn.tree import DecisionTreeClassifier + +bag_clf = BaggingClassifier( + DecisionTreeClassifier(random_state=42), n_estimators=500, + max_samples=100, bootstrap=True, n_jobs=-1, random_state=42) +bag_clf.fit(X_train, y_train) +y_pred = bag_clf.predict(X_test) +\end{minted} + + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.metrics import accuracy_score +print(accuracy_score(y_test, y_pred)) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +tree_clf = DecisionTreeClassifier(random_state=42) +tree_clf.fit(X_train, y_train) +y_pred_tree = tree_clf.predict(X_test) +print(accuracy_score(y_test, y_pred_tree)) +\end{minted} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from matplotlib.colors import ListedColormap + +def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True): + x1s = np.linspace(axes[0], axes[1], 100) + x2s = np.linspace(axes[2], axes[3], 100) + x1, x2 = np.meshgrid(x1s, x2s) + X_new = np.c_[x1.ravel(), x2.ravel()] + y_pred = clf.predict(X_new).reshape(x1.shape) + custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) + plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) + if contour: + custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) + plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) + plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha) + plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha) + plt.axis(axes) + plt.xlabel(r"$x_1$", fontsize=18) + plt.ylabel(r"$x_2$", fontsize=18, rotation=0) +plt.figure(figsize=(11,4)) +plt.subplot(121) +plot_decision_boundary(tree_clf, X, y) +plt.title("Decision Tree", fontsize=14) +plt.subplot(122) +plot_decision_boundary(bag_clf, X, y) +plt.title("Decision Trees with Bagging", fontsize=14) +plt.show() +\end{minted} + + +% !split +\subsection*{Making our own Bagging with Bootstrap} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.tree import DecisionTreeRegressor + + +np.random.seed(2018) + +n = 40 +n_boostraps = 100 +maxdegree = 14 + +# 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) + +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) + +for degree in range(maxdegree): + model = DecisionTreeRegressor(max_depth=5) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_) + y_pred[:, i] = model.predict(X_test_scaled).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + +\end{minted} + + +% !split +\subsection*{Changing the Level of the Decision Tree} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.tree import DecisionTreeRegressor + +n = 100 +n_boostraps = 100 +maxdepth = 8 + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +error = np.zeros(maxdepth) +bias = np.zeros(maxdepth) +variance = np.zeros(maxdepth) +polydegree = np.zeros(maxdepth) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +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) + +for degree in range(1,maxdepth): + model = DecisionTreeRegressor(max_depth=degree) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_) + y_pred[:, i] = model.predict(X_test_scaled)#.ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.xlim(1,maxdepth) +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + + +\end{minted} + + + + +% !split +\subsection*{Random forests} + +Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. + +As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of $m$ predictors is chosen as split +candidates from the full set of $p$ predictors. The split is allowed to +use only one of those $m$ predictors. + +A fresh sample of $m$ predictors is +taken at each split, and typically we choose + +\[ +m\approx \sqrt{p}. +\] + +In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. + +The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quanti- ties. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. + + +% !split +\subsection*{Random Forest Algorithm} +The algorithm described here can be applied to both classification and regression problems. + +We will grow of forest of say $M$ trees. +\begin{enumerate} +\item For $m=1:M$ we +\begin{itemize} + + \item Draw a bootstrap sample of from the training data organized in our $\bm{X}$ matrix. + + \item We grow then a random forest tree $T_m$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached +\begin{enumerate} + + \item we select $m \le p$ varibales at random from the $p$ predictors/features + + \item pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node + + \item split the node into daughter nodes + +\end{enumerate} + +\noindent +\end{itemize} + +\noindent +\item Output then the ensemble of trees $\{T_m\}_1^{M}$ and make predictions for either a regression type of problem or a classification type of problem. +\end{enumerate} + +\noindent +% !split +\subsection*{Bootstrap with Random Forests Instead of a Single Tree, own Bagging} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.ensemble import RandomForestRegressor + +np.random.seed(2018) + +n = 100 +n_boostraps = 100 +maxdegree = 14 + +# 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) + +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) + +for degree in range(maxdegree): + model = RandomForestRegressor() + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_.ravel()) + y_pred[:, i] = model.predict(X_test_scaled).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + +\end{minted} + + + + +% !split +\subsection*{Random Forests Compared with other Methods on the Cancer Data} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +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) +plt.show() + +\end{minted} + + +% !split +\subsection*{Compare Bagging on Trees with Random Forests} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +bag_clf = BaggingClassifier( + DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42), + n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42) +\end{minted} + + + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +bag_clf.fit(X_train, y_train) +y_pred = bag_clf.predict(X_test) +from sklearn.ensemble import RandomForestClassifier +rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42) +rnd_clf.fit(X_train, y_train) +y_pred_rf = rnd_clf.predict(X_test) +np.sum(y_pred == y_pred_rf) / len(y_pred) +\end{minted} + + + + + +% !split +\subsection*{Boosting, a Bird'e Eye} + +The basic idea is to combine weak classifiers in order to create a good +classifier. With a weak classifier we often intend a classifier which +produces results which are only slightly better than we would get by +random guesses. + +This is done by applying in an iterative way a weak (or a standard +classifier like decision trees) to modify the data. In each iteration +we emphasize those observations which are misclassified by weighting +them with a factor. + + +% !split +\subsection*{Adaptive boosting: AdaBoost, Basic Algorithm} + +The algorithm here is rather straightforward. Assume that our weak +classifier is a decision tree and we consider a binary set of outputs +with $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of +observations. Our design matrix is given in terms of the +feature/predictor vectors +$\bm{X}=[\bm{x}_0\bm{x}_1\dots\bm{x}_{p-1}$. Finally, we define also a +classifier determined by our data via a function $G(\bm{X})$. This function tells us how well we are able to classify our outputs/targets $\bm{y}$. + +We can then define the misclassification error $\mathrm{err}$ as +\[ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(\bm{X}_{i*}), +\] +where the function $I()$ is one if we misclassify and zero if we classify correctly. + +% !split +\subsection*{Basic Steps of AdaBoost} + +With the above definitions we are now ready to set up the algorithm for AdaBoost. +The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. +\begin{enumerate} +\item We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\dots n-1$. It is to see then that $\sum_{i=0}^{n-1}w_i = 1$. + +\item We rewrite the misclassification error as +\end{enumerate} + +\noindent +\[ +\mathrm{err}=\frac{\sum_{i=0}^{n-1}w_iI(y_i\ne G(\bm{X}_{i*})}{\sum_{i=0}^{n-1}w_i}, +\] +\begin{enumerate} +\item 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. +\begin{enumerate} + + \item Fit then a given classifier to the training using the weights $w_i$. + + \item Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly. + + \item Define a quantity $\alpha_{m} = \log{(1-\mathrm{err})/\mathrm{err}} + + \item Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(\bm{X}_{i*})}. + +\end{enumerate} + +\noindent +\item Compute the new classifier $G(\bm{X})= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(\bm{X}_{i*}). +\end{enumerate} + +\noindent +For the iterations with $m \le 2$ the weights are modified +individually at each steps. The obersvations 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. + + + +% !split +\subsection*{AdaBoost Examples} + +Using \textbf{Scikit-Learn} it is easy to appply the adaptive boosting algorithm, as done here. + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +from sklearn.ensemble import AdaBoostClassifier + +ada_clf = AdaBoostClassifier( + DecisionTreeClassifier(max_depth=1), n_estimators=200, + algorithm="SAMME.R", learning_rate=0.5, random_state=42) +ada_clf.fit(X_train, y_train) + +plot_decision_boundary(ada_clf, X, y) + +m = len(X_train) + +plt.figure(figsize=(11, 4)) +for subplot, learning_rate in ((121, 1), (122, 0.5)): + sample_weights = np.ones(m) + plt.subplot(subplot) + for i in range(5): + svm_clf = SVC(kernel="rbf", C=0.05, gamma="auto", random_state=42) + svm_clf.fit(X_train, y_train, sample_weight=sample_weights) + y_pred = svm_clf.predict(X_train) + sample_weights[y_pred != y_train] *= (1 + learning_rate) + plot_decision_boundary(svm_clf, X, y, alpha=0.2) + plt.title("learning_rate = {}".format(learning_rate), fontsize=16) + if subplot == 121: + plt.text(-0.7, -0.65, "1", fontsize=14) + plt.text(-0.6, -0.10, "2", fontsize=14) + plt.text(-0.5, 0.10, "3", fontsize=14) + plt.text(-0.4, 0.55, "4", fontsize=14) + plt.text(-0.3, 0.90, "5", fontsize=14) + +save_fig("boosting_plot") +plt.show() +\end{minted} + + +% !split +\subsection*{Gradient boosting: Basics} + +Gradient boosting is again a similar technique to Adapative boosting, +it combines so-called weak classifiers or regressors into a strong +method via a series of iterations. + +In order to understand the method, let us illustrate its basics by +bringing back the essential steps in linear regression, where our cost +function was the least squares function. + +% !split +\subsection*{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 least squares function +\[ +C(\bm{y},\bm{f})=\frac{1}{n}\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +\] + +The way we proceed in an iterative fashion is to +\begin{enumerate} +\item Initialize our estimate by $f_0(x)=0$. + +\item For $m=1:M$, we +\begin{enumerate} + + \item compute the negative gradient vector $\bm{u}_m = -\partial C(\bm{y},\bm{f})/\partial \bm{f}(x)$ at $f(x) = f_{m-1}(x); + + \item fit the so-called base-learner to the negative gradient $h_m(u_m,x)$; + + \item update the estimate $f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x)$; + +\end{enumerate} + +\noindent +\item The final estimate is then $f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x)$. +\end{enumerate} + +\noindent +% !split +\subsection*{Gradient Boosting, Examples} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +np.random.seed(42) +X = np.random.rand(100, 1) - 0.5 +y = 3*X[:, 0]**2 + 0.05 * np.random.randn(100) + +from sklearn.tree import DecisionTreeRegressor + +tree_reg1 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg1.fit(X, y) + +y2 = y - tree_reg1.predict(X) +tree_reg2 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg2.fit(X, y2) + +y3 = y2 - tree_reg2.predict(X) +tree_reg3 = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg3.fit(X, y3) + +X_new = np.array([[0.8]]) +y_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3)) + +def plot_predictions(regressors, X, y, axes, label=None, style="r-", data_style="b.", data_label=None): + x1 = np.linspace(axes[0], axes[1], 500) + y_pred = sum(regressor.predict(x1.reshape(-1, 1)) for regressor in regressors) + plt.plot(X[:, 0], y, data_style, label=data_label) + plt.plot(x1, y_pred, style, linewidth=2, label=label) + if label or data_label: + plt.legend(loc="upper center", fontsize=16) + plt.axis(axes) + +plt.figure(figsize=(11,11)) + +plt.subplot(321) +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h_1(x_1)$", style="g-", data_label="Training set") +plt.ylabel("$y$", fontsize=16, rotation=0) +plt.title("Residuals and tree predictions", fontsize=16) + +plt.subplot(322) +plot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1)$", data_label="Training set") +plt.ylabel("$y$", fontsize=16, rotation=0) +plt.title("Ensemble predictions", fontsize=16) + +plt.subplot(323) +plot_predictions([tree_reg2], X, y2, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_2(x_1)$", style="g-", data_style="k+", data_label="Residuals") +plt.ylabel("$y - h_1(x_1)$", fontsize=16) + +plt.subplot(324) +plot_predictions([tree_reg1, tree_reg2], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1)$") +plt.ylabel("$y$", fontsize=16, rotation=0) + +plt.subplot(325) +plot_predictions([tree_reg3], X, y3, axes=[-0.5, 0.5, -0.5, 0.5], label="$h_3(x_1)$", style="g-", data_style="k+") +plt.ylabel("$y - h_1(x_1) - h_2(x_1)$", fontsize=16) +plt.xlabel("$x_1$", fontsize=16) + +plt.subplot(326) +plot_predictions([tree_reg1, tree_reg2, tree_reg3], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="$h(x_1) = h_1(x_1) + h_2(x_1) + h_3(x_1)$") +plt.xlabel("$x_1$", fontsize=16) +plt.ylabel("$y$", fontsize=16, rotation=0) + +save_fig("gradient_boosting_plot") +plt.show() + +from sklearn.ensemble import GradientBoostingRegressor + +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0, random_state=42) +gbrt.fit(X, y) + +gbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42) +gbrt_slow.fit(X, y) + +plt.figure(figsize=(11,4)) + +plt.subplot(121) +plot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label="Ensemble predictions") +plt.title("learning_rate={}, n_estimators={}".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14) + +plt.subplot(122) +plot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8]) +plt.title("learning_rate={}, n_estimators={}".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14) + +save_fig("gbrt_learning_rate_plot") +plt.show() + +\end{minted} + + +% !split +\subsection*{Gradient Boots with Early Stopping} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} + +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error + +X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=49) + +gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120, random_state=42) +gbrt.fit(X_train, y_train) + +errors = [mean_squared_error(y_val, y_pred) + for y_pred in gbrt.staged_predict(X_val)] +bst_n_estimators = np.argmin(errors) + 1 + +gbrt_best = GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators, random_state=42) +gbrt_best.fit(X_train, y_train) + +min_error = np.min(errors) +plt.figure(figsize=(11, 4)) + +plt.subplot(121) +plt.plot(errors, "b.-") +plt.plot([bst_n_estimators, bst_n_estimators], [0, min_error], "k--") +plt.plot([0, 120], [min_error, min_error], "k--") +plt.plot(bst_n_estimators, min_error, "ko") +plt.text(bst_n_estimators, min_error*1.2, "Minimum", ha="center", fontsize=14) +plt.axis([0, 120, 0, 0.01]) +plt.xlabel("Number of trees") +plt.title("Validation error", fontsize=14) + +plt.subplot(122) +plot_predictions([gbrt_best], X, y, axes=[-0.5, 0.5, -0.1, 0.8]) +plt.title("Best model (%d trees)" % bst_n_estimators, fontsize=14) + +save_fig("early_stopping_gbrt_plot") +plt.show() + + +gbrt = GradientBoostingRegressor(max_depth=2, warm_start=True, random_state=42) + +min_val_error = float("inf") +error_going_up = 0 +for n_estimators in range(1, 120): + gbrt.n_estimators = n_estimators + gbrt.fit(X_train, y_train) + y_pred = gbrt.predict(X_val) + val_error = mean_squared_error(y_val, y_pred) + if val_error < min_val_error: + min_val_error = val_error + error_going_up = 0 + else: + error_going_up += 1 + if error_going_up == 5: + break # early stopping + + +print(gbrt.n_estimators) +print("Minimum validation MSE:", min_val_error) +\end{minted} + +% !split +\subsection*{XGBoost: Extreme Gradient Boosting} + + +\href{{https://github.com/dmlc/xgboost}}{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 \href{{https://arxiv.org/abs/1603.02754}}{article by Chen and Guestrin}. + +The authors design and build a highly scalable end-to-end tree +boosting system. It has a theoretically justified weighted quantile +sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. + +It is now the algorithm which wins essentially all ML competitions!!! + +% !split +\subsection*{Regression Case} + +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +import xgboost as xgb +from sklearn.preprocessing import StandardScaler +import scikitplot as skplt +from sklearn.metrics import mean_squared_error + +n = 100 +maxdegree = 6 + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) + +error = np.zeros(maxdegree) +bias = np.zeros(maxdegree) +variance = np.zeros(maxdegree) +polydegree = np.zeros(maxdegree) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +for degree in range(maxdegree): + model = xgb.XGBRegressor(objective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1, + max_depth = degree, alpha = 10, n_estimators = 10) + model.fit(X_train_scaled,y_train) + y_pred = model.predict(X_test_scaled) + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) + variance[degree] = np.mean( np.var(y_pred) ) + print('Max depth:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.xlim(1,maxdegree-1) +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + +\end{minted} + + + +% !split +\subsection*{Xgboost on the Cancer Data} +\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.datasets import load_breast_cancer +from sklearn.preprocessing import LabelEncoder +from sklearn.model_selection import cross_validate +import scikitplot as skplt +import xgboost as xgb +# Load the data +cancer = load_breast_cancer() + +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) +print(X_train.shape) +print(X_test.shape) +#now scale the data +from sklearn.preprocessing import StandardScaler +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +xg_clf = xgb.XGBClassifier() +xg_clf.fit(X_train_scaled,y_train) +xgb.plot_tree(xg_clf,num_trees=0) +plt.rcParams['figure.figsize'] = [50, 10] +plt.show() +xgb.plot_importance(xg_clf) +plt.rcParams['figure.figsize'] = [5, 5] +plt.show() +\end{minted} + +% ------------------- end of main content --------------- + +\end{document} + diff --git a/doc/src/DecisionTrees/_minted-DecisionTrees/default.pygstyle b/doc/src/DecisionTrees/_minted-DecisionTrees/default.pygstyle new file mode 100644 index 000000000..e69de29bb diff --git a/doc/src/DecisionTrees/ipynb-DecisionTrees-src.tar.gz b/doc/src/DecisionTrees/ipynb-DecisionTrees-src.tar.gz new file mode 100644 index 000000000..0ff487d36 Binary files /dev/null and b/doc/src/DecisionTrees/ipynb-DecisionTrees-src.tar.gz differ diff --git a/doc/src/DecisionTrees/reveal.js/.gitignore b/doc/src/DecisionTrees/reveal.js/.gitignore new file mode 100644 index 000000000..a5df3133d --- /dev/null +++ b/doc/src/DecisionTrees/reveal.js/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.svn +log/*.log +tmp/** +node_modules/ +.sass-cache +css/reveal.min.css +js/reveal.min.js diff --git a/doc/src/DecisionTrees/reveal.js/.travis.yml b/doc/src/DecisionTrees/reveal.js/.travis.yml new file mode 100644 index 000000000..165d9ae9f --- /dev/null +++ b/doc/src/DecisionTrees/reveal.js/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +before_script: + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/src/DecisionTrees/reveal.js/CONTRIBUTING.md b/doc/src/DecisionTrees/reveal.js/CONTRIBUTING.md new file mode 100644 index 000000000..c2091e88f --- /dev/null +++ b/doc/src/DecisionTrees/reveal.js/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/src/DecisionTrees/reveal.js/Gruntfile.js b/doc/src/DecisionTrees/reveal.js/Gruntfile.js new file mode 100644 index 000000000..b257e8f32 --- /dev/null +++ b/doc/src/DecisionTrees/reveal.js/Gruntfile.js @@ -0,0 +1,140 @@ +/* global module:false */ +module.exports = function(grunt) { + var port = grunt.option('port') || 8000; + // Project configuration + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + meta: { + banner: + '/*!\n' + + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + + ' * http://lab.hakim.se/reveal-js\n' + + ' * MIT licensed\n' + + ' *\n' + + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + + ' */' + }, + + qunit: { + files: [ 'test/*.html' ] + }, + + uglify: { + options: { + banner: '<%= meta.banner %>\n' + }, + build: { + src: 'js/reveal.js', + dest: 'js/reveal.min.js' + } + }, + + cssmin: { + compress: { + files: { + 'css/reveal.min.css': [ 'css/reveal.css' ] + } + } + }, + + sass: { + main: { + files: { + 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', + 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', + 'css/theme/cbc.css': 'css/theme/source/cbc.scss', + 'css/theme/default.css': 'css/theme/source/default.scss', + 'css/theme/beige.css': 'css/theme/source/beige.scss', + 'css/theme/night.css': 'css/theme/source/night.scss', + 'css/theme/serif.css': 'css/theme/source/serif.scss', + 'css/theme/simple.css': 'css/theme/source/simple.scss', + 'css/theme/sky.css': 'css/theme/source/sky.scss', + 'css/theme/moon.css': 'css/theme/source/moon.scss', + 'css/theme/solarized.css': 'css/theme/source/solarized.scss', + 'css/theme/blood.css': 'css/theme/source/blood.scss' + } + } + }, + + jshint: { + options: { + curly: false, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + noarg: true, + sub: true, + undef: true, + eqnull: true, + browser: true, + expr: true, + globals: { + head: false, + module: false, + console: false, + unescape: false + } + }, + files: [ 'Gruntfile.js', 'js/reveal.js' ] + }, + + connect: { + server: { + options: { + port: port, + base: '.' + } + } + }, + + zip: { + 'reveal-js-presentation.zip': [ + 'index.html', + 'css/**', + 'js/**', + 'lib/**', + 'images/**', + 'plugin/**' + ] + }, + + watch: { + main: { + files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], + tasks: 'default' + }, + theme: { + files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], + tasks: 'themes' + } + } + + }); + + // Dependencies + grunt.loadNpmTasks( 'grunt-contrib-qunit' ); + grunt.loadNpmTasks( 'grunt-contrib-jshint' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-zip' ); + + // Default task + grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + + // Theme task + grunt.registerTask( 'themes', [ 'sass' ] ); + + // Package presentation to archive + grunt.registerTask( 'package', [ 'default', 'zip' ] ); + + // Serve presentation locally + grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); + + // Run tests + grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); + +}; diff --git a/doc/src/DecisionTrees/reveal.js/LICENSE b/doc/src/DecisionTrees/reveal.js/LICENSE new file mode 100644 index 000000000..09623076f --- /dev/null +++ b/doc/src/DecisionTrees/reveal.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Hakim El Hattab, http://hakim.se + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/doc/src/DecisionTrees/reveal.js/README.md b/doc/src/DecisionTrees/reveal.js/README.md new file mode 100644 index 000000000..573b19597 --- /dev/null +++ b/doc/src/DecisionTrees/reveal.js/README.md @@ -0,0 +1,1052 @@ +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) + +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). + +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. + + +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. +- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! +- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. + +## Online Editor + +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). + + +## Instructions + +### Markup + +Markup hierarchy needs to be ``
    `` where the ``
    `` represents one slide and can be repeated indefinitely. If you place multiple ``
    ``'s inside of another ``
    `` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: + +```html +
    +
    +
    Single Horizontal Slide
    +
    +
    Vertical Slide 1
    +
    Vertical Slide 2
    +
    +
    +
    +``` + +### Markdown + +It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
    ``` elements and wrap the contents in a ``` +
    +``` + +#### External Markdown + +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. + +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). + +```html +
    +
    +``` + +#### Element Attributes + +Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. + +```html +
    + +
    +``` + +#### Slide Attributes + +Special syntax (in html comment) is available for adding attributes to the slide `
    ` elements generated by your Markdown. + +```html +
    + +
    +``` + + +### Configuration + +At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. + +```javascript +Reveal.initialize({ + + // Display controls in the bottom right corner + controls: true, + + // Display a presentation progress bar + progress: true, + + // Display the page number of the current slide + slideNumber: false, + + // Push each slide change to the browser history + history: false, + + // Enable keyboard shortcuts for navigation + keyboard: true, + + // Enable the slide overview mode + overview: true, + + // Vertical centering of slides + center: true, + + // Enables touch navigation on devices with touch input + touch: true, + + // Loop the presentation + loop: false, + + // Change the presentation direction to be RTL + rtl: false, + + // Turns fragments on and off globally + fragments: true, + + // Flags if the presentation is running in an embedded mode, + // i.e. contained within a limited portion of the screen + embedded: false, + + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Number of milliseconds between automatically proceeding to the + // next slide, disabled when set to 0, this value can be overwritten + // by using a data-autoslide attribute on your slides + autoSlide: 0, + + // Stop auto-sliding after user input + autoSlideStoppable: true, + + // Enable slide navigation via mouse wheel + mouseWheel: false, + + // Hides the address bar on mobile devices + hideAddressBar: true, + + // Opens links in an iframe preview overlay + previewLinks: false, + + // Transition style + transition: 'default', // none/fade/slide/convex/concave/zoom + + // Transition speed + transitionSpeed: 'default', // default/fast/slow + + // Transition style for full page slide backgrounds + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom + + // Number of slides away from the current that are visible + viewDistance: 3, + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' + +}); +``` + + +The configuration can be updated after initialization using the ```configure``` method: + +```javascript +// Turn autoSlide off +Reveal.configure({ autoSlide: 0 }); + +// Start auto-sliding every 5s +Reveal.configure({ autoSlide: 5000 }); +``` + + +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
    elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + +### Presentation Size + +All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. + +See below for a list of configuration options related to sizing, including default values: + +```javascript +Reveal.initialize({ + + ... + + // The "normal" size of the presentation, aspect ratio will be preserved + // when the presentation is scaled to fit different resolutions. Can be + // specified using percentage units. + width: 960, + height: 700, + + // Factor of the display size that should remain empty around the content + margin: 0.1, + + // Bounds for smallest/largest possible scale to apply to content + minScale: 0.2, + maxScale: 1.5 + +}); +``` + + +### Auto-sliding + +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: + +```javascript +// Slide every five seconds +Reveal.configure({ + autoSlide: 5000 +}); +``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. + +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: + +```html +
    +

    After 2 seconds the first fragment will be shown.

    +

    After 10 seconds the next fragment will be shown.

    +

    Now, the fragment is displayed for 2 seconds before the next slide is shown.

    +
    +``` + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + + +### Keyboard Bindings + +If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: + +```javascript +Reveal.configure({ + keyboard: { + 13: 'next', // go to the next slide when the ENTER key is pressed + 27: function() {}, // do something custom when ESC is pressed + 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) + } +}); +``` + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
    + + + +
    +``` + + +### API + +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: + +```javascript +// Navigation +Reveal.slide( indexh, indexv, indexf ); +Reveal.left(); +Reveal.right(); +Reveal.up(); +Reveal.down(); +Reveal.prev(); +Reveal.next(); +Reveal.prevFragment(); +Reveal.nextFragment(); + +// Toggle presentation states, optionally pass true/false to force on/off +Reveal.toggleOverview(); +Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); + +// Retrieves the previous and current slide elements +Reveal.getPreviousSlide(); +Reveal.getCurrentSlide(); + +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// State checks +Reveal.isFirstSlide(); +Reveal.isLastSlide(); +Reveal.isOverview(); +Reveal.isPaused(); +Reveal.isAutoSliding(); +``` + +### Slide Changed Event + +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. + +Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'slidechanged', function( event ) { + // event.previousSlide, event.currentSlide, event.indexh, event.indexv +} ); +``` + +### Presentation State + +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States + +If you set ``data-state="somestate"`` on a slide ``
    ``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. + +Furthermore you can also listen to these changes in state via JavaScript: + +```javascript +Reveal.addEventListener( 'somestate', function() { + // TODO: Sprinkle magic +}, false ); +``` + +### Slide Backgrounds + +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
    ``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. + +```html +
    +

    All CSS color formats are supported, like rgba() or hsl().

    +
    +
    +

    This slide will have a full-size background image.

    +
    +
    +

    This background image will be sized to 100px and repeated.

    +
    +
    +

    Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

    +
    +
    +

    Embeds a web page as a background. Note that the page won't be interactive.

    +
    +``` + +Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. + + +### Parallax Background + +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). + +```javascript +Reveal.initialize({ + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) + + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 + +}); +``` + +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). + + + +### Slide Transitions +The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: + +```html +
    +

    This slide will override the presentation transition and zoom!

    +
    + +
    +

    Choose from three transition speeds: default, fast or slow!

    +
    +``` + +You can also use different in and out transitions for the same slide: + +```html +
    + The train goes on … +
    +
    + and on … +
    +
    + and stops. +
    +
    + (Passengers entering and leaving) +
    +
    + And it starts again. +
    +``` + + +Note that this does not work with the page and cube transitions. + + +### Internal links + +It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
    ```): + +```html +Link +Link +``` + +You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. + +```html + + + + + + +``` + + +### Fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments + +The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: + +```html +
    +

    grow

    +

    shrink

    +

    fade-out

    +

    visible only once

    +

    blue only once

    +

    highlight-red

    +

    highlight-green

    +

    highlight-blue

    +
    +``` + +Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. + +```html +
    + + I'll fade in, then out + +
    +``` + +The display order of fragments can be controlled using the ```data-fragment-index``` attribute. + +```html +
    +

    Appears last

    +

    Appears first

    +

    Appears second

    +
    +``` + +### Fragment events + +When a slide fragment is either shown or hidden reveal.js will dispatch an event. + +Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'fragmentshown', function( event ) { + // event.fragment = the fragment DOM element +} ); +Reveal.addEventListener( 'fragmenthidden', function( event ) { + // event.fragment = the fragment DOM element +} ); +``` + +### Code syntax highlighting + +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. + +```html +
    +
    
    +(def lazy-fib
    +  (concat
    +   [0 1]
    +   ((fn rfib [a b]
    +        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
    +	
    +
    +``` + +### Slide number +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. + +```javascript +// Shows the slide number using default formatting +Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); + +``` + + +### Overview mode + +Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, +as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: + +```javascript +Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); +Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); + +// Toggle the overview mode programmatically +Reveal.toggleOverview(); +``` + +### Fullscreen mode +Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. + + +### Embedded media +Embedded HTML5 `