diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html index 8136086bf..4591c0dc0 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs000.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -195,7 +202,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Oct 29, 2019

    +

    Oct 31, 2019


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

  • 9
  • 10
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html index 017dbf0d2..da1b18b86 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs001.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -224,7 +231,7 @@ given some assumptions, make predictions about the target feature value
  • 10
  • 11
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html index dd41cd135..c2d203db9 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs002.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -199,7 +206,7 @@ In the figure here we present a decision tree obtained from a classification pro
  • 11
  • 12
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html index 827610f21..bd90da767 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs003.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -200,7 +207,7 @@ In the figure we present a decision tree obtained from a simple regression prob
  • 12
  • 13
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html index f9696d635..b35e3c6ad 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs004.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -211,7 +218,7 @@ node.
  • 13
  • 14
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html index fe313790f..7f7d52061 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs005.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -212,7 +219,7 @@ Then we are essentially done!
  • 14
  • 15
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html index 5ea3aa965..151427dea 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs006.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -291,7 +298,7 @@ plt.show()
  • 15
  • 16
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html index 45d860328..fcc3f8e61 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs007.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -224,7 +231,7 @@ within box \( j \).
  • 16
  • 17
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html index c0391d238..c8533f1f2 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs008.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -216,7 +223,7 @@ better tree in some future step.
  • 17
  • 18
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html index 29a2bf72e..525fffcfd 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs009.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -249,7 +256,7 @@ region contains more than five observations.
  • 18
  • 19
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html index 9b03e5c6f..83fbc8ee0 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs010.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -218,7 +225,7 @@ parameter \( \alpha \).
  • 19
  • 20
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html index f6e230314..87d3174c7 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs011.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -230,7 +237,7 @@ subtree corresponding to \( \alpha \).
  • 20
  • 21
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html index d660d8e01..d322da06d 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs012.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -226,7 +233,7 @@ MathJax.Hub.Config({
  • 21
  • 22
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html index fed826427..bdf58e375 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs013.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -218,7 +225,7 @@ fall into that region.
  • 22
  • 23
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html index 16a25427e..3743f474b 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs014.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -223,7 +230,7 @@ than is the classification error rate.
  • 23
  • 24
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html index 6a1d92ce7..09645870c 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs015.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -249,7 +256,7 @@ $$
  • 24
  • 25
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html index 0486b997b..31ddce3f4 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs016.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,185 +183,43 @@ MathJax.Hub.Config({ -

    The CART (Classification and Regression Tree) algorithm

    - -

    -The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm first before we move on to the information gain algorithm ID3. - +

    Visualizing the Tree, Classification

    -

    from random import seed
    -from random import randrange
    -from csv import reader
    - 
    -# Load a CSV file
    -def load_csv(filename):
    -	file = open(filename, "rb")
    -	lines = reader(file)
    -	dataset = list(lines)
    -	return dataset
    - 
    -# Convert string column to float
    -def str_column_to_float(dataset, column):
    -	for row in dataset:
    -		row[column] = float(row[column].strip())
    - 
    -# Split a dataset into k folds
    -def cross_validation_split(dataset, n_folds):
    -	dataset_split = list()
    -	dataset_copy = list(dataset)
    -	fold_size = int(len(dataset) / n_folds)
    -	for i in range(n_folds):
    -		fold = list()
    -		while len(fold) < fold_size:
    -			index = randrange(len(dataset_copy))
    -			fold.append(dataset_copy.pop(index))
    -		dataset_split.append(fold)
    -	return dataset_split
    - 
    -# Calculate accuracy percentage
    -def accuracy_metric(actual, predicted):
    -	correct = 0
    -	for i in range(len(actual)):
    -		if actual[i] == predicted[i]:
    -			correct += 1
    -	return correct / float(len(actual)) * 100.0
    - 
    -# Evaluate an algorithm using a cross validation split
    -def evaluate_algorithm(dataset, algorithm, n_folds, *args):
    -	folds = cross_validation_split(dataset, n_folds)
    -	scores = list()
    -	for fold in folds:
    -		train_set = list(folds)
    -		train_set.remove(fold)
    -		train_set = sum(train_set, [])
    -		test_set = list()
    -		for row in fold:
    -			row_copy = list(row)
    -			test_set.append(row_copy)
    -			row_copy[-1] = None
    -		predicted = algorithm(train_set, test_set, *args)
    -		actual = [row[-1] for row in fold]
    -		accuracy = accuracy_metric(actual, predicted)
    -		scores.append(accuracy)
    -	return scores
    - 
    -# 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)
    -			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}
    - 
    -# Create a terminal node value
    -def to_terminal(group):
    -	outcomes = [row[-1] for row in group]
    -	return max(set(outcomes), key=outcomes.count)
    - 
    -# Create child splits for a node or make terminal
    -def split(node, max_depth, min_size, depth):
    -	left, right = node['groups']
    -	del(node['groups'])
    -	# check for a no split
    -	if not left or not right:
    -		node['left'] = node['right'] = to_terminal(left + right)
    -		return
    -	# check for max depth
    -	if depth >= max_depth:
    -		node['left'], node['right'] = to_terminal(left), to_terminal(right)
    -		return
    -	# process left child
    -	if len(left) <= min_size:
    -		node['left'] = to_terminal(left)
    -	else:
    -		node['left'] = get_split(left)
    -		split(node['left'], max_depth, min_size, depth+1)
    -	# process right child
    -	if len(right) <= min_size:
    -		node['right'] = to_terminal(right)
    -	else:
    -		node['right'] = get_split(right)
    -		split(node['right'], max_depth, min_size, depth+1)
    - 
    -# Build a decision tree
    -def build_tree(train, max_depth, min_size):
    -	root = get_split(train)
    -	split(root, max_depth, min_size, 1)
    -	return root
    - 
    -# Make a prediction with a decision tree
    -def predict(node, row):
    -	if row[node['index']] < node['value']:
    -		if isinstance(node['left'], dict):
    -			return predict(node['left'], row)
    -		else:
    -			return node['left']
    -	else:
    -		if isinstance(node['right'], dict):
    -			return predict(node['right'], row)
    -		else:
    -			return node['right']
    - 
    -# Classification and Regression Tree Algorithm
    -def decision_tree(train, test, max_depth, min_size):
    -	tree = build_tree(train, max_depth, min_size)
    -	predictions = list()
    -	for row in test:
    -		prediction = predict(tree, row)
    -		predictions.append(prediction)
    -	return(predictions)
    - 
    -# Test CART 
    -seed(1)
    -# load and prepare data
    -filename = 'DataFiles/rideclass.csv'
    -dataset = load_csv(filename)
    -# convert string attributes to integers
    -for i in range(len(dataset[0])):
    -	str_column_to_float(dataset, i)
    -# evaluate algorithm
    -n_folds = 5
    -max_depth = 5
    -min_size = 10
    -scores = evaluate_algorithm(dataset, decision_tree, n_folds, max_depth, min_size)
    -print('Scores: %s' % scores)
    -print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))
    +
    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)
     

    @@ -382,7 +247,7 @@ scores = evaluate_algorithm(dataset, decisio

  • 25
  • 26
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html index 3ff2e4c07..ab845fe0f 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs017.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,39 +183,35 @@ MathJax.Hub.Config({ -

    Entropy and the ID3 algorithm

    - +

    Visualizing the Tree, The Moons

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

    @@ -235,7 +238,7 @@ attributes at each step while growing the tree.

  • 26
  • 27
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html index 0b61ea913..504c3373f 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs018.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,11 +183,48 @@ MathJax.Hub.Config({ -

    Implementing the ID3 Algorithm

    +

    Computing the Gini index

    -more text to come here, material presented during lecture Friday Oct 25. +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
    +
    +

    @@ -207,7 +251,7 @@ MathJax.Hub.Config({

  • 27
  • 28
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html index c9605d53a..6cc582f6b 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs019.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,51 +183,64 @@ MathJax.Hub.Config({ -

    Cancer Data again now with Decision Trees

    +

    Simple Python Code to read in Data

    +

    -

    import matplotlib.pyplot as plt
    +
    # Common imports
     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
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +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
     
    -# Load the data
    -cancer = load_breast_cancer()
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
     
    -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)))
    +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("ride.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)
    +display(ridedata)
    +# Features and targets
    +X = ridedata.loc[:, ridedata.columns != 'Ride'].values
    +display(X)
    +y = ridedata.loc[:, ridedata.columns == 'Ride'].values
    +display(y)
    +# Categorical variables to one-hot's
    +onehotencoder = OneHotEncoder(categories="auto")
    +
    +X = ColumnTransformer([("", onehotencoder)]).fit_transform(X)
    +y.shape
    +
    +display(X)
    +display(y)
     

    @@ -248,7 +268,7 @@ deep_tree_clf.fit(X_train_scaled, y_train)

  • 28
  • 29
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html index 644725d7e..c20d867e3 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs020.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,74 +183,80 @@ MathJax.Hub.Config({ -

    Another example, the moons again

    +

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

    -

    from __future__ import division, print_function, unicode_literals
    +
    # 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
     
    -# Common imports
    -import numpy as np
    -import os
    +# 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]]
     
    -# 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()
    +split = get_split(dataset)
    +print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
     

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

  • 29
  • 30
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html index 03d9652fb..5bc4ec431 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs021.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,31 +183,39 @@ MathJax.Hub.Config({ -

    Playing around with regions

    +

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

    np.random.seed(6)
    -Xs = np.random.rand(100, 2) - 0.5
    -ys = (Xs[:, 0] > 0).astype(np.float32) * 2
    +
      +
    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. +
    -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) +The ID3 algorithm selects, which attribute to test at each node in the +tree. -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) +

    +We would like to select the attribute that is most useful for classifying +examples. -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) +

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

    @@ -227,7 +242,7 @@ plt.show()

  • 30
  • 31
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html index cd54b9b78..25c8cbcc9 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs022.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,25 +183,212 @@ MathJax.Hub.Config({ -

    Regression trees

    +

    Implementing the ID3 Algorithm

    +

    +import re +import math +from collections import deque - -

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

    +class Node(object): + def __init__(self): + self.value = None + self.next = None + self.childs = None + +

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

    @@ -221,7 +415,7 @@ tree_reg.fit(X, y)

  • 31
  • 32
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html index 67de6c38d..6c66fb5e7 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs023.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,80 +183,51 @@ MathJax.Hub.Config({ -

    Final regressor code

    +

    Cancer Data again now with Decision Trees and other Methods

    -

    from sklearn.tree import DecisionTreeRegressor
    +
    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
     
    -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)
    +# Load the data
    +cancer = load_breast_cancer()
     
    -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()
    +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)))
     

    @@ -277,7 +255,7 @@ plt.show()

  • 32
  • 33
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html index 245bac28b..4edb2d51a 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs024.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,18 +183,76 @@ MathJax.Hub.Config({ -

    Pros and cons of trees, pros

    +

    Another example, the moons again

    +

    -

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

      @@ -212,6 +277,8 @@ MathJax.Hub.Config({
    • 32
    • 33
    • 34
    • +
    • ...
    • +
    • 39
    • »
    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html index 199639975..9b12a47de 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs025.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,20 +183,31 @@ MathJax.Hub.Config({ -

    Disadvantages

    +

    Playing around with regions

    +

    -

      -
    • 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
    • -
    + +
    np.random.seed(6)
    +Xs = np.random.rand(100, 2) - 0.5
    +ys = (Xs[:, 0] > 0).astype(np.float32) * 2
     
    -However, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of trees can be substantially improved.
    +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()
    +

    @@ -214,6 +232,9 @@ However, by aggregating many decision trees, using methods like bagging, random

  • 32
  • 33
  • 34
  • +
  • 35
  • +
  • ...
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html index 585aa4cfd..8f217f034 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs026.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,46 +183,25 @@ MathJax.Hub.Config({ -

    Bagging

    - +

    Regression trees

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

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

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

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

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

    @@ -239,6 +225,10 @@ predictor, averaged over all \( B \) trees.

  • 32
  • 33
  • 34
  • +
  • 35
  • +
  • 36
  • +
  • ...
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html index 7c8f43f65..21cc1bb47 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs027.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,21 +183,79 @@ MathJax.Hub.Config({ -

    Simple example, head or tail

    +

    Final regressor code

    -

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

    @@ -215,6 +280,11 @@ plt.show()

  • 32
  • 33
  • 34
  • +
  • 35
  • +
  • 36
  • +
  • 37
  • +
  • ...
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html index 6dcc724bf..de920c9e4 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs028.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,48 +183,18 @@ MathJax.Hub.Config({ -

    Random forests

    +

    Pros and cons of trees, pros

    -

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

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

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

    diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html index c7afc7f08..0ccfacfb4 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs029.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,21 +183,20 @@ MathJax.Hub.Config({ -

    A simple scikit-learn example

    -

    +

    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. - -
    from sklearn.ensemble import RandomForestClassifier
    -from sklearn.preprocessing import LabelEncoder
    -from sklearn.model_selection import cross_validate
    -# Data set not specificied
    -X = dataset.XXX
    -Y = dataset.YYY
    -#Instantiate the model with 100 trees and entropy as splitting criteria
    -Random_Forest_model = RandomForestClassifier(n_estimators=100,criterion="entropy")
    -#Cross validation
    -accuracy = cross_validate(Random_Forest_model,X,Y,cv=10)['test_score']
    -

    @@ -211,6 +217,11 @@ accuracy = cross_validate(Random_Forest_mode

  • 32
  • 33
  • 34
  • +
  • 35
  • +
  • 36
  • +
  • 37
  • +
  • 38
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html index 233dda632..0227cab95 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs030.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,61 +183,22 @@ MathJax.Hub.Config({ -

    Please, not the moons again!

    +

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

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

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

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

    @@ -250,6 +218,11 @@ voting_clf.fit(X_train, y_train)

  • 32
  • 33
  • 34
  • +
  • 35
  • +
  • 36
  • +
  • 37
  • +
  • 38
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html b/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html index d85e0ae27..8c89c0702 100644 --- a/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html +++ b/doc/pub/DecisionTrees/html/._DecisionTrees-bs031.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -176,64 +183,32 @@ MathJax.Hub.Config({ -

    Bagging examples

    +

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

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

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

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

    @@ -252,6 +227,11 @@ plt.show()

  • 32
  • 33
  • 34
  • +
  • 35
  • +
  • 36
  • +
  • 37
  • +
  • 38
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-bs.html b/doc/pub/DecisionTrees/html/DecisionTrees-bs.html index 8136086bf..4591c0dc0 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees-bs.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees-bs.html @@ -67,30 +67,32 @@ Automatically generated HTML file from DocOnce source ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -143,24 +145,29 @@ MathJax.Hub.Config({
  • A Classification Tree
  • Growing a classification tree
  • Classification tree, how to split nodes
  • -
  • The CART (Classification and Regression Tree) algorithm
  • -
  • Entropy and the ID3 algorithm
  • -
  • Implementing the ID3 Algorithm
  • -
  • Cancer Data again now with Decision Trees
  • -
  • Another example, the moons again
  • -
  • Playing around with regions
  • -
  • Regression trees
  • -
  • Final regressor code
  • -
  • Pros and cons of trees, pros
  • -
  • Disadvantages
  • -
  • Bagging
  • -
  • Simple example, head or tail
  • -
  • Random forests
  • -
  • A simple scikit-learn example
  • -
  • Please, not the moons again!
  • -
  • Bagging examples
  • -
  • Then random forests
  • -
  • Boosting and more
  • +
  • Visualizing the Tree, Classification
  • +
  • Visualizing the Tree, The Moons
  • +
  • Computing the Gini index
  • +
  • Simple Python Code to read in Data
  • +
  • Computing the Gini Factor
  • +
  • Entropy and the ID3 algorithm
  • +
  • Implementing the ID3 Algorithm
  • +
  • Cancer Data again now with Decision Trees and other Methods
  • +
  • Another example, the moons again
  • +
  • Playing around with regions
  • +
  • Regression trees
  • +
  • Final regressor code
  • +
  • Pros and cons of trees, pros
  • +
  • Disadvantages
  • +
  • Bagging
  • +
  • More bagging
  • +
  • Simple example, head or tail
  • +
  • Bagging Example
  • +
  • Random forests
  • +
  • A simple scikit-learn example
  • +
  • Please, not the moons again!
  • +
  • Bagging examples
  • +
  • Then random forests
  • @@ -195,7 +202,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Oct 29, 2019

    +

    Oct 31, 2019


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

  • 9
  • 10
  • ...
  • -
  • 34
  • +
  • 39
  • »
  • diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html b/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html index aca451881..2b39f802b 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

     
    -

    Oct 29, 2019

    +

    Oct 31, 2019


    @@ -627,71 +627,200 @@ $$

    -

    The CART (Classification and Regression Tree) algorithm

    +

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

    Computing the Gini index

    -The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm first before we move on to the information gain algorithm ID3. +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

    -

    from random import seed
    -from random import randrange
    -from csv import reader
    - 
    -# Load a CSV file
    -def load_csv(filename):
    -	file = open(filename, "rb")
    -	lines = reader(file)
    -	dataset = list(lines)
    -	return dataset
    - 
    -# Convert string column to float
    -def str_column_to_float(dataset, column):
    -	for row in dataset:
    -		row[column] = float(row[column].strip())
    - 
    -# Split a dataset into k folds
    -def cross_validation_split(dataset, n_folds):
    -	dataset_split = list()
    -	dataset_copy = list(dataset)
    -	fold_size = int(len(dataset) / n_folds)
    -	for i in range(n_folds):
    -		fold = list()
    -		while len(fold) < fold_size:
    -			index = randrange(len(dataset_copy))
    -			fold.append(dataset_copy.pop(index))
    -		dataset_split.append(fold)
    -	return dataset_split
    - 
    -# Calculate accuracy percentage
    -def accuracy_metric(actual, predicted):
    -	correct = 0
    -	for i in range(len(actual)):
    -		if actual[i] == predicted[i]:
    -			correct += 1
    -	return correct / float(len(actual)) * 100.0
    - 
    -# Evaluate an algorithm using a cross validation split
    -def evaluate_algorithm(dataset, algorithm, n_folds, *args):
    -	folds = cross_validation_split(dataset, n_folds)
    -	scores = list()
    -	for fold in folds:
    -		train_set = list(folds)
    -		train_set.remove(fold)
    -		train_set = sum(train_set, [])
    -		test_set = list()
    -		for row in fold:
    -			row_copy = list(row)
    -			test_set.append(row_copy)
    -			row_copy[-1] = None
    -		predicted = algorithm(train_set, test_set, *args)
    -		actual = [row[-1] for row in fold]
    -		accuracy = accuracy_metric(actual, predicted)
    -		scores.append(accuracy)
    -	return scores
    - 
    -# Split a dataset based on an attribute and an attribute value
    +
    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +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("ride.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)
    +display(ridedata)
    +# Features and targets
    +X = ridedata.loc[:, ridedata.columns != 'Ride'].values
    +display(X)
    +y = ridedata.loc[:, ridedata.columns == 'Ride'].values
    +display(y)
    +# Categorical variables to one-hot's
    +onehotencoder = OneHotEncoder(categories="auto")
    +
    +X = ColumnTransformer([("", onehotencoder)]).fit_transform(X)
    +y.shape
    +
    +display(X)
    +display(y)
    +
    +
    + + +
    +

    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:
    @@ -720,7 +849,7 @@ The above functions (gini, entropy and misclassification error) are important co
     		# 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))
    @@ -729,89 +858,34 @@ The above functions (gini, entropy and misclassification error) are important co
     		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}
      
    -# Create a terminal node value
    -def to_terminal(group):
    -	outcomes = [row[-1] for row in group]
    -	return max(set(outcomes), key=outcomes.count)
    - 
    -# Create child splits for a node or make terminal
    -def split(node, max_depth, min_size, depth):
    -	left, right = node['groups']
    -	del(node['groups'])
    -	# check for a no split
    -	if not left or not right:
    -		node['left'] = node['right'] = to_terminal(left + right)
    -		return
    -	# check for max depth
    -	if depth >= max_depth:
    -		node['left'], node['right'] = to_terminal(left), to_terminal(right)
    -		return
    -	# process left child
    -	if len(left) <= min_size:
    -		node['left'] = to_terminal(left)
    -	else:
    -		node['left'] = get_split(left)
    -		split(node['left'], max_depth, min_size, depth+1)
    -	# process right child
    -	if len(right) <= min_size:
    -		node['right'] = to_terminal(right)
    -	else:
    -		node['right'] = get_split(right)
    -		split(node['right'], max_depth, min_size, depth+1)
    - 
    -# Build a decision tree
    -def build_tree(train, max_depth, min_size):
    -	root = get_split(train)
    -	split(root, max_depth, min_size, 1)
    -	return root
    - 
    -# Make a prediction with a decision tree
    -def predict(node, row):
    -	if row[node['index']] < node['value']:
    -		if isinstance(node['left'], dict):
    -			return predict(node['left'], row)
    -		else:
    -			return node['left']
    -	else:
    -		if isinstance(node['right'], dict):
    -			return predict(node['right'], row)
    -		else:
    -			return node['right']
    - 
    -# Classification and Regression Tree Algorithm
    -def decision_tree(train, test, max_depth, min_size):
    -	tree = build_tree(train, max_depth, min_size)
    -	predictions = list()
    -	for row in test:
    -		prediction = predict(tree, row)
    -		predictions.append(prediction)
    -	return(predictions)
    - 
    -# Test CART 
    -seed(1)
    -# load and prepare data
    -filename = 'DataFiles/rideclass.csv'
    -dataset = load_csv(filename)
    -# convert string attributes to integers
    -for i in range(len(dataset[0])):
    -	str_column_to_float(dataset, i)
    -# evaluate algorithm
    -n_folds = 5
    -max_depth = 5
    -min_size = 10
    -scores = evaluate_algorithm(dataset, decision_tree, n_folds, max_depth, min_size)
    -print('Scores: %s' % scores)
    -print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))
    +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

    +

    Entropy and the ID3 algorithm

    ID3, learns decision trees by constructing @@ -848,15 +922,216 @@ attributes at each step while growing the tree.

    -

    Implementing the ID3 Algorithm

    +

    Implementing the ID3 Algorithm

    -more text to come here, material presented during lecture Friday Oct 25. +import re +import math +from collections import deque + +

    + + + + + + +

    +class Node(object): + def __init__(self): + self.value = None + self.next = None + self.childs = None + +

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

    +

    Cancer Data again now with Decision Trees and other Methods

    @@ -906,7 +1181,7 @@ deep_tree_clf.fit(X_train_scaled, y_train)

    -

    Another example, the moons again

    +

    Another example, the moons again

    @@ -979,7 +1254,7 @@ plt.show()

    -

    Playing around with regions

    +

    Playing around with regions

    @@ -987,7 +1262,7 @@ plt.show() Xs = np.random.rand(100, 2) - 0.5 ys = (Xs[:, 0] > 0).astype(np.float32) * 2 -angle = np.pi / 4 +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) @@ -1008,7 +1283,7 @@ plt.show()

    -

    Regression trees

    +

    Regression trees

    @@ -1031,7 +1306,7 @@ tree_reg.fit(X, y)

    -

    Final regressor code

    +

    Final regressor code

    @@ -1110,7 +1385,7 @@ plt.show()

    -

    Pros and cons of trees, pros

    +

    Pros and cons of trees, pros

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

      Disadvantages

      +

      Disadvantages

      • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
      • @@ -1143,7 +1418,7 @@ However, by aggregating many decision trees, using methods like bagging, random
        -

        Bagging

        +

        Bagging

        The plain decision trees suffer from high @@ -1158,6 +1433,11 @@ 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 @@ -1186,7 +1466,7 @@ predictor, averaged over all \( B \) trees.

        -

        Simple example, head or tail

        +

        Simple example, head or tail

        @@ -1207,7 +1487,59 @@ plt.show()

        -

        Random forests

        +

        Bagging Example

        +

        + + +

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

        Random forests

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

        -

        A simple scikit-learn example

        +

        A simple scikit-learn example

        @@ -1272,7 +1604,7 @@ accuracy = cross_validate(Random_Forest_model,X,Y,cv=Please, not the moons again! +

        Please, not the moons again!

        @@ -1331,7 +1663,7 @@ voting_clf.fit(X_train, y_train)

        -

        Bagging examples

        +

        Bagging examples

        @@ -1393,7 +1725,7 @@ plt.show()

        -

        Then random forests

        +

        Then random forests

        @@ -1415,12 +1747,6 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)

        -
        -

        Boosting and more

        -More material to come here. -
        - -
    diff --git a/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html b/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html index c889b56e0..b75715681 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees-solarized.html @@ -87,30 +87,32 @@ div { text-align: justify; text-justify: inter-word; } ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -152,7 +154,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Oct 29, 2019

    +

    Oct 31, 2019












    @@ -606,71 +608,196 @@ $$











    -

    The CART (Classification and Regression Tree) algorithm

    +

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

    +









    + +

    Computing the Gini index

    -The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm first before we move on to the information gain algorithm ID3. +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

    -

    from random import seed
    -from random import randrange
    -from csv import reader
    - 
    -# Load a CSV file
    -def load_csv(filename):
    -	file = open(filename, "rb")
    -	lines = reader(file)
    -	dataset = list(lines)
    -	return dataset
    - 
    -# Convert string column to float
    -def str_column_to_float(dataset, column):
    -	for row in dataset:
    -		row[column] = float(row[column].strip())
    - 
    -# Split a dataset into k folds
    -def cross_validation_split(dataset, n_folds):
    -	dataset_split = list()
    -	dataset_copy = list(dataset)
    -	fold_size = int(len(dataset) / n_folds)
    -	for i in range(n_folds):
    -		fold = list()
    -		while len(fold) < fold_size:
    -			index = randrange(len(dataset_copy))
    -			fold.append(dataset_copy.pop(index))
    -		dataset_split.append(fold)
    -	return dataset_split
    - 
    -# Calculate accuracy percentage
    -def accuracy_metric(actual, predicted):
    -	correct = 0
    -	for i in range(len(actual)):
    -		if actual[i] == predicted[i]:
    -			correct += 1
    -	return correct / float(len(actual)) * 100.0
    - 
    -# Evaluate an algorithm using a cross validation split
    -def evaluate_algorithm(dataset, algorithm, n_folds, *args):
    -	folds = cross_validation_split(dataset, n_folds)
    -	scores = list()
    -	for fold in folds:
    -		train_set = list(folds)
    -		train_set.remove(fold)
    -		train_set = sum(train_set, [])
    -		test_set = list()
    -		for row in fold:
    -			row_copy = list(row)
    -			test_set.append(row_copy)
    -			row_copy[-1] = None
    -		predicted = algorithm(train_set, test_set, *args)
    -		actual = [row[-1] for row in fold]
    -		accuracy = accuracy_metric(actual, predicted)
    -		scores.append(accuracy)
    -	return scores
    - 
    -# Split a dataset based on an attribute and an attribute value
    +
    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +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("ride.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)
    +display(ridedata)
    +# Features and targets
    +X = ridedata.loc[:, ridedata.columns != 'Ride'].values
    +display(X)
    +y = ridedata.loc[:, ridedata.columns == 'Ride'].values
    +display(y)
    +# Categorical variables to one-hot's
    +onehotencoder = OneHotEncoder(categories="auto")
    +
    +X = ColumnTransformer([("", onehotencoder)]).fit_transform(X)
    +y.shape
    +
    +display(X)
    +display(y)
    +
    +

    +









    + +

    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:
    @@ -699,7 +826,7 @@ The above functions (gini, entropy and misclassification error) are important co
     		# 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))
    @@ -708,88 +835,33 @@ The above functions (gini, entropy and misclassification error) are important co
     		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}
      
    -# Create a terminal node value
    -def to_terminal(group):
    -	outcomes = [row[-1] for row in group]
    -	return max(set(outcomes), key=outcomes.count)
    - 
    -# Create child splits for a node or make terminal
    -def split(node, max_depth, min_size, depth):
    -	left, right = node['groups']
    -	del(node['groups'])
    -	# check for a no split
    -	if not left or not right:
    -		node['left'] = node['right'] = to_terminal(left + right)
    -		return
    -	# check for max depth
    -	if depth >= max_depth:
    -		node['left'], node['right'] = to_terminal(left), to_terminal(right)
    -		return
    -	# process left child
    -	if len(left) <= min_size:
    -		node['left'] = to_terminal(left)
    -	else:
    -		node['left'] = get_split(left)
    -		split(node['left'], max_depth, min_size, depth+1)
    -	# process right child
    -	if len(right) <= min_size:
    -		node['right'] = to_terminal(right)
    -	else:
    -		node['right'] = get_split(right)
    -		split(node['right'], max_depth, min_size, depth+1)
    - 
    -# Build a decision tree
    -def build_tree(train, max_depth, min_size):
    -	root = get_split(train)
    -	split(root, max_depth, min_size, 1)
    -	return root
    - 
    -# Make a prediction with a decision tree
    -def predict(node, row):
    -	if row[node['index']] < node['value']:
    -		if isinstance(node['left'], dict):
    -			return predict(node['left'], row)
    -		else:
    -			return node['left']
    -	else:
    -		if isinstance(node['right'], dict):
    -			return predict(node['right'], row)
    -		else:
    -			return node['right']
    - 
    -# Classification and Regression Tree Algorithm
    -def decision_tree(train, test, max_depth, min_size):
    -	tree = build_tree(train, max_depth, min_size)
    -	predictions = list()
    -	for row in test:
    -		prediction = predict(tree, row)
    -		predictions.append(prediction)
    -	return(predictions)
    - 
    -# Test CART 
    -seed(1)
    -# load and prepare data
    -filename = 'DataFiles/rideclass.csv'
    -dataset = load_csv(filename)
    -# convert string attributes to integers
    -for i in range(len(dataset[0])):
    -	str_column_to_float(dataset, i)
    -# evaluate algorithm
    -n_folds = 5
    -max_depth = 5
    -min_size = 10
    -scores = evaluate_algorithm(dataset, decision_tree, n_folds, max_depth, min_size)
    -print('Scores: %s' % scores)
    -print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))
    +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

    +

    Entropy and the ID3 algorithm

    ID3, learns decision trees by constructing @@ -825,15 +897,216 @@ attributes at each step while growing the tree.











    -

    Implementing the ID3 Algorithm

    +

    Implementing the ID3 Algorithm

    -more text to come here, material presented during lecture Friday Oct 25. +import re +import math +from collections import deque + +

    + + + + + + +

    +class Node(object): + def __init__(self): + self.value = None + self.next = None + self.childs = None + +

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

    +

    Cancer Data again now with Decision Trees and other Methods

    @@ -882,7 +1155,7 @@ deep_tree_clf.fit(X_train_scaled, y_train)











    -

    Another example, the moons again

    +

    Another example, the moons again

    @@ -954,7 +1227,7 @@ plt.show()











    -

    Playing around with regions

    +

    Playing around with regions

    @@ -962,7 +1235,7 @@ plt.show() Xs = np.random.rand(100, 2) - 0.5 ys = (Xs[:, 0] > 0).astype(np.float32) * 2 -angle = np.pi / 4 +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) @@ -982,7 +1255,7 @@ plt.show()











    -

    Regression trees

    +

    Regression trees

    @@ -1004,7 +1277,7 @@ tree_reg.fit(X, y)











    -

    Final regressor code

    +

    Final regressor code

    @@ -1082,7 +1355,7 @@ plt.show()











    -

    Pros and cons of trees, pros

    +

    Pros and cons of trees, pros

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









      -

      Disadvantages

      +

      Disadvantages

      • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
      • @@ -1113,7 +1386,7 @@ However, by aggregating many decision trees, using methods like bagging, random











        -

        Bagging

        +

        Bagging

        The plain decision trees suffer from high @@ -1129,6 +1402,11 @@ of \( n \) to \( p \) is moderately large. 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 @@ -1156,7 +1434,7 @@ predictor, averaged over all \( B \) trees.











        -

        Simple example, head or tail

        +

        Simple example, head or tail

        @@ -1176,7 +1454,58 @@ plt.show()











        -

        Random forests

        +

        Bagging Example

        +

        + + +

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

        +









        + +

        Random forests

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











        -

        A simple scikit-learn example

        +

        A simple scikit-learn example

        @@ -1238,7 +1567,7 @@ accuracy = cross_validate(Random_Forest_model,X,Y,cv=Please, not the moons again! +

        Please, not the moons again!

        @@ -1296,7 +1625,7 @@ voting_clf.fit(X_train, y_train)











        -

        Bagging examples

        +

        Bagging examples

        @@ -1357,7 +1686,7 @@ plt.show()











        -

        Then random forests

        +

        Then random forests

        @@ -1376,12 +1705,6 @@ 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 and more

    -More material to come here. -

    diff --git a/doc/pub/DecisionTrees/html/DecisionTrees.html b/doc/pub/DecisionTrees/html/DecisionTrees.html index dfb71089a..5885a1674 100644 --- a/doc/pub/DecisionTrees/html/DecisionTrees.html +++ b/doc/pub/DecisionTrees/html/DecisionTrees.html @@ -92,30 +92,32 @@ div { text-align: justify; text-justify: inter-word; } ('A Classification Tree', 2, None, '___sec12'), ('Growing a classification tree', 2, None, '___sec13'), ('Classification tree, how to split nodes', 2, None, '___sec14'), - ('The CART (Classification and Regression Tree) algorithm', + ('Visualizing the Tree, Classification', 2, None, '___sec15'), + ('Visualizing the Tree, The Moons', 2, None, '___sec16'), + ('Computing the Gini index', 2, None, '___sec17'), + ('Simple Python Code to read in Data', 2, None, '___sec18'), + ('Computing the Gini Factor', 2, None, '___sec19'), + ('Entropy and the ID3 algorithm', 2, None, '___sec20'), + ('Implementing the ID3 Algorithm', 2, None, '___sec21'), + ('Cancer Data again now with Decision Trees and other Methods', 2, None, - '___sec15'), - ('Entropy and the ID3 algorithm', 2, None, '___sec16'), - ('Implementing the ID3 Algorithm', 2, None, '___sec17'), - ('Cancer Data again now with Decision Trees', - 2, - None, - '___sec18'), - ('Another example, the moons again', 2, None, '___sec19'), - ('Playing around with regions', 2, None, '___sec20'), - ('Regression trees', 2, None, '___sec21'), - ('Final regressor code', 2, None, '___sec22'), - ('Pros and cons of trees, pros', 2, None, '___sec23'), - ('Disadvantages', 2, None, '___sec24'), - ('Bagging', 2, None, '___sec25'), - ('Simple example, head or tail', 2, None, '___sec26'), - ('Random forests', 2, None, '___sec27'), - ('A simple scikit-learn example', 2, None, '___sec28'), - ('Please, not the moons again!', 2, None, '___sec29'), - ('Bagging examples', 2, None, '___sec30'), - ('Then random forests', 2, None, '___sec31'), - ('Boosting and more', 2, None, '___sec32')]} + '___sec22'), + ('Another example, the moons again', 2, None, '___sec23'), + ('Playing around with regions', 2, None, '___sec24'), + ('Regression trees', 2, None, '___sec25'), + ('Final regressor code', 2, None, '___sec26'), + ('Pros and cons of trees, pros', 2, None, '___sec27'), + ('Disadvantages', 2, None, '___sec28'), + ('Bagging', 2, None, '___sec29'), + ('More bagging', 2, None, '___sec30'), + ('Simple example, head or tail', 2, None, '___sec31'), + ('Bagging Example', 2, None, '___sec32'), + ('Random forests', 2, None, '___sec33'), + ('A simple scikit-learn example', 2, None, '___sec34'), + ('Please, not the moons again!', 2, None, '___sec35'), + ('Bagging examples', 2, None, '___sec36'), + ('Then random forests', 2, None, '___sec37')]} end of tocinfo --> @@ -157,7 +159,7 @@ MathJax.Hub.Config({

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

    -

    Oct 29, 2019

    +

    Oct 31, 2019












    @@ -611,71 +613,196 @@ $$











    -

    The CART (Classification and Regression Tree) algorithm

    +

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

    +









    + +

    Computing the Gini index

    -The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm first before we move on to the information gain algorithm ID3. +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

    -

    from random import seed
    -from random import randrange
    -from csv import reader
    - 
    -# Load a CSV file
    -def load_csv(filename):
    -	file = open(filename, "rb")
    -	lines = reader(file)
    -	dataset = list(lines)
    -	return dataset
    - 
    -# Convert string column to float
    -def str_column_to_float(dataset, column):
    -	for row in dataset:
    -		row[column] = float(row[column].strip())
    - 
    -# Split a dataset into k folds
    -def cross_validation_split(dataset, n_folds):
    -	dataset_split = list()
    -	dataset_copy = list(dataset)
    -	fold_size = int(len(dataset) / n_folds)
    -	for i in range(n_folds):
    -		fold = list()
    -		while len(fold) < fold_size:
    -			index = randrange(len(dataset_copy))
    -			fold.append(dataset_copy.pop(index))
    -		dataset_split.append(fold)
    -	return dataset_split
    - 
    -# Calculate accuracy percentage
    -def accuracy_metric(actual, predicted):
    -	correct = 0
    -	for i in range(len(actual)):
    -		if actual[i] == predicted[i]:
    -			correct += 1
    -	return correct / float(len(actual)) * 100.0
    - 
    -# Evaluate an algorithm using a cross validation split
    -def evaluate_algorithm(dataset, algorithm, n_folds, *args):
    -	folds = cross_validation_split(dataset, n_folds)
    -	scores = list()
    -	for fold in folds:
    -		train_set = list(folds)
    -		train_set.remove(fold)
    -		train_set = sum(train_set, [])
    -		test_set = list()
    -		for row in fold:
    -			row_copy = list(row)
    -			test_set.append(row_copy)
    -			row_copy[-1] = None
    -		predicted = algorithm(train_set, test_set, *args)
    -		actual = [row[-1] for row in fold]
    -		accuracy = accuracy_metric(actual, predicted)
    -		scores.append(accuracy)
    -	return scores
    - 
    -# Split a dataset based on an attribute and an attribute value
    +
    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +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("ride.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)
    +display(ridedata)
    +# Features and targets
    +X = ridedata.loc[:, ridedata.columns != 'Ride'].values
    +display(X)
    +y = ridedata.loc[:, ridedata.columns == 'Ride'].values
    +display(y)
    +# Categorical variables to one-hot's
    +onehotencoder = OneHotEncoder(categories="auto")
    +
    +X = ColumnTransformer([("", onehotencoder)]).fit_transform(X)
    +y.shape
    +
    +display(X)
    +display(y)
    +
    +

    +









    + +

    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:
    @@ -704,7 +831,7 @@ The above functions (gini, entropy and misclassification error) are important co
     		# 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))
    @@ -713,88 +840,33 @@ The above functions (gini, entropy and misclassification error) are important co
     		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}
      
    -# Create a terminal node value
    -def to_terminal(group):
    -	outcomes = [row[-1] for row in group]
    -	return max(set(outcomes), key=outcomes.count)
    - 
    -# Create child splits for a node or make terminal
    -def split(node, max_depth, min_size, depth):
    -	left, right = node['groups']
    -	del(node['groups'])
    -	# check for a no split
    -	if not left or not right:
    -		node['left'] = node['right'] = to_terminal(left + right)
    -		return
    -	# check for max depth
    -	if depth >= max_depth:
    -		node['left'], node['right'] = to_terminal(left), to_terminal(right)
    -		return
    -	# process left child
    -	if len(left) <= min_size:
    -		node['left'] = to_terminal(left)
    -	else:
    -		node['left'] = get_split(left)
    -		split(node['left'], max_depth, min_size, depth+1)
    -	# process right child
    -	if len(right) <= min_size:
    -		node['right'] = to_terminal(right)
    -	else:
    -		node['right'] = get_split(right)
    -		split(node['right'], max_depth, min_size, depth+1)
    - 
    -# Build a decision tree
    -def build_tree(train, max_depth, min_size):
    -	root = get_split(train)
    -	split(root, max_depth, min_size, 1)
    -	return root
    - 
    -# Make a prediction with a decision tree
    -def predict(node, row):
    -	if row[node['index']] < node['value']:
    -		if isinstance(node['left'], dict):
    -			return predict(node['left'], row)
    -		else:
    -			return node['left']
    -	else:
    -		if isinstance(node['right'], dict):
    -			return predict(node['right'], row)
    -		else:
    -			return node['right']
    - 
    -# Classification and Regression Tree Algorithm
    -def decision_tree(train, test, max_depth, min_size):
    -	tree = build_tree(train, max_depth, min_size)
    -	predictions = list()
    -	for row in test:
    -		prediction = predict(tree, row)
    -		predictions.append(prediction)
    -	return(predictions)
    - 
    -# Test CART 
    -seed(1)
    -# load and prepare data
    -filename = 'DataFiles/rideclass.csv'
    -dataset = load_csv(filename)
    -# convert string attributes to integers
    -for i in range(len(dataset[0])):
    -	str_column_to_float(dataset, i)
    -# evaluate algorithm
    -n_folds = 5
    -max_depth = 5
    -min_size = 10
    -scores = evaluate_algorithm(dataset, decision_tree, n_folds, max_depth, min_size)
    -print('Scores: %s' % scores)
    -print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))
    +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

    +

    Entropy and the ID3 algorithm

    ID3, learns decision trees by constructing @@ -830,15 +902,216 @@ attributes at each step while growing the tree.











    -

    Implementing the ID3 Algorithm

    +

    Implementing the ID3 Algorithm

    -more text to come here, material presented during lecture Friday Oct 25. +import re +import math +from collections import deque + +

    + + + + + + +

    +class Node(object): + def __init__(self): + self.value = None + self.next = None + self.childs = None + +

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

    +

    Cancer Data again now with Decision Trees and other Methods

    @@ -887,7 +1160,7 @@ deep_tree_clf.fit(X_train_scaled, y_train)











    -

    Another example, the moons again

    +

    Another example, the moons again

    @@ -959,7 +1232,7 @@ plt.show()











    -

    Playing around with regions

    +

    Playing around with regions

    @@ -967,7 +1240,7 @@ plt.show() Xs = np.random.rand(100, 2) - 0.5 ys = (Xs[:, 0] > 0).astype(np.float32) * 2 -angle = np.pi / 4 +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) @@ -987,7 +1260,7 @@ plt.show()











    -

    Regression trees

    +

    Regression trees

    @@ -1009,7 +1282,7 @@ tree_reg.fit(X, y)











    -

    Final regressor code

    +

    Final regressor code

    @@ -1087,7 +1360,7 @@ plt.show()











    -

    Pros and cons of trees, pros

    +

    Pros and cons of trees, pros

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









      -

      Disadvantages

      +

      Disadvantages

      • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
      • @@ -1118,7 +1391,7 @@ However, by aggregating many decision trees, using methods like bagging, random











        -

        Bagging

        +

        Bagging

        The plain decision trees suffer from high @@ -1134,6 +1407,11 @@ of \( n \) to \( p \) is moderately large. 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 @@ -1161,7 +1439,7 @@ predictor, averaged over all \( B \) trees.











        -

        Simple example, head or tail

        +

        Simple example, head or tail

        @@ -1181,7 +1459,58 @@ plt.show()











        -

        Random forests

        +

        Bagging Example

        +

        + + +

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

        +









        + +

        Random forests

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











        -

        A simple scikit-learn example

        +

        A simple scikit-learn example

        @@ -1243,7 +1572,7 @@ accuracy = cross_validate(Random_Forest_mode











        -

        Please, not the moons again!

        +

        Please, not the moons again!

        @@ -1301,7 +1630,7 @@ voting_clf.fit(X_train, y_train)











        -

        Bagging examples

        +

        Bagging examples

        @@ -1362,7 +1691,7 @@ plt.show()











        -

        Then random forests

        +

        Then random forests

        @@ -1381,12 +1710,6 @@ 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 and more

    -More material to come here. -

    diff --git a/doc/pub/DecisionTrees/ipynb/DecisionTrees.ipynb b/doc/pub/DecisionTrees/ipynb/DecisionTrees.ipynb index ac3afe181..e06ed31ed 100644 --- a/doc/pub/DecisionTrees/ipynb/DecisionTrees.ipynb +++ b/doc/pub/DecisionTrees/ipynb/DecisionTrees.ipynb @@ -10,7 +10,7 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Oct 29, 2019**\n", + "Date: **Oct 31, 2019**\n", "\n", "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", @@ -506,9 +506,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## The CART (Classification and Regression Tree) algorithm\n", - "\n", - "The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm first before we move on to the information gain algorithm ID3." + "## Visualizing the Tree, Classification" ] }, { @@ -519,62 +517,210 @@ }, "outputs": [], "source": [ - "from random import seed\n", - "from random import randrange\n", - "from csv import reader\n", - " \n", - "# Load a CSV file\n", - "def load_csv(filename):\n", - "\tfile = open(filename, \"rb\")\n", - "\tlines = reader(file)\n", - "\tdataset = list(lines)\n", - "\treturn dataset\n", - " \n", - "# Convert string column to float\n", - "def str_column_to_float(dataset, column):\n", - "\tfor row in dataset:\n", - "\t\trow[column] = float(row[column].strip())\n", - " \n", - "# Split a dataset into k folds\n", - "def cross_validation_split(dataset, n_folds):\n", - "\tdataset_split = list()\n", - "\tdataset_copy = list(dataset)\n", - "\tfold_size = int(len(dataset) / n_folds)\n", - "\tfor i in range(n_folds):\n", - "\t\tfold = list()\n", - "\t\twhile len(fold) < fold_size:\n", - "\t\t\tindex = randrange(len(dataset_copy))\n", - "\t\t\tfold.append(dataset_copy.pop(index))\n", - "\t\tdataset_split.append(fold)\n", - "\treturn dataset_split\n", - " \n", - "# Calculate accuracy percentage\n", - "def accuracy_metric(actual, predicted):\n", - "\tcorrect = 0\n", - "\tfor i in range(len(actual)):\n", - "\t\tif actual[i] == predicted[i]:\n", - "\t\t\tcorrect += 1\n", - "\treturn correct / float(len(actual)) * 100.0\n", - " \n", - "# Evaluate an algorithm using a cross validation split\n", - "def evaluate_algorithm(dataset, algorithm, n_folds, *args):\n", - "\tfolds = cross_validation_split(dataset, n_folds)\n", - "\tscores = list()\n", - "\tfor fold in folds:\n", - "\t\ttrain_set = list(folds)\n", - "\t\ttrain_set.remove(fold)\n", - "\t\ttrain_set = sum(train_set, [])\n", - "\t\ttest_set = list()\n", - "\t\tfor row in fold:\n", - "\t\t\trow_copy = list(row)\n", - "\t\t\ttest_set.append(row_copy)\n", - "\t\t\trow_copy[-1] = None\n", - "\t\tpredicted = algorithm(train_set, test_set, *args)\n", - "\t\tactual = [row[-1] for row in fold]\n", - "\t\taccuracy = accuracy_metric(actual, predicted)\n", - "\t\tscores.append(accuracy)\n", - "\treturn scores\n", - " \n", + "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": [ + "## 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" + ] + }, + { + "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.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(\"ride.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", + "display(ridedata)\n", + "# Features and targets\n", + "X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n", + "display(X)\n", + "y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n", + "display(y)\n", + "# Categorical variables to one-hot's\n", + "onehotencoder = OneHotEncoder(categories=\"auto\")\n", + "\n", + "X = ColumnTransformer([(\"\", onehotencoder)]).fit_transform(X)\n", + "y.shape\n", + "\n", + "display(X)\n", + "display(y)" + ] + }, + { + "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", @@ -604,7 +750,7 @@ "\t\t# weight the group score by its relative size\n", "\t\tgini += (1.0 - score) * (size / n_instances)\n", "\treturn gini\n", - " \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", @@ -613,83 +759,28 @@ "\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", - "# Create a terminal node value\n", - "def to_terminal(group):\n", - "\toutcomes = [row[-1] for row in group]\n", - "\treturn max(set(outcomes), key=outcomes.count)\n", - " \n", - "# Create child splits for a node or make terminal\n", - "def split(node, max_depth, min_size, depth):\n", - "\tleft, right = node['groups']\n", - "\tdel(node['groups'])\n", - "\t# check for a no split\n", - "\tif not left or not right:\n", - "\t\tnode['left'] = node['right'] = to_terminal(left + right)\n", - "\t\treturn\n", - "\t# check for max depth\n", - "\tif depth >= max_depth:\n", - "\t\tnode['left'], node['right'] = to_terminal(left), to_terminal(right)\n", - "\t\treturn\n", - "\t# process left child\n", - "\tif len(left) <= min_size:\n", - "\t\tnode['left'] = to_terminal(left)\n", - "\telse:\n", - "\t\tnode['left'] = get_split(left)\n", - "\t\tsplit(node['left'], max_depth, min_size, depth+1)\n", - "\t# process right child\n", - "\tif len(right) <= min_size:\n", - "\t\tnode['right'] = to_terminal(right)\n", - "\telse:\n", - "\t\tnode['right'] = get_split(right)\n", - "\t\tsplit(node['right'], max_depth, min_size, depth+1)\n", - " \n", - "# Build a decision tree\n", - "def build_tree(train, max_depth, min_size):\n", - "\troot = get_split(train)\n", - "\tsplit(root, max_depth, min_size, 1)\n", - "\treturn root\n", - " \n", - "# Make a prediction with a decision tree\n", - "def predict(node, row):\n", - "\tif row[node['index']] < node['value']:\n", - "\t\tif isinstance(node['left'], dict):\n", - "\t\t\treturn predict(node['left'], row)\n", - "\t\telse:\n", - "\t\t\treturn node['left']\n", - "\telse:\n", - "\t\tif isinstance(node['right'], dict):\n", - "\t\t\treturn predict(node['right'], row)\n", - "\t\telse:\n", - "\t\t\treturn node['right']\n", - " \n", - "# Classification and Regression Tree Algorithm\n", - "def decision_tree(train, test, max_depth, min_size):\n", - "\ttree = build_tree(train, max_depth, min_size)\n", - "\tpredictions = list()\n", - "\tfor row in test:\n", - "\t\tprediction = predict(tree, row)\n", - "\t\tpredictions.append(prediction)\n", - "\treturn(predictions)\n", - " \n", - "# Test CART \n", - "seed(1)\n", - "# load and prepare data\n", - "filename = 'DataFiles/rideclass.csv'\n", - "dataset = load_csv(filename)\n", - "# convert string attributes to integers\n", - "for i in range(len(dataset[0])):\n", - "\tstr_column_to_float(dataset, i)\n", - "# evaluate algorithm\n", - "n_folds = 5\n", - "max_depth = 5\n", - "min_size = 10\n", - "scores = evaluate_algorithm(dataset, decision_tree, n_folds, max_depth, min_size)\n", - "print('Scores: %s' % scores)\n", - "print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))" + "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']))" ] }, { @@ -729,14 +820,201 @@ "\n", "## Implementing the ID3 Algorithm\n", "\n", - "**more text to come here**, material presented during lecture Friday Oct 25.\n", + "import re\n", + "import math\n", + "from collections import deque\n", "\n", - "## Cancer Data again now with Decision Trees" + "\n", + "\n", + "\n", + "\n", + "\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", + "\n", + "\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()\n", + "\n", + "\n", + "## Cancer Data again now with Decision Trees and other Methods" ] }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 6, "metadata": { "collapsed": false }, @@ -794,7 +1072,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 7, "metadata": { "collapsed": false }, @@ -875,7 +1153,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 8, "metadata": { "collapsed": false }, @@ -885,7 +1163,7 @@ "Xs = np.random.rand(100, 2) - 0.5\n", "ys = (Xs[:, 0] > 0).astype(np.float32) * 2\n", "\n", - "angle = np.pi / 4\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", @@ -912,7 +1190,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 9, "metadata": { "collapsed": false }, @@ -928,7 +1206,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 10, "metadata": { "collapsed": false }, @@ -949,7 +1227,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 11, "metadata": { "collapsed": false }, @@ -997,7 +1275,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 12, "metadata": { "collapsed": false }, @@ -1086,6 +1364,8 @@ "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", @@ -1113,7 +1393,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 13, "metadata": { "collapsed": false }, @@ -1133,6 +1413,66 @@ "plt.show()" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Bagging Example" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "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": {}, @@ -1188,7 +1528,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 15, "metadata": { "collapsed": false }, @@ -1215,7 +1555,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 16, "metadata": { "collapsed": false }, @@ -1243,7 +1583,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 17, "metadata": { "collapsed": false }, @@ -1259,7 +1599,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 18, "metadata": { "collapsed": false }, @@ -1277,7 +1617,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 19, "metadata": { "collapsed": false }, @@ -1300,7 +1640,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 20, "metadata": { "collapsed": false }, @@ -1318,7 +1658,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 21, "metadata": { "collapsed": false }, @@ -1330,7 +1670,7 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 22, "metadata": { "collapsed": false }, @@ -1344,7 +1684,7 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 23, "metadata": { "collapsed": false }, @@ -1387,7 +1727,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 24, "metadata": { "collapsed": false }, @@ -1400,7 +1740,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 25, "metadata": { "collapsed": false }, @@ -1414,15 +1754,6 @@ "y_pred_rf = rnd_clf.predict(X_test)\n", "np.sum(y_pred == y_pred_rf) / len(y_pred)" ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## Boosting and more\n", - "More material to come here." - ] } ], "metadata": {}, diff --git a/doc/pub/DecisionTrees/ipynb/ipynb-DecisionTrees-src.tar.gz b/doc/pub/DecisionTrees/ipynb/ipynb-DecisionTrees-src.tar.gz index 88c12c16b..9ecef5eea 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 4f7eedff7..445baf294 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/DataFiles/cancer.dot b/doc/src/DecisionTrees/DataFiles/cancer.dot new file mode 100644 index 000000000..5b4b48a9b --- /dev/null +++ b/doc/src/DecisionTrees/DataFiles/cancer.dot @@ -0,0 +1,57 @@ +digraph Tree { +node [shape=box, style="filled, rounded", color="black", fontname=helvetica] ; +edge [fontname=helvetica] ; +0 [label="worst perimeter <= 106.05\ngini = 0.465\nsamples = 426\nvalue = [[269, 157]\n[157, 269]]", fillcolor="#e5813908"] ; +1 [label="worst concave points <= 0.159\ngini = 0.067\nsamples = 259\nvalue = [[250, 9]\n[9, 250]]", fillcolor="#e58139db"] ; +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="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="worst symmetry <= 0.208\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"] ; +5 -> 6 ; +7 [label="gini = 0.0\nsamples = 2\nvalue = [[2, 0]\n[0, 2]]", fillcolor="#e58139ff"] ; +5 -> 7 ; +8 [label="worst texture <= 29.455\ngini = 0.397\nsamples = 11\nvalue = [[8, 3]\n[3, 8]]", fillcolor="#e581392c"] ; +2 -> 8 ; +9 [label="gini = 0.0\nsamples = 8\nvalue = [[8, 0]\n[0, 8]]", fillcolor="#e58139ff"] ; +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"] ; +1 -> 11 ; +12 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ; +11 -> 12 ; +13 [label="gini = 0.0\nsamples = 5\nvalue = [[0, 5]\n[5, 0]]", fillcolor="#e58139ff"] ; +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 radius <= 17.74\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 texture <= 13.745\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 ; +19 [label="gini = 0.0\nsamples = 4\nvalue = [[0, 4]\n[4, 0]]", fillcolor="#e58139ff"] ; +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"] ; +20 -> 21 ; +22 [label="gini = 0.0\nsamples = 9\nvalue = [[0, 9]\n[9, 0]]", fillcolor="#e58139ff"] ; +21 -> 22 ; +23 [label="gini = 0.0\nsamples = 6\nvalue = [[6, 0]\n[0, 6]]", fillcolor="#e58139ff"] ; +21 -> 23 ; +24 [label="worst smoothness <= 0.096\ngini = 0.015\nsamples = 136\nvalue = [[1, 135]\n[135, 1]]", fillcolor="#e58139f7"] ; +20 -> 24 ; +25 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ; +24 -> 25 ; +26 [label="gini = 0.0\nsamples = 135\nvalue = [[0, 135]\n[135, 0]]", fillcolor="#e58139ff"] ; +24 -> 26 ; +} \ No newline at end of file diff --git a/doc/src/DecisionTrees/DataFiles/cancer.png b/doc/src/DecisionTrees/DataFiles/cancer.png new file mode 100644 index 000000000..2ceb5e1f8 Binary files /dev/null and b/doc/src/DecisionTrees/DataFiles/cancer.png differ diff --git a/doc/src/DecisionTrees/DecisionTrees.do.txt b/doc/src/DecisionTrees/DecisionTrees.do.txt index 44b510e89..abcc176f6 100644 --- a/doc/src/DecisionTrees/DecisionTrees.do.txt +++ b/doc/src/DecisionTrees/DecisionTrees.do.txt @@ -400,67 +400,179 @@ s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. !split -===== The CART (Classification and Regression Tree) algorithm ===== +===== Visualizing the Tree, Classification ===== +!bc pycod +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 -The above functions (gini, entropy and misclassification error) are important components of the so-called CART algorithm. We will discuss this algorithm first before we move on to the information gain algorithm ID3. +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) +!ec + +!split +===== Visualizing the Tree, The Moons ===== +!bc pycod +# 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) +!ec + + +!split +===== 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 | +|-------------------------------------------| + + +!split +===== Simple Python Code to read in Data ===== + +!bc pycod +# Common imports +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +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("ride.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) +display(ridedata) +# Features and targets +X = ridedata.loc[:, ridedata.columns != 'Ride'].values +display(X) +y = ridedata.loc[:, ridedata.columns == 'Ride'].values +display(y) +# Categorical variables to one-hot's +onehotencoder = OneHotEncoder(categories="auto") + +X = ColumnTransformer([("", onehotencoder)]).fit_transform(X) +y.shape + +display(X) +display(y) + +!ec + +!split +===== 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. !bc pycod -from random import seed -from random import randrange -from csv import reader - -# Load a CSV file -def load_csv(filename): - file = open(filename, "rb") - lines = reader(file) - dataset = list(lines) - return dataset - -# Convert string column to float -def str_column_to_float(dataset, column): - for row in dataset: - row[column] = float(row[column].strip()) - -# Split a dataset into k folds -def cross_validation_split(dataset, n_folds): - dataset_split = list() - dataset_copy = list(dataset) - fold_size = int(len(dataset) / n_folds) - for i in range(n_folds): - fold = list() - while len(fold) < fold_size: - index = randrange(len(dataset_copy)) - fold.append(dataset_copy.pop(index)) - dataset_split.append(fold) - return dataset_split - -# Calculate accuracy percentage -def accuracy_metric(actual, predicted): - correct = 0 - for i in range(len(actual)): - if actual[i] == predicted[i]: - correct += 1 - return correct / float(len(actual)) * 100.0 - -# Evaluate an algorithm using a cross validation split -def evaluate_algorithm(dataset, algorithm, n_folds, *args): - folds = cross_validation_split(dataset, n_folds) - scores = list() - for fold in folds: - train_set = list(folds) - train_set.remove(fold) - train_set = sum(train_set, []) - test_set = list() - for row in fold: - row_copy = list(row) - test_set.append(row_copy) - row_copy[-1] = None - predicted = algorithm(train_set, test_set, *args) - actual = [row[-1] for row in fold] - accuracy = accuracy_metric(actual, predicted) - scores.append(accuracy) - return scores - # Split a dataset based on an attribute and an attribute value def test_split(index, value, dataset): left, right = list(), list() @@ -490,7 +602,7 @@ def gini_index(groups, classes): # 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)) @@ -499,84 +611,28 @@ def get_split(dataset): 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} -# Create a terminal node value -def to_terminal(group): - outcomes = [row[-1] for row in group] - return max(set(outcomes), key=outcomes.count) - -# Create child splits for a node or make terminal -def split(node, max_depth, min_size, depth): - left, right = node['groups'] - del(node['groups']) - # check for a no split - if not left or not right: - node['left'] = node['right'] = to_terminal(left + right) - return - # check for max depth - if depth >= max_depth: - node['left'], node['right'] = to_terminal(left), to_terminal(right) - return - # process left child - if len(left) <= min_size: - node['left'] = to_terminal(left) - else: - node['left'] = get_split(left) - split(node['left'], max_depth, min_size, depth+1) - # process right child - if len(right) <= min_size: - node['right'] = to_terminal(right) - else: - node['right'] = get_split(right) - split(node['right'], max_depth, min_size, depth+1) - -# Build a decision tree -def build_tree(train, max_depth, min_size): - root = get_split(train) - split(root, max_depth, min_size, 1) - return root - -# Make a prediction with a decision tree -def predict(node, row): - if row[node['index']] < node['value']: - if isinstance(node['left'], dict): - return predict(node['left'], row) - else: - return node['left'] - else: - if isinstance(node['right'], dict): - return predict(node['right'], row) - else: - return node['right'] - -# Classification and Regression Tree Algorithm -def decision_tree(train, test, max_depth, min_size): - tree = build_tree(train, max_depth, min_size) - predictions = list() - for row in test: - prediction = predict(tree, row) - predictions.append(prediction) - return(predictions) - -# Test CART -seed(1) -# load and prepare data -filename = 'DataFiles/rideclass.csv' -dataset = load_csv(filename) -# convert string attributes to integers -for i in range(len(dataset[0])): - str_column_to_float(dataset, i) -# evaluate algorithm -n_folds = 5 -max_depth = 5 -min_size = 10 -scores = evaluate_algorithm(dataset, decision_tree, n_folds, max_depth, min_size) -print('Scores: %s' % scores) -print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores)))) +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'])) !ec !split @@ -609,10 +665,197 @@ attributes at each step while growing the tree. !split ===== Implementing the ID3 Algorithm ===== -_more text to come here_, material presented during lecture Friday Oct 25. +import re +import math +from collections import deque + +# x is examples in training set +# y is set of attributes +# 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() + !split -===== Cancer Data again now with Decision Trees ===== +===== Cancer Data again now with Decision Trees and other Methods ===== !bc pycod import matplotlib.pyplot as plt import numpy as np @@ -736,7 +979,7 @@ np.random.seed(6) Xs = np.random.rand(100, 2) - 0.5 ys = (Xs[:, 0] > 0).astype(np.float32) * 2 -angle = np.pi / 4 +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) @@ -889,6 +1132,9 @@ general-purpose procedure for reducing the variance of a statistical learning method. +!split +===== More bagging ===== + Bagging typically results in improved accuracy over prediction using a single tree. Unfortunately, however, it can be difficult to interpret the resulting model. Recall that one of the @@ -929,6 +1175,56 @@ plt.show() !ec +!split +===== Bagging Example ===== +!bc pycod +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) + +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(solver="liblinear", random_state=42) +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42) +svm_clf = SVC(gamma="auto", random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='hard') + +voting_clf.fit(X_train, y_train) + +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) + +log_clf = LogisticRegression(solver="liblinear", random_state=42) +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42) +svm_clf = SVC(gamma="auto", probability=True, random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='soft') +voting_clf.fit(X_train, y_train) + +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) + +!ec + + !split ===== Random forests ===== @@ -1113,8 +1409,4 @@ np.sum(y_pred == y_pred_rf) / len(y_pred) !ec -!split -===== Boosting and more ===== -More material to come here. - diff --git a/doc/src/DecisionTrees/cancer.dot b/doc/src/DecisionTrees/Results/FigureFiles/cancer.dot similarity index 85% rename from doc/src/DecisionTrees/cancer.dot rename to doc/src/DecisionTrees/Results/FigureFiles/cancer.dot index a0d5d819c..bf6a8ded3 100644 --- a/doc/src/DecisionTrees/cancer.dot +++ b/doc/src/DecisionTrees/Results/FigureFiles/cancer.dot @@ -10,7 +10,7 @@ edge [fontname=helvetica] ; 2 -> 3 ; 4 [label="gini = 0.0\nsamples = 239\nvalue = [[239, 0]\n[0, 239]]", fillcolor="#e58139ff"] ; 3 -> 4 ; -5 [label="symmetry error <= 0.025\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#e5813913"] ; +5 [label="compactness error <= 0.014\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"] ; 5 -> 6 ; @@ -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="worst texture <= 24.785\ngini = 0.278\nsamples = 6\nvalue = [[1, 5]\n[5, 1]]", fillcolor="#e581396b"] ; +11 [label="mean texture <= 16.22\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 perimeter <= 116.8\ngini = 0.375\nsamples = 16\nvalue = [[12, 4]\n[4, 12]]", fillcolor="#e5813938"] ; +15 [label="worst area <= 964.4\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 concavity <= 0.06\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#e5813955"] ; +17 [label="worst compactness <= 0.126\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 ; diff --git a/doc/src/DecisionTrees/dtcancer.py b/doc/src/DecisionTrees/dtcancer.py index 45d9e5fe1..ee4e677d2 100644 --- a/doc/src/DecisionTrees/dtcancer.py +++ b/doc/src/DecisionTrees/dtcancer.py @@ -1,3 +1,4 @@ +import os from sklearn.datasets import load_breast_cancer from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split @@ -9,6 +10,31 @@ from pydot import graph_from_dot_data import pandas as pd import numpy as np + +# 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') + + cancer = load_breast_cancer() X = pd.DataFrame(cancer.data, columns=cancer.feature_names) print(X) @@ -21,10 +47,11 @@ tree_clf.fit(X_train, y_train) export_graphviz( tree_clf, - out_file="cancer.dot", + 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) diff --git a/doc/src/DecisionTrees/gini.py b/doc/src/DecisionTrees/gini.py index a393242d7..cf4509b9c 100644 --- a/doc/src/DecisionTrees/gini.py +++ b/doc/src/DecisionTrees/gini.py @@ -41,6 +41,7 @@ def get_split(dataset): b_index, b_value, b_score, b_groups = index, row[index], gini, groups return {'index':b_index, 'value':b_value, 'groups':b_groups} +""" dataset = [[2.771244718,1.784783929,0], [1.728571309,1.169761413,0], [3.678319846,2.81281357,0], @@ -51,5 +52,23 @@ dataset = [[2.771244718,1.784783929,0], [7.444542326,0.476683375,1], [10.12493903,3.234550982,1], [6.642287351,3.319983761,1]] +""" +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'])) + +