2716 lines
173 KiB
HTML
2716 lines
173 KiB
HTML
<!--
|
|
HTML file automatically generated from DocOnce source
|
|
(https://github.com/doconce/doconce/)
|
|
doconce format html week46.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week46 --no_mako
|
|
-->
|
|
<html>
|
|
<head>
|
|
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
|
<meta name="generator" content="DocOnce: https://github.com/doconce/doconce/" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<meta name="description" content="Week 46: Decision Trees, Ensemble methods and Random Forests">
|
|
<title>Week 46: Decision Trees, Ensemble methods and Random Forests</title>
|
|
<style type="text/css">
|
|
/* bloodish style */
|
|
body {
|
|
font-family: Helvetica, Verdana, Arial, Sans-serif;
|
|
color: #404040;
|
|
background: #ffffff;
|
|
}
|
|
h1 { font-size: 1.8em; color: #8A0808; }
|
|
h2 { font-size: 1.6em; color: #8A0808; }
|
|
h3 { font-size: 1.4em; color: #8A0808; }
|
|
h4 { font-size: 1.2em; color: #8A0808; }
|
|
a { color: #8A0808; text-decoration:none; }
|
|
tt { font-family: "Courier New", Courier; }
|
|
p { text-indent: 0px; }
|
|
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
|
|
p.caption { width: 80%; font-style: normal; text-align: left; }
|
|
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa; }div.highlight {
|
|
border: 1px solid #cfcfcf;
|
|
border-radius: 2px;
|
|
line-height: 1.21429em;
|
|
}
|
|
div.cell {
|
|
width: 100%;
|
|
padding: 5px 5px 5px 0;
|
|
margin: 0;
|
|
outline: none;
|
|
}
|
|
div.input {
|
|
page-break-inside: avoid;
|
|
box-orient: horizontal;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: row;
|
|
align-items: stretch;
|
|
}
|
|
div.inner_cell {
|
|
box-orient: vertical;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: stretch;
|
|
box-flex: 1;
|
|
flex: 1;
|
|
}
|
|
div.input_area {
|
|
border: 1px solid #cfcfcf;
|
|
border-radius: 4px;
|
|
background: #f7f7f7;
|
|
line-height: 1.21429em;
|
|
}
|
|
div.input_area > div.highlight {
|
|
margin: .4em;
|
|
border: none;
|
|
padding: 0;
|
|
background-color: transparent;
|
|
}
|
|
div.output_wrapper {
|
|
position: relative;
|
|
box-orient: vertical;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: stretch;
|
|
}
|
|
.output {
|
|
box-orient: vertical;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: stretch;
|
|
}
|
|
div.output_area {
|
|
padding: 0;
|
|
page-break-inside: avoid;
|
|
box-orient: horizontal;
|
|
box-align: stretch;
|
|
display: flex;
|
|
flex-direction: row;
|
|
align-items: stretch;
|
|
}
|
|
div.output_subarea {
|
|
padding: .4em .4em 0 .4em;
|
|
box-flex: 1;
|
|
flex: 1;
|
|
}
|
|
div.output_text {
|
|
text-align: left;
|
|
color: #000;
|
|
line-height: 1.21429em;
|
|
}
|
|
.alert-text-small { font-size: 80%; }
|
|
.alert-text-large { font-size: 130%; }
|
|
.alert-text-normal { font-size: 90%; }
|
|
.alert {
|
|
padding:8px 35px 8px 14px; margin-bottom:18px;
|
|
text-shadow:0 1px 0 rgba(255,255,255,0.5);
|
|
border:1px solid #bababa;
|
|
border-radius: 4px;
|
|
-webkit-border-radius: 4px;
|
|
-moz-border-radius: 4px;
|
|
color: #555;
|
|
background-color: #f8f8f8;
|
|
background-position: 10px 5px;
|
|
background-repeat: no-repeat;
|
|
background-size: 38px;
|
|
padding-left: 55px;
|
|
width: 75%;
|
|
}
|
|
.alert-block {padding-top:14px; padding-bottom:14px}
|
|
.alert-block > p, .alert-block > ul {margin-bottom:1em}
|
|
.alert li {margin-top: 1em}
|
|
.alert-block p+p {margin-top:5px}
|
|
.alert-notice { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_notice.png); }
|
|
.alert-summary { background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_summary.png); }
|
|
.alert-warning { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_warning.png); }
|
|
.alert-question {background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_question.png); }
|
|
div { text-align: justify; text-justify: inter-word; }
|
|
.tab {
|
|
padding-left: 1.5em;
|
|
}
|
|
div.toc p,a {
|
|
line-height: 1.3;
|
|
margin-top: 1.1;
|
|
margin-bottom: 1.1;
|
|
}
|
|
</style>
|
|
</head>
|
|
|
|
<!-- tocinfo
|
|
{'highest level': 2,
|
|
'sections': [('Plan for week 46', 2, None, 'plan-for-week-46'),
|
|
('Decision trees, overarching aims',
|
|
2,
|
|
None,
|
|
'decision-trees-overarching-aims'),
|
|
('Basics of a tree', 2, None, 'basics-of-a-tree'),
|
|
('A typical Decision Tree with its pertinent Jargon, '
|
|
'Classification Problem',
|
|
2,
|
|
None,
|
|
'a-typical-decision-tree-with-its-pertinent-jargon-classification-problem'),
|
|
('General Features', 2, None, 'general-features'),
|
|
('How do we set it up?', 2, None, 'how-do-we-set-it-up'),
|
|
('Decision trees and Regression',
|
|
2,
|
|
None,
|
|
'decision-trees-and-regression'),
|
|
('Building a tree, regression',
|
|
2,
|
|
None,
|
|
'building-a-tree-regression'),
|
|
('A top-down approach, recursive binary splitting',
|
|
2,
|
|
None,
|
|
'a-top-down-approach-recursive-binary-splitting'),
|
|
('Making a tree', 2, None, 'making-a-tree'),
|
|
('Pruning the tree', 2, None, 'pruning-the-tree'),
|
|
('Cost complexity pruning', 2, None, 'cost-complexity-pruning'),
|
|
('Schematic Regression Procedure',
|
|
2,
|
|
None,
|
|
'schematic-regression-procedure'),
|
|
('A Classification Tree', 2, None, 'a-classification-tree'),
|
|
('Growing a classification tree',
|
|
2,
|
|
None,
|
|
'growing-a-classification-tree'),
|
|
('Classification tree, how to split nodes',
|
|
2,
|
|
None,
|
|
'classification-tree-how-to-split-nodes'),
|
|
('Visualizing the Tree, Classification',
|
|
2,
|
|
None,
|
|
'visualizing-the-tree-classification'),
|
|
('Visualizing the Tree, The Moons',
|
|
2,
|
|
None,
|
|
'visualizing-the-tree-the-moons'),
|
|
('Other ways of visualizing the trees',
|
|
2,
|
|
None,
|
|
'other-ways-of-visualizing-the-trees'),
|
|
('Printing out as text', 2, None, 'printing-out-as-text'),
|
|
('Algorithms for Setting up Decision Trees',
|
|
2,
|
|
None,
|
|
'algorithms-for-setting-up-decision-trees'),
|
|
('The CART algorithm for Classification',
|
|
2,
|
|
None,
|
|
'the-cart-algorithm-for-classification'),
|
|
('The CART algorithm for Regression',
|
|
2,
|
|
None,
|
|
'the-cart-algorithm-for-regression'),
|
|
('Why binary splits?', 2, None, 'why-binary-splits'),
|
|
('Computing a Tree using the Gini Index',
|
|
2,
|
|
None,
|
|
'computing-a-tree-using-the-gini-index'),
|
|
('The Table', 2, None, 'the-table'),
|
|
('Computing the various Gini Indices',
|
|
2,
|
|
None,
|
|
'computing-the-various-gini-indices'),
|
|
('Computing the various Gini Indices, Hours slept',
|
|
2,
|
|
None,
|
|
'computing-the-various-gini-indices-hours-slept'),
|
|
('Computing the various Gini Indices, Hours studied',
|
|
2,
|
|
None,
|
|
'computing-the-various-gini-indices-hours-studied'),
|
|
('A possible code using Scikit-Learn',
|
|
2,
|
|
None,
|
|
'a-possible-code-using-scikit-learn'),
|
|
('Further example: Computing the Gini index',
|
|
2,
|
|
None,
|
|
'further-example-computing-the-gini-index'),
|
|
('Simple Python Code to read in Data and perform Classification',
|
|
2,
|
|
None,
|
|
'simple-python-code-to-read-in-data-and-perform-classification'),
|
|
('Computing the Gini Factor',
|
|
2,
|
|
None,
|
|
'computing-the-gini-factor'),
|
|
('Regression trees', 2, None, 'regression-trees'),
|
|
('Final regressor code', 2, None, 'final-regressor-code'),
|
|
('Pros and cons of trees, pros',
|
|
2,
|
|
None,
|
|
'pros-and-cons-of-trees-pros'),
|
|
('Disadvantages', 2, None, 'disadvantages'),
|
|
('Ensemble Methods: From a Single Tree to Many Trees and Extreme '
|
|
'Boosting, Meet the Jungle of Methods',
|
|
2,
|
|
None,
|
|
'ensemble-methods-from-a-single-tree-to-many-trees-and-extreme-boosting-meet-the-jungle-of-methods'),
|
|
('An Overview of Ensemble Methods',
|
|
2,
|
|
None,
|
|
'an-overview-of-ensemble-methods'),
|
|
('Why Voting?', 2, None, 'why-voting'),
|
|
('Tossing coins', 2, None, 'tossing-coins'),
|
|
('Standard imports first', 2, None, 'standard-imports-first'),
|
|
('Simple Voting Example, head or tail',
|
|
2,
|
|
None,
|
|
'simple-voting-example-head-or-tail'),
|
|
('Using the Voting Classifier',
|
|
2,
|
|
None,
|
|
'using-the-voting-classifier'),
|
|
('Voting and Bagging', 2, None, 'voting-and-bagging'),
|
|
('Bagging', 2, None, 'bagging'),
|
|
('More bagging', 2, None, 'more-bagging'),
|
|
('Making your own Bootstrap: Changing the Level of the Decision '
|
|
'Tree',
|
|
2,
|
|
None,
|
|
'making-your-own-bootstrap-changing-the-level-of-the-decision-tree'),
|
|
('Random forests', 2, None, 'random-forests'),
|
|
('Random Forest Algorithm', 2, None, 'random-forest-algorithm'),
|
|
('Random Forests Compared with other Methods on the Cancer Data',
|
|
2,
|
|
None,
|
|
'random-forests-compared-with-other-methods-on-the-cancer-data'),
|
|
('Compare Bagging on Trees with Random Forests',
|
|
2,
|
|
None,
|
|
'compare-bagging-on-trees-with-random-forests'),
|
|
("Boosting, a Bird's Eye View",
|
|
2,
|
|
None,
|
|
'boosting-a-bird-s-eye-view'),
|
|
('What is boosting? Additive Modelling/Iterative Fitting',
|
|
2,
|
|
None,
|
|
'what-is-boosting-additive-modelling-iterative-fitting'),
|
|
('Iterative Fitting, Regression and Squared-error Cost Function',
|
|
2,
|
|
None,
|
|
'iterative-fitting-regression-and-squared-error-cost-function'),
|
|
('Squared-Error Example and Iterative Fitting',
|
|
2,
|
|
None,
|
|
'squared-error-example-and-iterative-fitting'),
|
|
('Iterative Fitting, Classification and AdaBoost',
|
|
2,
|
|
None,
|
|
'iterative-fitting-classification-and-adaboost'),
|
|
('Adaptive Boosting, AdaBoost',
|
|
2,
|
|
None,
|
|
'adaptive-boosting-adaboost'),
|
|
('Building up AdaBoost', 2, None, 'building-up-adaboost'),
|
|
('Adaptive boosting: AdaBoost, Basic Algorithm',
|
|
2,
|
|
None,
|
|
'adaptive-boosting-adaboost-basic-algorithm'),
|
|
('Basic Steps of AdaBoost', 2, None, 'basic-steps-of-adaboost'),
|
|
('AdaBoost Examples', 2, None, 'adaboost-examples')]}
|
|
end of tocinfo -->
|
|
|
|
<body>
|
|
|
|
|
|
|
|
<script type="text/x-mathjax-config">
|
|
MathJax.Hub.Config({
|
|
TeX: {
|
|
equationNumbers: { autoNumber: "AMS" },
|
|
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
|
|
}
|
|
});
|
|
</script>
|
|
<script type="text/javascript" async
|
|
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
|
|
</script>
|
|
|
|
|
|
<!-- ------------------- main content ---------------------- -->
|
|
<center>
|
|
<h1>Week 46: Decision Trees, Ensemble methods and Random Forests</h1>
|
|
</center> <!-- document title -->
|
|
|
|
<!-- author(s): Morten Hjorth-Jensen -->
|
|
<center>
|
|
<b>Morten Hjorth-Jensen</b> [1, 2]
|
|
</center>
|
|
<!-- institution(s) -->
|
|
<center>
|
|
[1] <b>Department of Physics, University of Oslo</b>
|
|
</center>
|
|
<center>
|
|
[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b>
|
|
</center>
|
|
<br>
|
|
<center>
|
|
<h4>Week 46, November 11-15</h4>
|
|
</center> <!-- date -->
|
|
<br>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="plan-for-week-46">Plan for week 46 </h2>
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Lab sessions on Tuesday and Wednesday</b>
|
|
<p>
|
|
<ol>
|
|
<li> Work on and discussions of project 3</li>
|
|
</ol>
|
|
</div>
|
|
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Material for the lecture on Monday November 11, 2024</b>
|
|
<p>
|
|
<p>Basics of decision trees, classification and regression algorithms and ensemble models </p>
|
|
<ol>
|
|
<li> Readings and Videos:
|
|
<ol type="a"></li>
|
|
<li> Lecture notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week46/ipynb/week46.ipynb" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week46/ipynb/week46.ipynb</tt></a></li>
|
|
<li> Video of lecture at <a href="https://youtu.be/TfRKUfdJwB4" target="_blank"><tt>https://youtu.be/TfRKUfdJwB4</tt></a></li>
|
|
<li> Whiteboard notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember11.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember11.pdf</tt></a></li>
|
|
<li> Video on Decision trees at <a href="https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn" target="_blank"><tt>https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn</tt></a></li>
|
|
<li> Decision Trees: Rashcka et al chapter 3 pages 86-98, and chapter 7 on Ensemble methods, Voting and Bagging and Gradient Boosting. See also lecture from STK-IN4300, lecture 7 at <a href="https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf" target="_blank"><tt>https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf</tt></a>.</li>
|
|
</ol>
|
|
</ol>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="decision-trees-overarching-aims">Decision trees, overarching aims </h2>
|
|
|
|
<p>We start here with the most basic algorithm, the so-called decision
|
|
tree. With this basic algorithm we can in turn build more complex
|
|
networks, spanning from homogeneous and heterogenous forests (bagging,
|
|
random forests and more) to one of the most popular supervised
|
|
algorithms nowadays, the extreme gradient boosting, or just
|
|
XGBoost. But let us start with the simplest possible ingredient.
|
|
</p>
|
|
|
|
<p>Decision trees are supervised learning algorithms used for both,
|
|
classification and regression tasks.
|
|
</p>
|
|
|
|
<p>The main idea of decision trees
|
|
is to find those descriptive features which contain the most
|
|
<b>information</b> regarding the target feature and then split the dataset
|
|
along the values of these features such that the target feature values
|
|
for the resulting underlying datasets are as pure as possible.
|
|
</p>
|
|
|
|
<p>The descriptive features which reproduce best the target/output features are normally said
|
|
to be the most informative ones. The process of finding the <b>most
|
|
informative</b> feature is done until we accomplish a stopping criteria
|
|
where we then finally end up in so called <b>leaf nodes</b>.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="basics-of-a-tree">Basics of a tree </h2>
|
|
|
|
<p>A decision tree is typically divided into a <b>root node</b>, the <b>interior nodes</b>,
|
|
and the final <b>leaf nodes</b> or just <b>leaves</b>. These entities are then connected by so-called <b>branches</b>.
|
|
</p>
|
|
|
|
<p>The leaf nodes
|
|
contain the predictions we will make for new query instances presented
|
|
to our trained model. This is possible since the model has
|
|
learned the underlying structure of the training data and hence can,
|
|
given some assumptions, make predictions about the target feature value
|
|
(class) of unseen query instances.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="a-typical-decision-tree-with-its-pertinent-jargon-classification-problem">A typical Decision Tree with its pertinent Jargon, Classification Problem </h2>
|
|
|
|
<br/><br/>
|
|
<center>
|
|
<p><img src="DataFiles/cancer.png" width="600" align="bottom"></p>
|
|
</center>
|
|
<br/><br/>
|
|
|
|
<p>This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using <b>Scikit-Learn</b>'s decision tree classifier. Here we have used the so-called <b>gini</b> index (see below) to split the various branches.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="general-features">General Features </h2>
|
|
|
|
<p>The overarching approach to decision trees is a top-down approach.</p>
|
|
|
|
<ul>
|
|
<li> A leaf provides the classification of a given instance.</li>
|
|
<li> A node specifies a test of some attribute of the instance.</li>
|
|
<li> A branch corresponds to a possible values of an attribute.</li>
|
|
<li> An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.</li>
|
|
</ul>
|
|
<p>This process is then repeated for the subtree rooted at the new
|
|
node.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="how-do-we-set-it-up">How do we set it up? </h2>
|
|
|
|
<p>In simplified terms, the process of training a decision tree and
|
|
predicting the target features of query instances is as follows:
|
|
</p>
|
|
|
|
<ol>
|
|
<li> Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature</li>
|
|
<li> Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process</li>
|
|
<li> Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the <em>predictions</em> we want to make for new query instances</li>
|
|
<li> Show query instances to the tree and run down the tree until we arrive at leaf nodes</li>
|
|
</ol>
|
|
<p>Then we are essentially done!</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="decision-trees-and-regression">Decision trees and Regression </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> PolynomialFeatures
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
|
|
|
|
steps<span style="color: #666666">=250</span>
|
|
|
|
distance<span style="color: #666666">=0</span>
|
|
x<span style="color: #666666">=0</span>
|
|
distance_list<span style="color: #666666">=</span>[]
|
|
steps_list<span style="color: #666666">=</span>[]
|
|
<span style="color: #008000; font-weight: bold">while</span> x<span style="color: #666666"><</span>steps:
|
|
distance<span style="color: #666666">+=</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randint(<span style="color: #666666">-1</span>,<span style="color: #666666">2</span>)
|
|
distance_list<span style="color: #666666">.</span>append(distance)
|
|
x<span style="color: #666666">+=1</span>
|
|
steps_list<span style="color: #666666">.</span>append(x)
|
|
plt<span style="color: #666666">.</span>plot(steps_list,distance_list, color<span style="color: #666666">=</span><span style="color: #BA2121">'green'</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"Random Walk Data"</span>)
|
|
|
|
steps_list<span style="color: #666666">=</span>np<span style="color: #666666">.</span>asarray(steps_list)
|
|
distance_list<span style="color: #666666">=</span>np<span style="color: #666666">.</span>asarray(distance_list)
|
|
|
|
X<span style="color: #666666">=</span>steps_list[:,np<span style="color: #666666">.</span>newaxis]
|
|
|
|
<span style="color: #408080; font-style: italic">#Polynomial fits</span>
|
|
|
|
<span style="color: #408080; font-style: italic">#Degree 2</span>
|
|
poly_features<span style="color: #666666">=</span>PolynomialFeatures(degree<span style="color: #666666">=2</span>, include_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
|
X_poly<span style="color: #666666">=</span>poly_features<span style="color: #666666">.</span>fit_transform(X)
|
|
|
|
lin_reg<span style="color: #666666">=</span>LinearRegression()
|
|
poly_fit<span style="color: #666666">=</span>lin_reg<span style="color: #666666">.</span>fit(X_poly,distance_list)
|
|
b<span style="color: #666666">=</span>lin_reg<span style="color: #666666">.</span>coef_
|
|
c<span style="color: #666666">=</span>lin_reg<span style="color: #666666">.</span>intercept_
|
|
<span style="color: #008000">print</span> (<span style="color: #BA2121">"2nd degree coefficients:"</span>)
|
|
<span style="color: #008000">print</span> (<span style="color: #BA2121">"zero power: "</span>,c)
|
|
<span style="color: #008000">print</span> (<span style="color: #BA2121">"first power: "</span>, b[<span style="color: #666666">0</span>])
|
|
<span style="color: #008000">print</span> (<span style="color: #BA2121">"second power: "</span>,b[<span style="color: #666666">1</span>])
|
|
|
|
z <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, steps, <span style="color: #666666">.01</span>)
|
|
z_mod<span style="color: #666666">=</span>b[<span style="color: #666666">1</span>]<span style="color: #666666">*</span>z<span style="color: #666666">**2+</span>b[<span style="color: #666666">0</span>]<span style="color: #666666">*</span>z<span style="color: #666666">+</span>c
|
|
|
|
fit_mod<span style="color: #666666">=</span>b[<span style="color: #666666">1</span>]<span style="color: #666666">*</span>X<span style="color: #666666">**2+</span>b[<span style="color: #666666">0</span>]<span style="color: #666666">*</span>X<span style="color: #666666">+</span>c
|
|
plt<span style="color: #666666">.</span>plot(z, z_mod, color<span style="color: #666666">=</span><span style="color: #BA2121">'r'</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"2nd Degree Fit"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Polynomial Regression"</span>)
|
|
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"Steps"</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"Distance"</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">#Degree 10</span>
|
|
poly_features10<span style="color: #666666">=</span>PolynomialFeatures(degree<span style="color: #666666">=10</span>, include_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
|
X_poly10<span style="color: #666666">=</span>poly_features10<span style="color: #666666">.</span>fit_transform(X)
|
|
|
|
poly_fit10<span style="color: #666666">=</span>lin_reg<span style="color: #666666">.</span>fit(X_poly10,distance_list)
|
|
|
|
y_plot<span style="color: #666666">=</span>poly_fit10<span style="color: #666666">.</span>predict(X_poly10)
|
|
plt<span style="color: #666666">.</span>plot(X, y_plot, color<span style="color: #666666">=</span><span style="color: #BA2121">'black'</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"10th Degree Fit"</span>)
|
|
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
|
|
<span style="color: #408080; font-style: italic">#Decision Tree Regression</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
|
|
regr_1<span style="color: #666666">=</span>DecisionTreeRegressor(max_depth<span style="color: #666666">=2</span>)
|
|
regr_2<span style="color: #666666">=</span>DecisionTreeRegressor(max_depth<span style="color: #666666">=5</span>)
|
|
regr_3<span style="color: #666666">=</span>DecisionTreeRegressor(max_depth<span style="color: #666666">=7</span>)
|
|
regr_1<span style="color: #666666">.</span>fit(X, distance_list)
|
|
regr_2<span style="color: #666666">.</span>fit(X, distance_list)
|
|
regr_3<span style="color: #666666">.</span>fit(X, distance_list)
|
|
|
|
X_test <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0.0</span>, steps, <span style="color: #666666">0.01</span>)[:, np<span style="color: #666666">.</span>newaxis]
|
|
y_1 <span style="color: #666666">=</span> regr_1<span style="color: #666666">.</span>predict(X_test)
|
|
y_2 <span style="color: #666666">=</span> regr_2<span style="color: #666666">.</span>predict(X_test)
|
|
y_3<span style="color: #666666">=</span>regr_3<span style="color: #666666">.</span>predict(X_test)
|
|
|
|
<span style="color: #408080; font-style: italic"># Plot the results</span>
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>scatter(X, distance_list, s<span style="color: #666666">=2.5</span>, c<span style="color: #666666">=</span><span style="color: #BA2121">"black"</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"data"</span>)
|
|
plt<span style="color: #666666">.</span>plot(X_test, y_1, color<span style="color: #666666">=</span><span style="color: #BA2121">"red"</span>,
|
|
label<span style="color: #666666">=</span><span style="color: #BA2121">"max_depth=2"</span>, linewidth<span style="color: #666666">=2</span>)
|
|
plt<span style="color: #666666">.</span>plot(X_test, y_2, color<span style="color: #666666">=</span><span style="color: #BA2121">"green"</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"max_depth=5"</span>, linewidth<span style="color: #666666">=2</span>)
|
|
plt<span style="color: #666666">.</span>plot(X_test, y_3, color<span style="color: #666666">=</span><span style="color: #BA2121">"m"</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"max_depth=7"</span>, linewidth<span style="color: #666666">=2</span>)
|
|
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"Data"</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"Darget"</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Decision Tree Regression"</span>)
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="building-a-tree-regression">Building a tree, regression </h2>
|
|
|
|
<p>There are mainly two steps</p>
|
|
<ol>
|
|
<li> We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).</li>
|
|
<li> For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).</li>
|
|
</ol>
|
|
<p>How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
|
|
regions could have any shape. However, we choose to divide the
|
|
predictor space into high-dimensional rectangles, or boxes, for
|
|
simplicity and for ease of interpretation of the resulting predictive
|
|
model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
|
|
MSE, given by
|
|
</p>
|
|
|
|
$$
|
|
\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
|
|
$$
|
|
|
|
<p>where \( \overline{y}_{R_j} \) is the mean response for the training observations
|
|
within box \( j \).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="a-top-down-approach-recursive-binary-splitting">A top-down approach, recursive binary splitting </h2>
|
|
|
|
<p>Unfortunately, it is computationally infeasible to consider every
|
|
possible partition of the feature space into \( J \) boxes. The common
|
|
strategy is to take a top-down approach
|
|
</p>
|
|
|
|
<p>The approach is top-down because it begins at the top of the tree (all
|
|
observations belong to a single region) and then successively splits
|
|
the predictor space; each split is indicated via two new branches
|
|
further down on the tree. It is greedy because at each step of the
|
|
tree-building process, the best split is made at that particular step,
|
|
rather than looking ahead and picking a split that will lead to a
|
|
better tree in some future step.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="making-a-tree">Making a tree </h2>
|
|
|
|
<p>In order to implement the recursive binary splitting we start by selecting
|
|
the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
|
|
</p>
|
|
$$
|
|
\left\{X\vert x_j < s\right\},
|
|
$$
|
|
|
|
<p>and</p>
|
|
$$
|
|
\left\{X\vert x_j \geq s\right\},
|
|
$$
|
|
|
|
<p>so that we obtain the lowest MSE, that is</p>
|
|
$$
|
|
\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
|
|
$$
|
|
|
|
<p>which we want to minimize by considering all predictors
|
|
\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
|
|
each predictor. These values could be determined by randomly assigned
|
|
numbers or by starting at the midpoint and then proceed till we find
|
|
an optimal value.
|
|
</p>
|
|
|
|
<p>For any \( j \) and \( s \), we define the pair of half-planes where
|
|
\( \overline{y}_{R_1} \) is the mean response for the training
|
|
observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
|
|
response for the training observations in \( R_2(j,s) \).
|
|
</p>
|
|
|
|
<p>Finding the values of \( j \) and \( s \) that minimize the above equation can be
|
|
done quite quickly, especially when the number of features \( p \) is not
|
|
too large.
|
|
</p>
|
|
|
|
<p>Next, we repeat the process, looking
|
|
for the best predictor and best cutpoint in order to split the data
|
|
further so as to minimize the MSE within each of the resulting
|
|
regions. However, this time, instead of splitting the entire predictor
|
|
space, we split one of the two previously identified regions. We now
|
|
have three regions. Again, we look to split one of these three regions
|
|
further, so as to minimize the MSE. The process continues until a
|
|
stopping criterion is reached; for instance, we may continue until no
|
|
region contains more than five observations.
|
|
</p>
|
|
|
|
<!-- !split -->
|
|
<h2 id="pruning-the-tree">Pruning the tree </h2>
|
|
|
|
<p>The above procedure is rather straightforward, but leads often to
|
|
overfitting and unnecessarily large and complicated trees. The basic
|
|
idea is to grow a large tree \( T_0 \) and then prune it back in order to
|
|
obtain a subtree. A smaller tree with fewer splits (fewer regions) can
|
|
lead to smaller variance and better interpretation at the cost of a
|
|
little more bias.
|
|
</p>
|
|
|
|
<p>The so-called Cost complexity pruning algorithm gives us a
|
|
way to do just this. Rather than considering every possible subtree,
|
|
we consider a sequence of trees indexed by a nonnegative tuning
|
|
parameter \( \alpha \).
|
|
</p>
|
|
|
|
<p>Read more at the following <a href="https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py" target="_blank">Scikit-Learn link on pruning</a>.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="cost-complexity-pruning">Cost complexity pruning </h2>
|
|
|
|
<p>For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that</p>
|
|
$$
|
|
\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
|
|
$$
|
|
|
|
<p>is as small as possible. Here \( \overline{T} \) is
|
|
the number of terminal nodes of the tree \( T \) , \( R_m \) is the
|
|
rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node.
|
|
</p>
|
|
|
|
<p>The tuning parameter \( \alpha \) controls a trade-off between the subtree’s
|
|
complexity and its fit to the training data. When \( \alpha = 0 \), then the
|
|
subtree \( T \) will simply equal \( T_0 \),
|
|
because then the above equation just measures the
|
|
training error.
|
|
However, as \( \alpha \) increases, there is a price to pay for
|
|
having a tree with many terminal nodes. The above equation will
|
|
tend to be minimized for a smaller subtree.
|
|
</p>
|
|
|
|
<p>It turns out that as we increase \( \alpha \) from zero
|
|
branches get pruned from the tree in a nested and predictable fashion,
|
|
so obtaining the whole sequence of subtrees as a function of \( \alpha \) is
|
|
easy. We can select a value of \( \alpha \) using a validation set or using
|
|
cross-validation. We then return to the full data set and obtain the
|
|
subtree corresponding to \( \alpha \).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="schematic-regression-procedure">Schematic Regression Procedure </h2>
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Building a Regression Tree</b>
|
|
<p>
|
|
|
|
<ol>
|
|
<li> Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.</li>
|
|
<li> Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).</li>
|
|
<li> Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:</li>
|
|
<ul>
|
|
<li> repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.</li>
|
|
<li> Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).</li>
|
|
<li> Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.</li>
|
|
</ul>
|
|
<li> Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).</li>
|
|
</ol>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="a-classification-tree">A Classification Tree </h2>
|
|
|
|
<p>A classification tree is very similar to a regression tree, except
|
|
that it is used to predict a qualitative response rather than a
|
|
quantitative one. Recall that for a regression tree, the predicted
|
|
response for an observation is given by the mean response of the
|
|
training observations that belong to the same terminal node. In
|
|
contrast, for a classification tree, we predict that each observation
|
|
belongs to the most commonly occurring class of training observations
|
|
in the region to which it belongs. In interpreting the results of a
|
|
classification tree, we are often interested not only in the class
|
|
prediction corresponding to a particular terminal node region, but
|
|
also in the class proportions among the training observations that
|
|
fall into that region.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="growing-a-classification-tree">Growing a classification tree </h2>
|
|
|
|
<p>The task of growing a
|
|
classification tree is quite similar to the task of growing a
|
|
regression tree. Just as in the regression setting, we use recursive
|
|
binary splitting to grow a classification tree. However, in the
|
|
classification setting, the MSE cannot be used as a criterion for making
|
|
the binary splits. A natural alternative to MSE is the <b>classification
|
|
error rate</b>. Since we plan to assign an observation in a given region
|
|
to the most commonly occurring error rate class of training
|
|
observations in that region, the classification error rate is simply
|
|
the fraction of the training observations in that region that do not
|
|
belong to the most common class.
|
|
</p>
|
|
|
|
<p>When building a classification tree, either the Gini index or the
|
|
entropy are typically used to evaluate the quality of a particular
|
|
split, since these two approaches are more sensitive to node purity
|
|
than is the classification error rate.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="classification-tree-how-to-split-nodes">Classification tree, how to split nodes </h2>
|
|
|
|
<p>If our targets are the outcome of a classification process that takes
|
|
for example \( k=1,2,\dots,K \) values, the only thing we need to think of
|
|
is to set up the splitting criteria for each node.
|
|
</p>
|
|
|
|
<p>We define a PDF \( p_{mk} \) that represents the number of observations of
|
|
a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
|
|
this likelihood function in terms of the proportion \( I(y_i=k) \) of
|
|
observations of this class in the region \( R_m \) as
|
|
</p>
|
|
|
|
$$
|
|
p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
|
|
$$
|
|
|
|
<p>We let \( p_{mk} \) represent the majority class of observations in region
|
|
\( m \). The three most common ways of splitting a node are given by
|
|
</p>
|
|
|
|
<ul>
|
|
<li> Misclassification error</li>
|
|
</ul>
|
|
$$
|
|
p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}.
|
|
$$
|
|
|
|
<ul>
|
|
<li> Gini index \( g \)</li>
|
|
</ul>
|
|
$$
|
|
g = \sum_{k=1}^K p_{mk}(1-p_{mk}).
|
|
$$
|
|
|
|
<ul>
|
|
<li> Information entropy or just entropy \( s \)</li>
|
|
</ul>
|
|
$$
|
|
s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="visualizing-the-tree-classification">Visualizing the Tree, Classification </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> confusion_matrix
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
|
|
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> Image
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
|
|
|
|
cancer <span style="color: #666666">=</span> load_breast_cancer()
|
|
X <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(cancer<span style="color: #666666">.</span>data, columns<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>feature_names)
|
|
<span style="color: #008000">print</span>(X)
|
|
y <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>Categorical<span style="color: #666666">.</span>from_codes(cancer<span style="color: #666666">.</span>target, cancer<span style="color: #666666">.</span>target_names)
|
|
y <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>get_dummies(y)
|
|
<span style="color: #008000">print</span>(y)
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, random_state<span style="color: #666666">=1</span>)
|
|
tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=5</span>)
|
|
tree_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
|
|
export_graphviz(
|
|
tree_clf,
|
|
out_file<span style="color: #666666">=</span><span style="color: #BA2121">"DataFiles/cancer.dot"</span>,
|
|
feature_names<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>feature_names,
|
|
class_names<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>target_names,
|
|
rounded<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
|
|
filled<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>
|
|
)
|
|
cmd <span style="color: #666666">=</span> <span style="color: #BA2121">'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'</span>
|
|
os<span style="color: #666666">.</span>system(cmd)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="visualizing-the-tree-the-moons">Visualizing the Tree, The Moons </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">42</span>)
|
|
X, y <span style="color: #666666">=</span> make_moons(n_samples<span style="color: #666666">=100</span>, noise<span style="color: #666666">=0.25</span>, random_state<span style="color: #666666">=53</span>)
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X,y,random_state<span style="color: #666666">=0</span>)
|
|
tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=5</span>)
|
|
tree_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
|
|
export_graphviz(
|
|
tree_clf,
|
|
out_file<span style="color: #666666">=</span><span style="color: #BA2121">"DataFiles/moons.dot"</span>,
|
|
rounded<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
|
|
filled<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>
|
|
)
|
|
cmd <span style="color: #666666">=</span> <span style="color: #BA2121">'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'</span>
|
|
os<span style="color: #666666">.</span>system(cmd)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="other-ways-of-visualizing-the-trees">Other ways of visualizing the trees </h2>
|
|
|
|
<p><b>Scikit-Learn</b> has also another way to visualize the trees which is very useful, here with the Iris data.</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_iris
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> tree
|
|
X, y <span style="color: #666666">=</span> load_iris(return_X_y<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
tree_clf <span style="color: #666666">=</span> tree<span style="color: #666666">.</span>DecisionTreeClassifier()
|
|
tree_clf <span style="color: #666666">=</span> tree_clf<span style="color: #666666">.</span>fit(X, y)
|
|
<span style="color: #408080; font-style: italic"># and then plot the tree</span>
|
|
tree<span style="color: #666666">.</span>plot_tree(tree_clf)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="printing-out-as-text">Printing out as text </h2>
|
|
|
|
<p>Alternatively, the tree can also be exported in textual format with the function exporttext.
|
|
This method doesn’t require the installation of external libraries and is more compact:
|
|
</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_iris
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_text
|
|
iris <span style="color: #666666">=</span> load_iris()
|
|
decision_tree <span style="color: #666666">=</span> DecisionTreeClassifier(random_state<span style="color: #666666">=0</span>, max_depth<span style="color: #666666">=2</span>)
|
|
decision_tree <span style="color: #666666">=</span> decision_tree<span style="color: #666666">.</span>fit(iris<span style="color: #666666">.</span>data, iris<span style="color: #666666">.</span>target)
|
|
r <span style="color: #666666">=</span> export_text(decision_tree, feature_names<span style="color: #666666">=</span>iris[<span style="color: #BA2121">'feature_names'</span>])
|
|
<span style="color: #008000">print</span>(r)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="algorithms-for-setting-up-decision-trees">Algorithms for Setting up Decision Trees </h2>
|
|
|
|
<p>Two algorithms stand out in the set up of decision trees:</p>
|
|
<ol>
|
|
<li> The CART (Classification And Regression Tree) algorithm for both classification and regression</li>
|
|
<li> The ID3 algorithm based on the computation of the information gain for classification</li>
|
|
</ol>
|
|
<p>We discuss both algorithms with applications here. The popular library
|
|
<b>Scikit-Learn</b> uses the CART algorithm. For classification problems
|
|
you can use either the <b>gini</b> index or the <b>entropy</b> to split a tree
|
|
in two branches.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-cart-algorithm-for-classification">The CART algorithm for Classification </h2>
|
|
|
|
<p>For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \).
|
|
This could be for example a threshold set by a number below a certain circumference of a malign tumor.
|
|
</p>
|
|
|
|
<p>How do we find these two quantities?
|
|
We search for the pair \( (k,t_k) \) that produces the purest subset using for example the <b>gini</b> factor \( G \).
|
|
The cost function it tries to minimize is then
|
|
</p>
|
|
$$
|
|
C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}},
|
|
$$
|
|
|
|
<p>where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \)
|
|
is the number of instances in the left/right subset
|
|
</p>
|
|
|
|
<p>Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets
|
|
and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the
|
|
\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other
|
|
hyperparameters control additional stopping conditions such as the \( min\_samples\_split \),
|
|
\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-cart-algorithm-for-regression">The CART algorithm for Regression </h2>
|
|
|
|
<p>The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the
|
|
training set in a way that minimizes say the <b>gini</b> or <b>entropy</b> impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now
|
|
</p>
|
|
$$
|
|
C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}.
|
|
$$
|
|
|
|
<p>Here the MSE for a specific node is defined as</p>
|
|
$$
|
|
\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2,
|
|
$$
|
|
|
|
<p>with</p>
|
|
$$
|
|
\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i,
|
|
$$
|
|
|
|
<p>the mean value of all observations in a specific node.</p>
|
|
|
|
<p>Without any regularization, the regression task for decision trees,
|
|
just like for classification tasks, is prone to overfitting.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="why-binary-splits">Why binary splits? </h2>
|
|
|
|
<p>It is custom to split to a tree uising binary splits. The reason is
|
|
that multiway splits fragment the data too quickly, leaving
|
|
insufficient data at the next level down. Multiway splits can be
|
|
achieved by a series of binary split and this is normally preferred.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="computing-a-tree-using-the-gini-index">Computing a Tree using the Gini Index </h2>
|
|
|
|
<p>Consider the following example with attributes/features and two
|
|
possible outcomes (classes) for each attribute. Assume we wish to find some
|
|
correlations between the average grade of a student as function of the
|
|
number of hours studied and hours slept. We want also to correlate the
|
|
grade in a given course with the general trend, whether the students
|
|
recently has gotten grades below average or above.
|
|
</p>
|
|
|
|
<p>We have three features/attributes</p>
|
|
<ol>
|
|
<li> Trend of average grades before present course, classified as either below or above the average grade of the whole class</li>
|
|
<li> The number of hours studies, classified again as either higher (more than 3 hours per day) or lower . Here we have used a standard for one \( ECTS \) which is scaled to 25-30 hours of work for a semester which lasts 18 weeks, with 15 weeks of lectures and 3 weeks for exams, assuming a total of 30 ECTS per semester.</li>
|
|
<li> The number of hours slept as high for more than \( 8 \) hours and below for less than 8 hours of sleep, classified again as either high or low</li>
|
|
<li> The final grade whether it is above or below average</li>
|
|
</ol>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="the-table">The Table </h2>
|
|
|
|
<table class="dotable" border="1">
|
|
<thead>
|
|
<tr><th align="center">Grade Trend</th> <th align="center">Hours slept</th> <th align="center">Hours Studied</th> <th align="center">Grade</th> </tr>
|
|
</thead>
|
|
<tbody>
|
|
<tr><td align="center"> Above </td> <td align="center"> Low </td> <td align="center"> High </td> <td align="center"> Above </td> </tr>
|
|
<tr><td align="center"> Below </td> <td align="center"> High </td> <td align="center"> Low </td> <td align="center"> Below </td> </tr>
|
|
<tr><td align="center"> Above </td> <td align="center"> Low </td> <td align="center"> High </td> <td align="center"> Above </td> </tr>
|
|
<tr><td align="center"> Above </td> <td align="center"> High </td> <td align="center"> High </td> <td align="center"> Above </td> </tr>
|
|
<tr><td align="center"> Below </td> <td align="center"> Low </td> <td align="center"> High </td> <td align="center"> Below </td> </tr>
|
|
<tr><td align="center"> Above </td> <td align="center"> Low </td> <td align="center"> Low </td> <td align="center"> Below </td> </tr>
|
|
<tr><td align="center"> Below </td> <td align="center"> High </td> <td align="center"> High </td> <td align="center"> Below </td> </tr>
|
|
<tr><td align="center"> Below </td> <td align="center"> Low </td> <td align="center"> High </td> <td align="center"> Below </td> </tr>
|
|
<tr><td align="center"> Above </td> <td align="center"> Low </td> <td align="center"> Low </td> <td align="center"> Below </td> </tr>
|
|
<tr><td align="center"> Above </td> <td align="center"> High </td> <td align="center"> High </td> <td align="center"> Above </td> </tr>
|
|
</tbody>
|
|
</table>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="computing-the-various-gini-indices">Computing the various Gini Indices </h2>
|
|
|
|
<p>In computations we will translate all classes into numbers. Being
|
|
these binary classes, they can easily be split into ones and zeros.
|
|
</p>
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Gini index for Average trend</b>
|
|
<p>
|
|
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf" target="_blank">See handwritten notes November 3</a>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="computing-the-various-gini-indices-hours-slept">Computing the various Gini Indices, Hours slept </h2>
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Gini index for hour slept</b>
|
|
<p>
|
|
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf" target="_blank">See handwritten notes November 3</a>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="computing-the-various-gini-indices-hours-studied">Computing the various Gini Indices, Hours studied </h2>
|
|
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b>Gini index for hour studied</b>
|
|
<p>
|
|
<a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf" target="_blank">See handwritten notes November 3</a>
|
|
</div>
|
|
|
|
|
|
<p>For final tree, see the above handwritten notes</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="a-possible-code-using-scikit-learn">A possible code using Scikit-Learn </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler, OneHotEncoder
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.compose</span> <span style="color: #008000; font-weight: bold">import</span> ColumnTransformer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> Image
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Where to save the figures and data files</span>
|
|
PROJECT_ROOT_DIR <span style="color: #666666">=</span> <span style="color: #BA2121">"Results"</span>
|
|
FIGURE_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"Results/FigureFiles"</span>
|
|
DATA_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"DataFiles/"</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(PROJECT_ROOT_DIR):
|
|
os<span style="color: #666666">.</span>mkdir(PROJECT_ROOT_DIR)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(FIGURE_ID):
|
|
os<span style="color: #666666">.</span>makedirs(FIGURE_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(DATA_ID):
|
|
os<span style="color: #666666">.</span>makedirs(DATA_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">image_path</span>(fig_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(FIGURE_ID, fig_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">data_path</span>(dat_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(DATA_ID, dat_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
|
|
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">".png"</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">'png'</span>)
|
|
|
|
infile <span style="color: #666666">=</span> <span style="color: #008000">open</span>(data_path(<span style="color: #BA2121">"grades.csv"</span>),<span style="color: #BA2121">'r'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Read the experimental data with Pandas</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
|
|
grades <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>read_csv(infile)
|
|
grades <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(grades)
|
|
display(grades)
|
|
<span style="color: #408080; font-style: italic"># Features and targets</span>
|
|
X <span style="color: #666666">=</span> grades<span style="color: #666666">.</span>loc[:, grades<span style="color: #666666">.</span>columns <span style="color: #666666">!=</span> <span style="color: #BA2121">'Grade'</span>]<span style="color: #666666">.</span>values
|
|
y <span style="color: #666666">=</span> grades<span style="color: #666666">.</span>loc[:, grades<span style="color: #666666">.</span>columns <span style="color: #666666">==</span> <span style="color: #BA2121">'Grade'</span>]<span style="color: #666666">.</span>values
|
|
<span style="color: #008000">print</span>(X)
|
|
<span style="color: #408080; font-style: italic"># Then do a Classification tree</span>
|
|
tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=2</span>)
|
|
tree_clf<span style="color: #666666">.</span>fit(X, y)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Train set accuracy with Decision Tree: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(tree_clf<span style="color: #666666">.</span>score(X,y)))
|
|
<span style="color: #408080; font-style: italic">#transfer to a decision tree graph</span>
|
|
export_graphviz(
|
|
tree_clf,
|
|
out_file<span style="color: #666666">=</span><span style="color: #BA2121">"DataFiles/grade.dot"</span>,
|
|
rounded<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
|
|
filled<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>
|
|
)
|
|
cmd <span style="color: #666666">=</span> <span style="color: #BA2121">'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'</span>
|
|
os<span style="color: #666666">.</span>system(cmd)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="further-example-computing-the-gini-index">Further example: Computing the Gini index </h2>
|
|
|
|
<p>The next 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 <b>outlook</b>, <b>temperature</b>,
|
|
<b>humidity</b> and <b>wind</b>. 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.
|
|
</p>
|
|
|
|
<p>The table here summarizes the various attributes and</p>
|
|
<table class="dotable" border="1">
|
|
<thead>
|
|
<tr><th align="center">Day</th> <th align="center">Outlook </th> <th align="center">Temperature</th> <th align="center">Humidity</th> <th align="center"> Wind </th> <th align="center">Ride</th> </tr>
|
|
</thead>
|
|
<tbody>
|
|
<tr><td align="center"> 1 </td> <td align="center"> Sunny </td> <td align="center"> Hot </td> <td align="center"> High </td> <td align="center"> Weak </td> <td align="center"> 0 </td> </tr>
|
|
<tr><td align="center"> 2 </td> <td align="center"> Sunny </td> <td align="center"> Hot </td> <td align="center"> High </td> <td align="center"> Strong </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 3 </td> <td align="center"> Overcast </td> <td align="center"> Hot </td> <td align="center"> High </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 4 </td> <td align="center"> Rain </td> <td align="center"> Mild </td> <td align="center"> High </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 5 </td> <td align="center"> Rain </td> <td align="center"> Cool </td> <td align="center"> Normal </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 6 </td> <td align="center"> Rain </td> <td align="center"> Cool </td> <td align="center"> Normal </td> <td align="center"> Strong </td> <td align="center"> 0 </td> </tr>
|
|
<tr><td align="center"> 7 </td> <td align="center"> Overcast </td> <td align="center"> Cool </td> <td align="center"> Normal </td> <td align="center"> Strong </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 8 </td> <td align="center"> Sunny </td> <td align="center"> Mild </td> <td align="center"> High </td> <td align="center"> Weak </td> <td align="center"> 0 </td> </tr>
|
|
<tr><td align="center"> 9 </td> <td align="center"> Sunny </td> <td align="center"> Cool </td> <td align="center"> Normal </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 10 </td> <td align="center"> Rain </td> <td align="center"> Mild </td> <td align="center"> Normal </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 11 </td> <td align="center"> Sunny </td> <td align="center"> Mild </td> <td align="center"> Normal </td> <td align="center"> Strong </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 12 </td> <td align="center"> Overcast </td> <td align="center"> Mild </td> <td align="center"> High </td> <td align="center"> Strong </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 13 </td> <td align="center"> Overcast </td> <td align="center"> Hot </td> <td align="center"> Normal </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
|
|
<tr><td align="center"> 14 </td> <td align="center"> Rain </td> <td align="center"> Mild </td> <td align="center"> High </td> <td align="center"> Strong </td> <td align="center"> 0 </td> </tr>
|
|
</tbody>
|
|
</table>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="simple-python-code-to-read-in-data-and-perform-classification">Simple Python Code to read in Data and perform Classification </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler, OneHotEncoder
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.compose</span> <span style="color: #008000; font-weight: bold">import</span> ColumnTransformer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> Image
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Where to save the figures and data files</span>
|
|
PROJECT_ROOT_DIR <span style="color: #666666">=</span> <span style="color: #BA2121">"Results"</span>
|
|
FIGURE_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"Results/FigureFiles"</span>
|
|
DATA_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"DataFiles/"</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(PROJECT_ROOT_DIR):
|
|
os<span style="color: #666666">.</span>mkdir(PROJECT_ROOT_DIR)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(FIGURE_ID):
|
|
os<span style="color: #666666">.</span>makedirs(FIGURE_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(DATA_ID):
|
|
os<span style="color: #666666">.</span>makedirs(DATA_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">image_path</span>(fig_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(FIGURE_ID, fig_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">data_path</span>(dat_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(DATA_ID, dat_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
|
|
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">".png"</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">'png'</span>)
|
|
|
|
infile <span style="color: #666666">=</span> <span style="color: #008000">open</span>(data_path(<span style="color: #BA2121">"rideclass.csv"</span>),<span style="color: #BA2121">'r'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Read the experimental data with Pandas</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
|
|
ridedata <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>read_csv(infile,names <span style="color: #666666">=</span> (<span style="color: #BA2121">'Outlook'</span>,<span style="color: #BA2121">'Temperature'</span>,<span style="color: #BA2121">'Humidity'</span>,<span style="color: #BA2121">'Wind'</span>,<span style="color: #BA2121">'Ride'</span>))
|
|
ridedata <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(ridedata)
|
|
|
|
<span style="color: #408080; font-style: italic"># Features and targets</span>
|
|
X <span style="color: #666666">=</span> ridedata<span style="color: #666666">.</span>loc[:, ridedata<span style="color: #666666">.</span>columns <span style="color: #666666">!=</span> <span style="color: #BA2121">'Ride'</span>]<span style="color: #666666">.</span>values
|
|
y <span style="color: #666666">=</span> ridedata<span style="color: #666666">.</span>loc[:, ridedata<span style="color: #666666">.</span>columns <span style="color: #666666">==</span> <span style="color: #BA2121">'Ride'</span>]<span style="color: #666666">.</span>values
|
|
|
|
<span style="color: #408080; font-style: italic"># Create the encoder.</span>
|
|
encoder <span style="color: #666666">=</span> OneHotEncoder(handle_unknown<span style="color: #666666">=</span><span style="color: #BA2121">"ignore"</span>)
|
|
<span style="color: #408080; font-style: italic"># Assume for simplicity all features are categorical.</span>
|
|
encoder<span style="color: #666666">.</span>fit(X)
|
|
<span style="color: #408080; font-style: italic"># Apply the encoder.</span>
|
|
X <span style="color: #666666">=</span> encoder<span style="color: #666666">.</span>transform(X)
|
|
<span style="color: #008000">print</span>(X)
|
|
<span style="color: #408080; font-style: italic"># Then do a Classification tree</span>
|
|
tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=2</span>)
|
|
tree_clf<span style="color: #666666">.</span>fit(X, y)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Train set accuracy with Decision Tree: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(tree_clf<span style="color: #666666">.</span>score(X,y)))
|
|
<span style="color: #408080; font-style: italic">#transfer to a decision tree graph</span>
|
|
export_graphviz(
|
|
tree_clf,
|
|
out_file<span style="color: #666666">=</span><span style="color: #BA2121">"DataFiles/ride.dot"</span>,
|
|
rounded<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
|
|
filled<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>
|
|
)
|
|
cmd <span style="color: #666666">=</span> <span style="color: #BA2121">'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'</span>
|
|
os<span style="color: #666666">.</span>system(cmd)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="computing-the-gini-factor">Computing the Gini Factor </h2>
|
|
|
|
<p>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.
|
|
</p>
|
|
|
|
<p>In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Split a dataset based on an attribute and an attribute value</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">test_split</span>(index, value, dataset):
|
|
left, right <span style="color: #666666">=</span> <span style="color: #008000">list</span>(), <span style="color: #008000">list</span>()
|
|
<span style="color: #008000; font-weight: bold">for</span> row <span style="color: #AA22FF; font-weight: bold">in</span> dataset:
|
|
<span style="color: #008000; font-weight: bold">if</span> row[index] <span style="color: #666666"><</span> value:
|
|
left<span style="color: #666666">.</span>append(row)
|
|
<span style="color: #008000; font-weight: bold">else</span>:
|
|
right<span style="color: #666666">.</span>append(row)
|
|
<span style="color: #008000; font-weight: bold">return</span> left, right
|
|
|
|
<span style="color: #408080; font-style: italic"># Calculate the Gini index for a split dataset</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">gini_index</span>(groups, classes):
|
|
<span style="color: #408080; font-style: italic"># count all samples at split point</span>
|
|
n_instances <span style="color: #666666">=</span> <span style="color: #008000">float</span>(<span style="color: #008000">sum</span>([<span style="color: #008000">len</span>(group) <span style="color: #008000; font-weight: bold">for</span> group <span style="color: #AA22FF; font-weight: bold">in</span> groups]))
|
|
<span style="color: #408080; font-style: italic"># sum weighted Gini index for each group</span>
|
|
gini <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> group <span style="color: #AA22FF; font-weight: bold">in</span> groups:
|
|
size <span style="color: #666666">=</span> <span style="color: #008000">float</span>(<span style="color: #008000">len</span>(group))
|
|
<span style="color: #408080; font-style: italic"># avoid divide by zero</span>
|
|
<span style="color: #008000; font-weight: bold">if</span> size <span style="color: #666666">==</span> <span style="color: #666666">0</span>:
|
|
<span style="color: #008000; font-weight: bold">continue</span>
|
|
score <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
|
|
<span style="color: #408080; font-style: italic"># score the group based on the score for each class</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> class_val <span style="color: #AA22FF; font-weight: bold">in</span> classes:
|
|
p <span style="color: #666666">=</span> [row[<span style="color: #666666">-1</span>] <span style="color: #008000; font-weight: bold">for</span> row <span style="color: #AA22FF; font-weight: bold">in</span> group]<span style="color: #666666">.</span>count(class_val) <span style="color: #666666">/</span> size
|
|
score <span style="color: #666666">+=</span> p <span style="color: #666666">*</span> p
|
|
<span style="color: #408080; font-style: italic"># weight the group score by its relative size</span>
|
|
gini <span style="color: #666666">+=</span> (<span style="color: #666666">1.0</span> <span style="color: #666666">-</span> score) <span style="color: #666666">*</span> (size <span style="color: #666666">/</span> n_instances)
|
|
<span style="color: #008000; font-weight: bold">return</span> gini
|
|
|
|
<span style="color: #408080; font-style: italic"># Select the best split point for a dataset</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">get_split</span>(dataset):
|
|
class_values <span style="color: #666666">=</span> <span style="color: #008000">list</span>(<span style="color: #008000">set</span>(row[<span style="color: #666666">-1</span>] <span style="color: #008000; font-weight: bold">for</span> row <span style="color: #AA22FF; font-weight: bold">in</span> dataset))
|
|
b_index, b_value, b_score, b_groups <span style="color: #666666">=</span> <span style="color: #666666">999</span>, <span style="color: #666666">999</span>, <span style="color: #666666">999</span>, <span style="color: #008000; font-weight: bold">None</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> index <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">len</span>(dataset[<span style="color: #666666">0</span>])<span style="color: #666666">-1</span>):
|
|
<span style="color: #008000; font-weight: bold">for</span> row <span style="color: #AA22FF; font-weight: bold">in</span> dataset:
|
|
groups <span style="color: #666666">=</span> test_split(index, row[index], dataset)
|
|
gini <span style="color: #666666">=</span> gini_index(groups, class_values)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'X</span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> < </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121"> Gini=</span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">'</span> <span style="color: #666666">%</span> ((index<span style="color: #666666">+1</span>), row[index], gini))
|
|
<span style="color: #008000; font-weight: bold">if</span> gini <span style="color: #666666"><</span> b_score:
|
|
b_index, b_value, b_score, b_groups <span style="color: #666666">=</span> index, row[index], gini, groups
|
|
<span style="color: #008000; font-weight: bold">return</span> {<span style="color: #BA2121">'index'</span>:b_index, <span style="color: #BA2121">'value'</span>:b_value, <span style="color: #BA2121">'groups'</span>:b_groups}
|
|
|
|
dataset <span style="color: #666666">=</span> [[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>],
|
|
[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">2</span>,<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">2</span>,<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>],
|
|
[<span style="color: #666666">1</span>,<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>],
|
|
[<span style="color: #666666">0</span>,<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
|
|
[<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>]]
|
|
|
|
split <span style="color: #666666">=</span> get_split(dataset)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Split: [X</span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> < </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">]'</span> <span style="color: #666666">%</span> ((split[<span style="color: #BA2121">'index'</span>]<span style="color: #666666">+1</span>), split[<span style="color: #BA2121">'value'</span>]))
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="regression-trees">Regression trees </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Quadratic training set + noise</span>
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">42</span>)
|
|
m <span style="color: #666666">=</span> <span style="color: #666666">200</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(m, <span style="color: #666666">1</span>)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4</span> <span style="color: #666666">*</span> (X <span style="color: #666666">-</span> <span style="color: #666666">0.5</span>) <span style="color: #666666">**</span> <span style="color: #666666">2</span>
|
|
y <span style="color: #666666">=</span> y <span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(m, <span style="color: #666666">1</span>) <span style="color: #666666">/</span> <span style="color: #666666">10</span>
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
|
|
|
|
tree_reg <span style="color: #666666">=</span> DecisionTreeRegressor(max_depth<span style="color: #666666">=2</span>, random_state<span style="color: #666666">=42</span>)
|
|
tree_reg<span style="color: #666666">.</span>fit(X, y)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="final-regressor-code">Final regressor code </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
|
|
|
|
tree_reg1 <span style="color: #666666">=</span> DecisionTreeRegressor(random_state<span style="color: #666666">=42</span>, max_depth<span style="color: #666666">=2</span>)
|
|
tree_reg2 <span style="color: #666666">=</span> DecisionTreeRegressor(random_state<span style="color: #666666">=42</span>, max_depth<span style="color: #666666">=3</span>)
|
|
tree_reg1<span style="color: #666666">.</span>fit(X, y)
|
|
tree_reg2<span style="color: #666666">.</span>fit(X, y)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plot_regression_predictions</span>(tree_reg, X, y, axes<span style="color: #666666">=</span>[<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">-0.2</span>, <span style="color: #666666">1</span>], ylabel<span style="color: #666666">=</span><span style="color: #BA2121">"$y$"</span>):
|
|
x1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(axes[<span style="color: #666666">0</span>], axes[<span style="color: #666666">1</span>], <span style="color: #666666">500</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
|
|
y_pred <span style="color: #666666">=</span> tree_reg<span style="color: #666666">.</span>predict(x1)
|
|
plt<span style="color: #666666">.</span>axis(axes)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"$x_1$"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
<span style="color: #008000; font-weight: bold">if</span> ylabel:
|
|
plt<span style="color: #666666">.</span>ylabel(ylabel, fontsize<span style="color: #666666">=18</span>, rotation<span style="color: #666666">=0</span>)
|
|
plt<span style="color: #666666">.</span>plot(X, y, <span style="color: #BA2121">"b."</span>)
|
|
plt<span style="color: #666666">.</span>plot(x1, y_pred, <span style="color: #BA2121">"r.-"</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">r"$\hat</span><span style="color: #BB6688; font-weight: bold">{y}</span><span style="color: #BA2121">$"</span>)
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
|
|
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
|
|
plot_regression_predictions(tree_reg1, X, y)
|
|
<span style="color: #008000; font-weight: bold">for</span> split, style <span style="color: #AA22FF; font-weight: bold">in</span> ((<span style="color: #666666">0.1973</span>, <span style="color: #BA2121">"k-"</span>), (<span style="color: #666666">0.0917</span>, <span style="color: #BA2121">"k--"</span>), (<span style="color: #666666">0.7718</span>, <span style="color: #BA2121">"k--"</span>)):
|
|
plt<span style="color: #666666">.</span>plot([split, split], [<span style="color: #666666">-0.2</span>, <span style="color: #666666">1</span>], style, linewidth<span style="color: #666666">=2</span>)
|
|
plt<span style="color: #666666">.</span>text(<span style="color: #666666">0.21</span>, <span style="color: #666666">0.65</span>, <span style="color: #BA2121">"Depth=0"</span>, fontsize<span style="color: #666666">=15</span>)
|
|
plt<span style="color: #666666">.</span>text(<span style="color: #666666">0.01</span>, <span style="color: #666666">0.2</span>, <span style="color: #BA2121">"Depth=1"</span>, fontsize<span style="color: #666666">=13</span>)
|
|
plt<span style="color: #666666">.</span>text(<span style="color: #666666">0.65</span>, <span style="color: #666666">0.8</span>, <span style="color: #BA2121">"Depth=1"</span>, fontsize<span style="color: #666666">=13</span>)
|
|
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">"upper center"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"max_depth=2"</span>, fontsize<span style="color: #666666">=14</span>)
|
|
|
|
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
|
|
plot_regression_predictions(tree_reg2, X, y, ylabel<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>)
|
|
<span style="color: #008000; font-weight: bold">for</span> split, style <span style="color: #AA22FF; font-weight: bold">in</span> ((<span style="color: #666666">0.1973</span>, <span style="color: #BA2121">"k-"</span>), (<span style="color: #666666">0.0917</span>, <span style="color: #BA2121">"k--"</span>), (<span style="color: #666666">0.7718</span>, <span style="color: #BA2121">"k--"</span>)):
|
|
plt<span style="color: #666666">.</span>plot([split, split], [<span style="color: #666666">-0.2</span>, <span style="color: #666666">1</span>], style, linewidth<span style="color: #666666">=2</span>)
|
|
<span style="color: #008000; font-weight: bold">for</span> split <span style="color: #AA22FF; font-weight: bold">in</span> (<span style="color: #666666">0.0458</span>, <span style="color: #666666">0.1298</span>, <span style="color: #666666">0.2873</span>, <span style="color: #666666">0.9040</span>):
|
|
plt<span style="color: #666666">.</span>plot([split, split], [<span style="color: #666666">-0.2</span>, <span style="color: #666666">1</span>], <span style="color: #BA2121">"k:"</span>, linewidth<span style="color: #666666">=1</span>)
|
|
plt<span style="color: #666666">.</span>text(<span style="color: #666666">0.3</span>, <span style="color: #666666">0.5</span>, <span style="color: #BA2121">"Depth=2"</span>, fontsize<span style="color: #666666">=13</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"max_depth=3"</span>, fontsize<span style="color: #666666">=14</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;">tree_reg1 <span style="color: #666666">=</span> DecisionTreeRegressor(random_state<span style="color: #666666">=42</span>)
|
|
tree_reg2 <span style="color: #666666">=</span> DecisionTreeRegressor(random_state<span style="color: #666666">=42</span>, min_samples_leaf<span style="color: #666666">=10</span>)
|
|
tree_reg1<span style="color: #666666">.</span>fit(X, y)
|
|
tree_reg2<span style="color: #666666">.</span>fit(X, y)
|
|
|
|
x1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">500</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
|
|
y_pred1 <span style="color: #666666">=</span> tree_reg1<span style="color: #666666">.</span>predict(x1)
|
|
y_pred2 <span style="color: #666666">=</span> tree_reg2<span style="color: #666666">.</span>predict(x1)
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
|
|
|
|
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
|
|
plt<span style="color: #666666">.</span>plot(X, y, <span style="color: #BA2121">"b."</span>)
|
|
plt<span style="color: #666666">.</span>plot(x1, y_pred1, <span style="color: #BA2121">"r.-"</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">r"$\hat</span><span style="color: #BB6688; font-weight: bold">{y}</span><span style="color: #BA2121">$"</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">-0.2</span>, <span style="color: #666666">1.1</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"$x_1$"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"$y$"</span>, fontsize<span style="color: #666666">=18</span>, rotation<span style="color: #666666">=0</span>)
|
|
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">"upper center"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"No restrictions"</span>, fontsize<span style="color: #666666">=14</span>)
|
|
|
|
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
|
|
plt<span style="color: #666666">.</span>plot(X, y, <span style="color: #BA2121">"b."</span>)
|
|
plt<span style="color: #666666">.</span>plot(x1, y_pred2, <span style="color: #BA2121">"r.-"</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">r"$\hat</span><span style="color: #BB6688; font-weight: bold">{y}</span><span style="color: #BA2121">$"</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">-0.2</span>, <span style="color: #666666">1.1</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"$x_1$"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"min_samples_leaf=</span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(tree_reg2<span style="color: #666666">.</span>min_samples_leaf), fontsize<span style="color: #666666">=14</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="pros-and-cons-of-trees-pros">Pros and cons of trees, pros </h2>
|
|
|
|
<ul>
|
|
<li> 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)</li>
|
|
<li> Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!</li>
|
|
<li> No feature normalization needed</li>
|
|
<li> Tree models can handle both continuous and categorical data (Classification and Regression Trees)</li>
|
|
<li> Can model nonlinear relationships</li>
|
|
<li> Can model interactions between the different descriptive features</li>
|
|
<li> Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)</li>
|
|
</ul>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="disadvantages">Disadvantages </h2>
|
|
|
|
<ul>
|
|
<li> Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches</li>
|
|
<li> If continuous features are used the tree may become quite large and hence less interpretable</li>
|
|
<li> 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</li>
|
|
<li> 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</li>
|
|
<li> 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.</li>
|
|
<li> If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data</li>
|
|
<li> Features with many levels may be preferred over features with less levels since for them it is <em>more easy</em> 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</li>
|
|
</ul>
|
|
<p>However, by aggregating many decision trees, using methods like
|
|
bagging, random forests, and boosting, the predictive performance of
|
|
trees can be substantially improved.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="ensemble-methods-from-a-single-tree-to-many-trees-and-extreme-boosting-meet-the-jungle-of-methods">Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods </h2>
|
|
|
|
<p>As stated above and seen in many of the examples discussed here about
|
|
a single decision tree, we often end up overfitting our training
|
|
data. This normally means that we have a high variance. Can we reduce
|
|
the variance of a statistical learning method?
|
|
</p>
|
|
|
|
<p>This leads us to a set of different methods that can combine different
|
|
machine learning algorithms or just use one of them to construct
|
|
forests and jungles of trees, homogeneous ones or heterogenous
|
|
ones. These methods are recognized by different names which we will
|
|
try to explain here. These are
|
|
</p>
|
|
|
|
<ol>
|
|
<li> Voting classifiers</li>
|
|
<li> Bagging and Pasting</li>
|
|
<li> Random forests</li>
|
|
<li> Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)</li>
|
|
</ol>
|
|
<p>We discuss these methods here.</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="an-overview-of-ensemble-methods">An Overview of Ensemble Methods </h2>
|
|
|
|
<br/><br/>
|
|
<center>
|
|
<p><img src="DataFiles/ensembleoverview.png" width="600" align="bottom"></p>
|
|
</center>
|
|
<br/><br/>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="why-voting">Why Voting? </h2>
|
|
|
|
<p>The idea behind boosting, and voting as well can be phrased as follows:
|
|
<b>Can a group of people somehow arrive at highly
|
|
reasoned decisions, despite the weak judgement of the individual
|
|
members?</b>
|
|
</p>
|
|
|
|
<p>The aim is to create a good classifier by combining several weak classifiers.
|
|
<b>A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random.</b>
|
|
</p>
|
|
|
|
<p>The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.
|
|
In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in
|
|
each iteration.
|
|
</p>
|
|
|
|
<p>Decision trees play an important role as our weak classifier. They serve as the basic method. </p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="tossing-coins">Tossing coins </h2>
|
|
|
|
<p>The simplest case is a so-called voting ensemble. To illustrate this,
|
|
think of yourself tossing coins with a biased outcome of 51 per cent
|
|
for heads and 49% for tails. With only few tosses,
|
|
you may not clearly see this distribution for heads and tails. However, after some
|
|
thousands of tosses, there will be a clear majority of heads. With 2000 tosses
|
|
you should see approximately 1020 heads and 980 tails.
|
|
</p>
|
|
|
|
<p>We can then state that the outcome is a clear majority of heads. If
|
|
you do this ten thousand times, it is easy to see that there is a 97%
|
|
likelihood of a majority of heads.
|
|
</p>
|
|
|
|
<p>Another example would be to collect all polls before an
|
|
election. Different polls may show different likelihoods for a
|
|
candidate winning with say a majority of the popular vote. The majority vote
|
|
would then consist in many polls indicating that this candidate will
|
|
actually win.
|
|
</p>
|
|
|
|
<p>The example here shows how we can implement the coin tossing case,
|
|
clealry demostrating that after some tosses we see the <a href="https://en.wikipedia.org/wiki/Law_of_large_numbers" target="_blank">law of large</a>
|
|
numbers kicking in.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="standard-imports-first">Standard imports first </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> Image
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler, OneHotEncoder
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.compose</span> <span style="color: #008000; font-weight: bold">import</span> ColumnTransformer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> Image
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Where to save the figures and data files</span>
|
|
PROJECT_ROOT_DIR <span style="color: #666666">=</span> <span style="color: #BA2121">"Results"</span>
|
|
FIGURE_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"Results/FigureFiles"</span>
|
|
DATA_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"DataFiles/"</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(PROJECT_ROOT_DIR):
|
|
os<span style="color: #666666">.</span>mkdir(PROJECT_ROOT_DIR)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(FIGURE_ID):
|
|
os<span style="color: #666666">.</span>makedirs(FIGURE_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(DATA_ID):
|
|
os<span style="color: #666666">.</span>makedirs(DATA_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">image_path</span>(fig_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(FIGURE_ID, fig_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">data_path</span>(dat_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(DATA_ID, dat_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
|
|
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">".png"</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">'png'</span>)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="simple-voting-example-head-or-tail">Simple Voting Example, head or tail </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib.colors</span> <span style="color: #008000; font-weight: bold">import</span> ListedColormap
|
|
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">'axes.labelsize'</span>] <span style="color: #666666">=</span> <span style="color: #666666">14</span>
|
|
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">'xtick.labelsize'</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
|
|
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">'ytick.labelsize'</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
|
|
|
|
heads_proba <span style="color: #666666">=</span> <span style="color: #666666">0.51</span>
|
|
coin_tosses <span style="color: #666666">=</span> (np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">10000</span>, <span style="color: #666666">10</span>) <span style="color: #666666"><</span> heads_proba)<span style="color: #666666">.</span>astype(np<span style="color: #666666">.</span>int32)
|
|
cumulative_heads_ratio <span style="color: #666666">=</span> np<span style="color: #666666">.</span>cumsum(coin_tosses, axis<span style="color: #666666">=0</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">1</span>, <span style="color: #666666">10001</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">8</span>,<span style="color: #666666">3.5</span>))
|
|
plt<span style="color: #666666">.</span>plot(cumulative_heads_ratio)
|
|
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">0</span>, <span style="color: #666666">10000</span>], [<span style="color: #666666">0.51</span>, <span style="color: #666666">0.51</span>], <span style="color: #BA2121">"k--"</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"51%"</span>)
|
|
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">0</span>, <span style="color: #666666">10000</span>], [<span style="color: #666666">0.5</span>, <span style="color: #666666">0.5</span>], <span style="color: #BA2121">"k-"</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"50%"</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">"Number of coin tosses"</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">"Heads ratio"</span>)
|
|
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">"lower right"</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>, <span style="color: #666666">10000</span>, <span style="color: #666666">0.42</span>, <span style="color: #666666">0.58</span>])
|
|
save_fig(<span style="color: #BA2121">"votingsimple"</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="using-the-voting-classifier">Using the Voting Classifier </h2>
|
|
|
|
<p>We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of <b>Scikit-Learn</b>.</p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
|
|
|
|
X, y <span style="color: #666666">=</span> make_moons(n_samples<span style="color: #666666">=500</span>, noise<span style="color: #666666">=0.30</span>, random_state<span style="color: #666666">=42</span>)
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, random_state<span style="color: #666666">=42</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> RandomForestClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> VotingClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
|
|
|
|
log_clf <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">"liblinear"</span>, random_state<span style="color: #666666">=42</span>)
|
|
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(n_estimators<span style="color: #666666">=10</span>, random_state<span style="color: #666666">=42</span>)
|
|
svm_clf <span style="color: #666666">=</span> SVC(gamma<span style="color: #666666">=</span><span style="color: #BA2121">"auto"</span>, random_state<span style="color: #666666">=42</span>)
|
|
|
|
voting_clf <span style="color: #666666">=</span> VotingClassifier(
|
|
estimators<span style="color: #666666">=</span>[(<span style="color: #BA2121">'lr'</span>, log_clf), (<span style="color: #BA2121">'rf'</span>, rnd_clf), (<span style="color: #BA2121">'svc'</span>, svm_clf)],
|
|
voting<span style="color: #666666">=</span><span style="color: #BA2121">'hard'</span>)
|
|
|
|
voting_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> clf <span style="color: #AA22FF; font-weight: bold">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
|
|
clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
|
|
<span style="color: #008000">print</span>(clf<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span>, accuracy_score(y_test, y_pred))
|
|
|
|
log_clf <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">"liblinear"</span>, random_state<span style="color: #666666">=42</span>)
|
|
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(n_estimators<span style="color: #666666">=10</span>, random_state<span style="color: #666666">=42</span>)
|
|
svm_clf <span style="color: #666666">=</span> SVC(gamma<span style="color: #666666">=</span><span style="color: #BA2121">"auto"</span>, probability<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, random_state<span style="color: #666666">=42</span>)
|
|
voting_clf <span style="color: #666666">=</span> VotingClassifier(
|
|
estimators<span style="color: #666666">=</span>[(<span style="color: #BA2121">'lr'</span>, log_clf), (<span style="color: #BA2121">'rf'</span>, rnd_clf), (<span style="color: #BA2121">'svc'</span>, svm_clf)],
|
|
voting<span style="color: #666666">=</span><span style="color: #BA2121">'soft'</span>)
|
|
voting_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> clf <span style="color: #AA22FF; font-weight: bold">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
|
|
clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
|
|
<span style="color: #008000">print</span>(clf<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span>, accuracy_score(y_test, y_pred))
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="voting-and-bagging">Voting and Bagging </h2>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
|
|
|
|
X, y <span style="color: #666666">=</span> make_moons(n_samples<span style="color: #666666">=500</span>, noise<span style="color: #666666">=0.30</span>, random_state<span style="color: #666666">=42</span>)
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, random_state<span style="color: #666666">=42</span>)
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> RandomForestClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> VotingClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
|
|
|
|
log_clf <span style="color: #666666">=</span> LogisticRegression(random_state<span style="color: #666666">=42</span>)
|
|
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(random_state<span style="color: #666666">=42</span>)
|
|
svm_clf <span style="color: #666666">=</span> SVC(random_state<span style="color: #666666">=42</span>)
|
|
|
|
voting_clf <span style="color: #666666">=</span> VotingClassifier(
|
|
estimators<span style="color: #666666">=</span>[(<span style="color: #BA2121">'lr'</span>, log_clf), (<span style="color: #BA2121">'rf'</span>, rnd_clf), (<span style="color: #BA2121">'svc'</span>, svm_clf)],
|
|
voting<span style="color: #666666">=</span><span style="color: #BA2121">'hard'</span>)
|
|
voting_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> clf <span style="color: #AA22FF; font-weight: bold">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
|
|
clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
|
|
<span style="color: #008000">print</span>(clf<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span>, accuracy_score(y_test, y_pred))
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;">log_clf <span style="color: #666666">=</span> LogisticRegression(random_state<span style="color: #666666">=42</span>)
|
|
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(random_state<span style="color: #666666">=42</span>)
|
|
svm_clf <span style="color: #666666">=</span> SVC(probability<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, random_state<span style="color: #666666">=42</span>)
|
|
|
|
voting_clf <span style="color: #666666">=</span> VotingClassifier(
|
|
estimators<span style="color: #666666">=</span>[(<span style="color: #BA2121">'lr'</span>, log_clf), (<span style="color: #BA2121">'rf'</span>, rnd_clf), (<span style="color: #BA2121">'svc'</span>, svm_clf)],
|
|
voting<span style="color: #666666">=</span><span style="color: #BA2121">'soft'</span>)
|
|
voting_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> clf <span style="color: #AA22FF; font-weight: bold">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
|
|
clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
|
|
<span style="color: #008000">print</span>(clf<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span>, accuracy_score(y_test, y_pred))
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="bagging">Bagging </h2>
|
|
|
|
<p>The <b>plain</b> 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.
|
|
</p>
|
|
|
|
<p><b>Bootstrap aggregation</b>, or just <b>bagging</b>, is a
|
|
general-purpose procedure for reducing the variance of a statistical
|
|
learning method.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="more-bagging">More bagging </h2>
|
|
|
|
<p>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.
|
|
</p>
|
|
|
|
<p>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.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="making-your-own-bootstrap-changing-the-level-of-the-decision-tree">Making your own Bootstrap: Changing the Level of the Decision Tree </h2>
|
|
|
|
<p>Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with
|
|
a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)).
|
|
</p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.pipeline</span> <span style="color: #008000; font-weight: bold">import</span> make_pipeline
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.utils</span> <span style="color: #008000; font-weight: bold">import</span> resample
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
|
|
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
n_boostraps <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
maxdepth <span style="color: #666666">=</span> <span style="color: #666666">8</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Make data set.</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-3</span>, <span style="color: #666666">3</span>, n)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
|
|
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> <span style="color: #666666">1.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(<span style="color: #666666">0</span>, <span style="color: #666666">0.1</span>, x<span style="color: #666666">.</span>shape)
|
|
error <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdepth)
|
|
bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdepth)
|
|
variance <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdepth)
|
|
polydegree <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdepth)
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(x, y, test_size<span style="color: #666666">=0.2</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler
|
|
scaler <span style="color: #666666">=</span> StandardScaler()
|
|
scaler<span style="color: #666666">.</span>fit(X_train)
|
|
X_train_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
|
|
X_test_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_test)
|
|
|
|
<span style="color: #408080; font-style: italic"># we produce a simple tree first as benchmark</span>
|
|
simpletree <span style="color: #666666">=</span> DecisionTreeRegressor(max_depth<span style="color: #666666">=3</span>)
|
|
simpletree<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
simpleprediction <span style="color: #666666">=</span> simpletree<span style="color: #666666">.</span>predict(X_test_scaled)
|
|
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,maxdepth):
|
|
model <span style="color: #666666">=</span> DecisionTreeRegressor(max_depth<span style="color: #666666">=</span>degree)
|
|
y_pred <span style="color: #666666">=</span> np<span style="color: #666666">.</span>empty((y_test<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], n_boostraps))
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_boostraps):
|
|
x_, y_ <span style="color: #666666">=</span> resample(X_train_scaled, y_train)
|
|
model<span style="color: #666666">.</span>fit(x_, y_)
|
|
y_pred[:, i] <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X_test_scaled)<span style="color: #408080; font-style: italic">#.ravel()</span>
|
|
|
|
polydegree[degree] <span style="color: #666666">=</span> degree
|
|
error[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>mean((y_test <span style="color: #666666">-</span> y_pred)<span style="color: #666666">**2</span>, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) )
|
|
bias[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( (y_test <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_pred, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>))<span style="color: #666666">**2</span> )
|
|
variance[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>var(y_pred, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) )
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Polynomial degree:'</span>, degree)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Error:'</span>, error[degree])
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Bias^2:'</span>, bias[degree])
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Var:'</span>, variance[degree])
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'</span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> >= </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> + </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> = </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">'</span><span style="color: #666666">.</span>format(error[degree], bias[degree], variance[degree], bias[degree]<span style="color: #666666">+</span>variance[degree]))
|
|
|
|
mse_simpletree<span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>mean((y_test <span style="color: #666666">-</span> simpleprediction)<span style="color: #666666">**2</span>))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Simple tree:"</span>,mse_simpletree)
|
|
plt<span style="color: #666666">.</span>xlim(<span style="color: #666666">1</span>,maxdepth)
|
|
plt<span style="color: #666666">.</span>plot(polydegree, error, label<span style="color: #666666">=</span><span style="color: #BA2121">'MSE'</span>)
|
|
plt<span style="color: #666666">.</span>plot(polydegree, bias, label<span style="color: #666666">=</span><span style="color: #BA2121">'bias'</span>)
|
|
plt<span style="color: #666666">.</span>plot(polydegree, variance, label<span style="color: #666666">=</span><span style="color: #BA2121">'Variance'</span>)
|
|
plt<span style="color: #666666">.</span>legend()
|
|
save_fig(<span style="color: #BA2121">"baggingboot"</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="random-forests">Random forests </h2>
|
|
|
|
<p>Random forests provide an improvement over bagged trees by way of a
|
|
small tweak that decorrelates the trees.
|
|
</p>
|
|
|
|
<p>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.
|
|
</p>
|
|
|
|
<p>A fresh sample of \( m \) predictors is
|
|
taken at each split, and typically we choose
|
|
</p>
|
|
|
|
$$
|
|
m\approx \sqrt{p}.
|
|
$$
|
|
|
|
<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.
|
|
</p>
|
|
|
|
<p>The reason for this is rather clever. Suppose that there is one very
|
|
strong predictor in the data set, along with a number of other
|
|
moderately strong predictors. Then in the collection of bagged
|
|
variable importance random forest trees, most or all of the trees will
|
|
use this strong predictor in the top split. Consequently, all of the
|
|
bagged trees will look quite similar to each other. Hence the
|
|
predictions from the bagged trees will be highly correlated.
|
|
Unfortunately, averaging many highly correlated quantities does not
|
|
lead to as large of a reduction in variance as averaging many
|
|
uncorrelated quantities. In particular, this means that bagging will
|
|
not lead to a substantial reduction in variance over a single tree in
|
|
this setting.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="random-forest-algorithm">Random Forest Algorithm </h2>
|
|
<p>The algorithm described here can be applied to both classification and regression problems.</p>
|
|
|
|
<p>We will grow of forest of say \( B \) trees.</p>
|
|
<ol>
|
|
<li> For \( b=1:B \)</li>
|
|
<ul>
|
|
<li> Draw a bootstrap sample from the training data organized in our \( \boldsymbol{X} \) matrix.</li>
|
|
<li> We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached</li>
|
|
<ol>
|
|
<li> we select \( m \le p \) variables at random from the \( p \) predictors/features</li>
|
|
<li> pick the best split point among the \( m \) features using for example the CART algorithm and create a new node</li>
|
|
<li> split the node into daughter nodes</li>
|
|
</ol>
|
|
</ul>
|
|
<li> Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.</li>
|
|
</ol>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="random-forests-compared-with-other-methods-on-the-cancer-data">Random Forests Compared with other Methods on the Cancer Data </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> BaggingClassifier
|
|
|
|
<span style="color: #408080; font-style: italic"># Load the data</span>
|
|
cancer <span style="color: #666666">=</span> load_breast_cancer()
|
|
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(cancer<span style="color: #666666">.</span>data,cancer<span style="color: #666666">.</span>target,random_state<span style="color: #666666">=0</span>)
|
|
<span style="color: #008000">print</span>(X_train<span style="color: #666666">.</span>shape)
|
|
<span style="color: #008000">print</span>(X_test<span style="color: #666666">.</span>shape)
|
|
<span style="color: #408080; font-style: italic">#define methods</span>
|
|
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
|
|
logreg <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">'lbfgs'</span>)
|
|
<span style="color: #408080; font-style: italic"># Support vector machine</span>
|
|
svm <span style="color: #666666">=</span> SVC(gamma<span style="color: #666666">=</span><span style="color: #BA2121">'auto'</span>, C<span style="color: #666666">=100</span>)
|
|
<span style="color: #408080; font-style: italic"># Decision Trees</span>
|
|
deep_tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>)
|
|
<span style="color: #408080; font-style: italic">#Scale the data</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler
|
|
scaler <span style="color: #666666">=</span> StandardScaler()
|
|
scaler<span style="color: #666666">.</span>fit(X_train)
|
|
X_train_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
|
|
X_test_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_test)
|
|
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
|
|
logreg<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy Logistic Regression with scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
|
|
<span style="color: #408080; font-style: italic"># Support Vector Machine</span>
|
|
svm<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy SVM with scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
|
|
<span style="color: #408080; font-style: italic"># Decision Trees</span>
|
|
deep_tree_clf<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy with Decision Trees and scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(deep_tree_clf<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> RandomForestClassifier
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> LabelEncoder
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> cross_validate
|
|
<span style="color: #408080; font-style: italic"># Data set not specificied</span>
|
|
<span style="color: #408080; font-style: italic">#Instantiate the model with 500 trees and entropy as splitting criteria</span>
|
|
Random_Forest_model <span style="color: #666666">=</span> RandomForestClassifier(n_estimators<span style="color: #666666">=500</span>,criterion<span style="color: #666666">=</span><span style="color: #BA2121">"entropy"</span>)
|
|
Random_Forest_model<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
<span style="color: #408080; font-style: italic">#Cross validation</span>
|
|
accuracy <span style="color: #666666">=</span> cross_validate(Random_Forest_model,X_test_scaled,y_test,cv<span style="color: #666666">=10</span>)[<span style="color: #BA2121">'test_score'</span>]
|
|
<span style="color: #008000">print</span>(accuracy)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy with Random Forests and scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(Random_Forest_model<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scikitplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skplt</span>
|
|
y_pred <span style="color: #666666">=</span> Random_Forest_model<span style="color: #666666">.</span>predict(X_test_scaled)
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_confusion_matrix(y_test, y_pred, normalize<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
y_probas <span style="color: #666666">=</span> Random_Forest_model<span style="color: #666666">.</span>predict_proba(X_test_scaled)
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_roc(y_test, y_probas)
|
|
plt<span style="color: #666666">.</span>show()
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_cumulative_gain(y_test, y_probas)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<p>Recall that the cumulative gains curve shows the percentage of the
|
|
overall number of cases in a given category <em>gained</em> by targeting a
|
|
percentage of the total number of cases.
|
|
</p>
|
|
|
|
<p>Similarly, the receiver operating characteristic curve, or ROC curve,
|
|
displays the diagnostic ability of a binary classifier system as its
|
|
discrimination threshold is varied. It plots the true positive rate against the false positive rate.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="compare-bagging-on-trees-with-random-forests">Compare Bagging on Trees with Random Forests </h2>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;">bag_clf <span style="color: #666666">=</span> BaggingClassifier(
|
|
DecisionTreeClassifier(splitter<span style="color: #666666">=</span><span style="color: #BA2121">"random"</span>, max_leaf_nodes<span style="color: #666666">=16</span>, random_state<span style="color: #666666">=42</span>),
|
|
n_estimators<span style="color: #666666">=500</span>, max_samples<span style="color: #666666">=1.0</span>, bootstrap<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, n_jobs<span style="color: #666666">=-1</span>, random_state<span style="color: #666666">=42</span>)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;">bag_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
y_pred <span style="color: #666666">=</span> bag_clf<span style="color: #666666">.</span>predict(X_test)
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> RandomForestClassifier
|
|
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(n_estimators<span style="color: #666666">=500</span>, max_leaf_nodes<span style="color: #666666">=16</span>, n_jobs<span style="color: #666666">=-1</span>, random_state<span style="color: #666666">=42</span>)
|
|
rnd_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
y_pred_rf <span style="color: #666666">=</span> rnd_clf<span style="color: #666666">.</span>predict(X_test)
|
|
np<span style="color: #666666">.</span>sum(y_pred <span style="color: #666666">==</span> y_pred_rf) <span style="color: #666666">/</span> <span style="color: #008000">len</span>(y_pred)
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="boosting-a-bird-s-eye-view">Boosting, a Bird's Eye View </h2>
|
|
|
|
<p>The basic idea is to combine weak classifiers in order to create a good
|
|
classifier. With a weak classifier we often intend a classifier which
|
|
produces results which are only slightly better than we would get by
|
|
random guesses.
|
|
</p>
|
|
|
|
<p>This is done by applying in an iterative way a weak (or a standard
|
|
classifier like decision trees) to modify the data. In each iteration
|
|
we emphasize those observations which are misclassified by weighting
|
|
them with a factor.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="what-is-boosting-additive-modelling-iterative-fitting">What is boosting? Additive Modelling/Iterative Fitting </h2>
|
|
|
|
<p>Boosting is a way of fitting an additive expansion in a set of
|
|
elementary basis functions like for example some simple polynomials.
|
|
Assume for example that we have a function
|
|
</p>
|
|
$$
|
|
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
|
|
$$
|
|
|
|
<p>where \( \beta_m \) are the expansion parameters to be determined in a
|
|
minimization process and \( b(x;\gamma_m) \) are some simple functions of
|
|
the multivariable parameter \( x \) which is characterized by the
|
|
parameters \( \gamma_m \).
|
|
</p>
|
|
|
|
<p>As an example, consider the Sigmoid function we used in logistic
|
|
regression. In that case, we can translate the function
|
|
\( b(x;\gamma_m) \) into the Sigmoid function
|
|
</p>
|
|
|
|
$$
|
|
\sigma(t) = \frac{1}{1+\exp{(-t)}},
|
|
$$
|
|
|
|
<p>where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and
|
|
\( \gamma_1 \) were determined by the Logistic Regression fitting
|
|
algorithm.
|
|
</p>
|
|
|
|
<p>As another example, consider the cost function we defined for linear regression</p>
|
|
$$
|
|
C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
|
|
$$
|
|
|
|
<p>In this case the function \( f(x) \) was replaced by the design matrix
|
|
\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \),
|
|
that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can
|
|
simply invert a matrix and obtain the parameters \( \beta \) by
|
|
</p>
|
|
|
|
$$
|
|
\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
|
|
$$
|
|
|
|
<p>In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="iterative-fitting-regression-and-squared-error-cost-function">Iterative Fitting, Regression and Squared-error Cost Function </h2>
|
|
|
|
<p>The way we proceed is as follows (here we specialize to the squared-error cost function)</p>
|
|
|
|
<ol>
|
|
<li> Establish a cost function, here \( C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).</li>
|
|
<li> Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.</li>
|
|
<li> For \( m=1:M \)
|
|
<ol type="a"></li>
|
|
<li> minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)</li>
|
|
<li> This gives the optimal values \( \beta_m \) and \( \gamma_m \)</li>
|
|
<li> Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)</li>
|
|
</ol>
|
|
</ol>
|
|
<p>We could use any of the algorithms we have discussed till now. If we
|
|
use trees, \( \gamma \) parameterizes the split variables and split points
|
|
at the internal nodes, and the predictions at the terminal nodes.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="squared-error-example-and-iterative-fitting">Squared-Error Example and Iterative Fitting </h2>
|
|
|
|
<p>To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.</p>
|
|
|
|
<p>For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). </p>
|
|
|
|
<p>This means that for every iteration \( m \), we need to optimize</p>
|
|
|
|
$$
|
|
(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2.
|
|
$$
|
|
|
|
<p>We start our iteration by simply setting \( f_0(x)=0 \).
|
|
Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
|
|
</p>
|
|
$$
|
|
\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
|
|
$$
|
|
|
|
<p>and</p>
|
|
$$
|
|
\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
|
|
$$
|
|
|
|
<p>We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)</p>
|
|
$$
|
|
\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0,
|
|
$$
|
|
|
|
<p>which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have </p>
|
|
$$
|
|
\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0,
|
|
$$
|
|
|
|
<p>which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting
|
|
for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically.
|
|
</p>
|
|
|
|
<p>The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as
|
|
\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \).
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="iterative-fitting-classification-and-adaboost">Iterative Fitting, Classification and AdaBoost </h2>
|
|
|
|
<p>Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of
|
|
observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values
|
|
\( \{-1,1\} \).
|
|
</p>
|
|
|
|
<p>The error rate of the training sample is then</p>
|
|
|
|
$$
|
|
\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
|
|
$$
|
|
|
|
<p>The iterative procedure starts with defining a weak classifier whose
|
|
error rate is barely better than random guessing. The iterative
|
|
procedure in boosting is to sequentially apply a weak
|
|
classification algorithm to repeatedly modified versions of the data
|
|
producing a sequence of weak classifiers \( G_m(x) \).
|
|
</p>
|
|
|
|
<p>Here we will express our function \( f(x) \) in terms of \( G(x) \). That is</p>
|
|
$$
|
|
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
|
|
$$
|
|
|
|
<p>will be a function of </p>
|
|
$$
|
|
G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="adaptive-boosting-adaboost">Adaptive Boosting, AdaBoost </h2>
|
|
|
|
<p>In our iterative procedure we define thus</p>
|
|
$$
|
|
f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
|
|
$$
|
|
|
|
<p>The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
|
|
exponential cost/loss function defined as
|
|
</p>
|
|
$$
|
|
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
|
|
$$
|
|
|
|
<p>We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case.
|
|
This is normally done in two steps. Let us however first rewrite the cost function as
|
|
</p>
|
|
|
|
$$
|
|
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
|
|
$$
|
|
|
|
<p>where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="building-up-adaboost">Building up AdaBoost </h2>
|
|
|
|
<p>First, for any \( \beta > 0 \), we optimize \( G \) by setting</p>
|
|
$$
|
|
G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
|
|
$$
|
|
|
|
<p>which is the classifier that minimizes the weighted error rate in predicting \( y \).</p>
|
|
|
|
<p>We can do this by rewriting</p>
|
|
$$
|
|
\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
|
|
$$
|
|
|
|
<p>which can be rewritten as</p>
|
|
$$
|
|
(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,
|
|
$$
|
|
|
|
<p>which leads to</p>
|
|
$$
|
|
\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
|
|
$$
|
|
|
|
<p>where we have redefined the error as </p>
|
|
$$
|
|
\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},
|
|
$$
|
|
|
|
<p>which leads to an update of</p>
|
|
$$
|
|
f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
|
|
$$
|
|
|
|
<p>This leads to the new weights</p>
|
|
$$
|
|
w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
|
|
$$
|
|
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="adaptive-boosting-adaboost-basic-algorithm">Adaptive boosting: AdaBoost, Basic Algorithm </h2>
|
|
|
|
<p>The algorithm here is rather straightforward. Assume that our weak
|
|
classifier is a decision tree and we consider a binary set of outputs
|
|
with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of
|
|
observations. Our design matrix is given in terms of the
|
|
feature/predictor vectors
|
|
\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a
|
|
classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \).
|
|
</p>
|
|
|
|
<p>We have already defined the misclassification error \( \mathrm{err} \) as</p>
|
|
$$
|
|
\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
|
|
$$
|
|
|
|
<p>where the function \( I() \) is one if we misclassify and zero if we classify correctly. </p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="basic-steps-of-adaboost">Basic Steps of AdaBoost </h2>
|
|
|
|
<p>With the above definitions we are now ready to set up the algorithm for AdaBoost.
|
|
The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.
|
|
</p>
|
|
<ol>
|
|
<li> We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).</li>
|
|
<li> We rewrite the misclassification error as</li>
|
|
</ol>
|
|
$$
|
|
\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i},
|
|
$$
|
|
|
|
<ol>
|
|
<li> Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree.
|
|
<ol type="a"></li>
|
|
<li> Fit then a given classifier to the training set using the weights \( w_i \).</li>
|
|
<li> Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.</li>
|
|
<li> Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)</li>
|
|
<li> Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).</li>
|
|
</ol>
|
|
<li> Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).</li>
|
|
</ol>
|
|
<p>For the iterations with \( m \le 2 \) the weights are modified
|
|
individually at each steps. The observations which were misclassified
|
|
at iteration \( m-1 \) have a weight which is larger than those which were
|
|
classified properly. As this proceeds, the observations which were
|
|
difficult to classifiy correctly are given a larger influence. Each
|
|
new classification step \( m \) is then forced to concentrate on those
|
|
observations that are missed in the previous iterations.
|
|
</p>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
<h2 id="adaboost-examples">AdaBoost Examples </h2>
|
|
|
|
<p>Using <b>Scikit-Learn</b> it is easy to apply the adaptive boosting algorithm, as done here.</p>
|
|
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="cell border-box-sizing code_cell rendered">
|
|
<div class="input">
|
|
<div class="inner_cell">
|
|
<div class="input_area">
|
|
<div class="highlight" style="background: #f8f8f8">
|
|
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> AdaBoostClassifier
|
|
|
|
ada_clf <span style="color: #666666">=</span> AdaBoostClassifier(
|
|
DecisionTreeClassifier(max_depth<span style="color: #666666">=1</span>), n_estimators<span style="color: #666666">=200</span>,
|
|
algorithm<span style="color: #666666">=</span><span style="color: #BA2121">"SAMME.R"</span>, learning_rate<span style="color: #666666">=0.5</span>, random_state<span style="color: #666666">=42</span>)
|
|
ada_clf<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> AdaBoostClassifier
|
|
|
|
ada_clf <span style="color: #666666">=</span> AdaBoostClassifier(
|
|
DecisionTreeClassifier(max_depth<span style="color: #666666">=1</span>), n_estimators<span style="color: #666666">=200</span>,
|
|
algorithm<span style="color: #666666">=</span><span style="color: #BA2121">"SAMME.R"</span>, learning_rate<span style="color: #666666">=0.5</span>, random_state<span style="color: #666666">=42</span>)
|
|
ada_clf<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
y_pred <span style="color: #666666">=</span> ada_clf<span style="color: #666666">.</span>predict(X_test_scaled)
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_confusion_matrix(y_test, y_pred, normalize<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
y_probas <span style="color: #666666">=</span> ada_clf<span style="color: #666666">.</span>predict_proba(X_test_scaled)
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_roc(y_test, y_probas)
|
|
plt<span style="color: #666666">.</span>show()
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_cumulative_gain(y_test, y_probas)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="output_wrapper">
|
|
<div class="output">
|
|
<div class="output_area">
|
|
<div class="output_subarea output_stream output_stdout output_text">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<!-- ------------------- end of main content --------------- -->
|
|
<center style="font-size:80%">
|
|
<!-- copyright --> © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
</body>
|
|
</html>
|
|
|