Files
FYS-STK4155/doc/pub/week46/html/week46-reveal.html
Morten Hjorth-Jensen b544385d9d added videos
2024-11-11 15:55:39 +01:00

2837 lines
148 KiB
HTML

<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week46-reveal.html week46-reveal reveal --html_slide_theme=beige
-->
<!DOCTYPE html>
<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>
<!-- reveal.js: https://lab.hakim.se/reveal-js/ -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="reveal.js/css/reveal.css">
<link rel="stylesheet" href="reveal.js/css/theme/beige.css" id="theme">
<!--
<link rel="stylesheet" href="reveal.js/css/reveal.css">
<link rel="stylesheet" href="reveal.js/css/theme/beige.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/beigesmall.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/solarized.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/serif.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/night.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/moon.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/simple.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/sky.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/darkgray.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/default.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/cbc.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/simula.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/black.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/white.css" id="theme">
<link rel="stylesheet" href="reveal.js/css/theme/league.css" id="theme">
-->
<!-- For syntax highlighting -->
<link rel="stylesheet" href="reveal.js/lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<style type="text/css">
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-size: 60%; font-style: italic; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa}
.reveal .alert-text-small { font-size: 80%; }
.reveal .alert-text-large { font-size: 130%; }
.reveal .alert-text-normal { font-size: 90%; }
.reveal .alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:5px solid #bababa;
-webkit-border-radius: 14px; -moz-border-radius: 14px;
border-radius:14px;
background-position: 10px 10px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 30px; /* 55px; if icon */
}
.reveal .alert-block {padding-top:14px; padding-bottom:14px}
.reveal .alert-block > p, .alert-block > ul {margin-bottom:1em}
/*.reveal .alert li {margin-top: 1em}*/
.reveal .alert-block p+p {margin-top:5px}
/*.reveal .alert-notice { background-image: url(https://hplgit.github.io/doconce/bundled/html_images/small_gray_notice.png); }
.reveal .alert-summary { background-image:url(https://hplgit.github.io/doconce/bundled/html_images/small_gray_summary.png); }
.reveal .alert-warning { background-image: url(https://hplgit.github.io/doconce/bundled/html_images/small_gray_warning.png); }
.reveal .alert-question {background-image:url(https://hplgit.github.io/doconce/bundled/html_images/small_gray_question.png); } */
/* Override reveal.js table border */
.reveal table td {
border: 0;
}
<style type="text/css">
/* Override h1, h2, ... styles */
h1 { font-size: 2.8em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.4em; }
h4 { font-size: 1.3em; }
h1, h2, h3, h4 { font-weight: bold; line-height: 1.2; }
body { overflow: auto; } /* vertical scrolling */
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-size: 60%; font-style: italic; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa}
.slide .alert-text-small { font-size: 80%; }
.slide .alert-text-large { font-size: 130%; }
.slide .alert-text-normal { font-size: 90%; }
.slide .alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:5px solid #bababa;
-webkit-border-radius:14px; -moz-border-radius:14px;
border-radius:14px
background-position: 10px 10px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 30px; /* 55px; if icon */
}
.slide .alert-block {padding-top:14px; padding-bottom:14px}
.slide .alert-block > p, .alert-block > ul {margin-bottom:0}
/*.slide .alert li {margin-top: 1em}*/
.deck .alert-block p+p {margin-top:5px}
/*.slide .alert-notice { background-image: url(https://hplgit.github.io/doconce/
bundled/html_images//small_gray_notice.png); }
.slide .alert-summary { background-image:url(https://hplgit.github.io/doconce/
bundled/html_images//small_gray_summary.png); }
.slide .alert-warning { background-image: url(https://hplgit.github.io/doconce/
bundled/html_images//small_gray_warning.png); }
.slide .alert-question {background-image:url(https://hplgit.github.io/doconce/
bundled/html_images/small_gray_question.png); } */
.dotable table, .dotable th, .dotable tr, .dotable tr td {
border: 2px solid black;
border-collapse: collapse;
padding: 2px;
}
</style>
<!-- Styles for table layout of slides -->
<style type="text/css">
td.padding {
padding-top:20px;
padding-bottom:20px;
padding-right:50px;
padding-left:50px;
}
</style>
</head>
<body>
<div class="reveal">
<div class="slides">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
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>
<section>
<!-- ------------------- main content ---------------------- -->
<center>
<h1 style="text-align: center;">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>
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</section>
<section>
<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>
<p><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>
<p><li> Readings and Videos:
<ol type="a"></li>
<p><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>
<p><li> Video of lecture at <a href="https://youtu.be/TfRKUfdJwB4" target="_blank"><tt>https://youtu.be/TfRKUfdJwB4</tt></a></li>
<p><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>
<p><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>
<p><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>
<p>
</ol>
</div>
</section>
<section>
<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>
</section>
<section>
<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>
</section>
<section>
<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>
</section>
<section>
<h2 id="general-features">General Features </h2>
<p>The overarching approach to decision trees is a top-down approach.</p>
<ul>
<p><li> A leaf provides the classification of a given instance.</li>
<p><li> A node specifies a test of some attribute of the instance.</li>
<p><li> A branch corresponds to a possible values of an attribute.</li>
<p><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>
<p>This process is then repeated for the subtree rooted at the new
node.
</p>
</section>
<section>
<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>
<p><li> Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature</li>
<p><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>
<p><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>
<p><li> Show query instances to the tree and run down the tree until we arrive at leaf nodes</li>
</ol>
<p>
<p>Then we are essentially done!</p>
</section>
<section>
<h2 id="decision-trees-and-regression">Decision trees and Regression </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.preprocessing</span> <span style="color: #8B008B; font-weight: bold">import</span> PolynomialFeatures
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.linear_model</span> <span style="color: #8B008B; font-weight: bold">import</span> LinearRegression
steps=<span style="color: #B452CD">250</span>
distance=<span style="color: #B452CD">0</span>
x=<span style="color: #B452CD">0</span>
distance_list=[]
steps_list=[]
<span style="color: #8B008B; font-weight: bold">while</span> x&lt;steps:
distance+=np.random.randint(-<span style="color: #B452CD">1</span>,<span style="color: #B452CD">2</span>)
distance_list.append(distance)
x+=<span style="color: #B452CD">1</span>
steps_list.append(x)
plt.plot(steps_list,distance_list, color=<span style="color: #CD5555">&#39;green&#39;</span>, label=<span style="color: #CD5555">&quot;Random Walk Data&quot;</span>)
steps_list=np.asarray(steps_list)
distance_list=np.asarray(distance_list)
X=steps_list[:,np.newaxis]
<span style="color: #228B22">#Polynomial fits</span>
<span style="color: #228B22">#Degree 2</span>
poly_features=PolynomialFeatures(degree=<span style="color: #B452CD">2</span>, include_bias=<span style="color: #8B008B; font-weight: bold">False</span>)
X_poly=poly_features.fit_transform(X)
lin_reg=LinearRegression()
poly_fit=lin_reg.fit(X_poly,distance_list)
b=lin_reg.coef_
c=lin_reg.intercept_
<span style="color: #658b00">print</span> (<span style="color: #CD5555">&quot;2nd degree coefficients:&quot;</span>)
<span style="color: #658b00">print</span> (<span style="color: #CD5555">&quot;zero power: &quot;</span>,c)
<span style="color: #658b00">print</span> (<span style="color: #CD5555">&quot;first power: &quot;</span>, b[<span style="color: #B452CD">0</span>])
<span style="color: #658b00">print</span> (<span style="color: #CD5555">&quot;second power: &quot;</span>,b[<span style="color: #B452CD">1</span>])
z = np.arange(<span style="color: #B452CD">0</span>, steps, <span style="color: #B452CD">.01</span>)
z_mod=b[<span style="color: #B452CD">1</span>]*z**<span style="color: #B452CD">2</span>+b[<span style="color: #B452CD">0</span>]*z+c
fit_mod=b[<span style="color: #B452CD">1</span>]*X**<span style="color: #B452CD">2</span>+b[<span style="color: #B452CD">0</span>]*X+c
plt.plot(z, z_mod, color=<span style="color: #CD5555">&#39;r&#39;</span>, label=<span style="color: #CD5555">&quot;2nd Degree Fit&quot;</span>)
plt.title(<span style="color: #CD5555">&quot;Polynomial Regression&quot;</span>)
plt.xlabel(<span style="color: #CD5555">&quot;Steps&quot;</span>)
plt.ylabel(<span style="color: #CD5555">&quot;Distance&quot;</span>)
<span style="color: #228B22">#Degree 10</span>
poly_features10=PolynomialFeatures(degree=<span style="color: #B452CD">10</span>, include_bias=<span style="color: #8B008B; font-weight: bold">False</span>)
X_poly10=poly_features10.fit_transform(X)
poly_fit10=lin_reg.fit(X_poly10,distance_list)
y_plot=poly_fit10.predict(X_poly10)
plt.plot(X, y_plot, color=<span style="color: #CD5555">&#39;black&#39;</span>, label=<span style="color: #CD5555">&quot;10th Degree Fit&quot;</span>)
plt.legend()
plt.show()
<span style="color: #228B22">#Decision Tree Regression</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeRegressor
regr_1=DecisionTreeRegressor(max_depth=<span style="color: #B452CD">2</span>)
regr_2=DecisionTreeRegressor(max_depth=<span style="color: #B452CD">5</span>)
regr_3=DecisionTreeRegressor(max_depth=<span style="color: #B452CD">7</span>)
regr_1.fit(X, distance_list)
regr_2.fit(X, distance_list)
regr_3.fit(X, distance_list)
X_test = np.arange(<span style="color: #B452CD">0.0</span>, steps, <span style="color: #B452CD">0.01</span>)[:, np.newaxis]
y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)
y_3=regr_3.predict(X_test)
<span style="color: #228B22"># Plot the results</span>
plt.figure()
plt.scatter(X, distance_list, s=<span style="color: #B452CD">2.5</span>, c=<span style="color: #CD5555">&quot;black&quot;</span>, label=<span style="color: #CD5555">&quot;data&quot;</span>)
plt.plot(X_test, y_1, color=<span style="color: #CD5555">&quot;red&quot;</span>,
label=<span style="color: #CD5555">&quot;max_depth=2&quot;</span>, linewidth=<span style="color: #B452CD">2</span>)
plt.plot(X_test, y_2, color=<span style="color: #CD5555">&quot;green&quot;</span>, label=<span style="color: #CD5555">&quot;max_depth=5&quot;</span>, linewidth=<span style="color: #B452CD">2</span>)
plt.plot(X_test, y_3, color=<span style="color: #CD5555">&quot;m&quot;</span>, label=<span style="color: #CD5555">&quot;max_depth=7&quot;</span>, linewidth=<span style="color: #B452CD">2</span>)
plt.xlabel(<span style="color: #CD5555">&quot;Data&quot;</span>)
plt.ylabel(<span style="color: #CD5555">&quot;Darget&quot;</span>)
plt.title(<span style="color: #CD5555">&quot;Decision Tree Regression&quot;</span>)
plt.legend()
plt.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>
</section>
<section>
<h2 id="building-a-tree-regression">Building a tree, regression </h2>
<p>There are mainly two steps</p>
<ol>
<p><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>
<p><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>
<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>
<p>&nbsp;<br>
$$
\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
$$
<p>&nbsp;<br>
<p>where \( \overline{y}_{R_j} \) is the mean response for the training observations
within box \( j \).
</p>
</section>
<section>
<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>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
\left\{X\vert x_j < s\right\},
$$
<p>&nbsp;<br>
<p>and</p>
<p>&nbsp;<br>
$$
\left\{X\vert x_j \geq s\right\},
$$
<p>&nbsp;<br>
<p>so that we obtain the lowest MSE, that is</p>
<p>&nbsp;<br>
$$
\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>&nbsp;<br>
<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>
</section>
<section>
<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>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
$$
<p>&nbsp;<br>
<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&#8217;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>
</section>
<section>
<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>
<p><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>
<p><li> Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).</li>
<p><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>
<p><li> repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.</li>
<p><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>
<p><li> Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.</li>
</ul>
<p>
<p><li> Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).</li>
</ol>
</div>
</section>
<section>
<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>
</section>
<section>
<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>
</section>
<section>
<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>&nbsp;<br>
$$
p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
$$
<p>&nbsp;<br>
<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>
<p><li> Misclassification error</li>
</ul>
<p>
<p>&nbsp;<br>
$$
p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}.
$$
<p>&nbsp;<br>
<ul>
<p><li> Gini index \( g \)</li>
</ul>
<p>
<p>&nbsp;<br>
$$
g = \sum_{k=1}^K p_{mk}(1-p_{mk}).
$$
<p>&nbsp;<br>
<ul>
<p><li> Information entropy or just entropy \( s \)</li>
</ul>
<p>
<p>&nbsp;<br>
$$
s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
$$
<p>&nbsp;<br>
</section>
<section>
<h2 id="visualizing-the-tree-classification">Visualizing the Tree, Classification </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">os</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> load_breast_cancer
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.metrics</span> <span style="color: #8B008B; font-weight: bold">import</span> confusion_matrix
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> export_graphviz
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> Image
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">pydot</span> <span style="color: #8B008B; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
cancer = load_breast_cancer()
X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
<span style="color: #658b00">print</span>(X)
y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
y = pd.get_dummies(y)
<span style="color: #658b00">print</span>(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=<span style="color: #B452CD">1</span>)
tree_clf = DecisionTreeClassifier(max_depth=<span style="color: #B452CD">5</span>)
tree_clf.fit(X_train, y_train)
export_graphviz(
tree_clf,
out_file=<span style="color: #CD5555">&quot;DataFiles/cancer.dot&quot;</span>,
feature_names=cancer.feature_names,
class_names=cancer.target_names,
rounded=<span style="color: #8B008B; font-weight: bold">True</span>,
filled=<span style="color: #8B008B; font-weight: bold">True</span>
)
cmd = <span style="color: #CD5555">&#39;dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png&#39;</span>
os.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>
</section>
<section>
<h2 id="visualizing-the-tree-the-moons">Visualizing the Tree, The Moons </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #228B22"># Common imports</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> make_moons
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> export_graphviz
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">pydot</span> <span style="color: #8B008B; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">os</span>
np.random.seed(<span style="color: #B452CD">42</span>)
X, y = make_moons(n_samples=<span style="color: #B452CD">100</span>, noise=<span style="color: #B452CD">0.25</span>, random_state=<span style="color: #B452CD">53</span>)
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=<span style="color: #B452CD">0</span>)
tree_clf = DecisionTreeClassifier(max_depth=<span style="color: #B452CD">5</span>)
tree_clf.fit(X_train, y_train)
export_graphviz(
tree_clf,
out_file=<span style="color: #CD5555">&quot;DataFiles/moons.dot&quot;</span>,
rounded=<span style="color: #8B008B; font-weight: bold">True</span>,
filled=<span style="color: #8B008B; font-weight: bold">True</span>
)
cmd = <span style="color: #CD5555">&#39;dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png&#39;</span>
os.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>
</section>
<section>
<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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> load_iris
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn</span> <span style="color: #8B008B; font-weight: bold">import</span> tree
X, y = load_iris(return_X_y=<span style="color: #8B008B; font-weight: bold">True</span>)
tree_clf = tree.DecisionTreeClassifier()
tree_clf = tree_clf.fit(X, y)
<span style="color: #228B22"># and then plot the tree</span>
tree.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>
</section>
<section>
<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&#8217;t require the installation of external libraries and is more compact:
</p>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> load_iris
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> export_text
iris = load_iris()
decision_tree = DecisionTreeClassifier(random_state=<span style="color: #B452CD">0</span>, max_depth=<span style="color: #B452CD">2</span>)
decision_tree = decision_tree.fit(iris.data, iris.target)
r = export_text(decision_tree, feature_names=iris[<span style="color: #CD5555">&#39;feature_names&#39;</span>])
<span style="color: #658b00">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>
</section>
<section>
<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>
<p><li> The CART (Classification And Regression Tree) algorithm for both classification and regression</li>
<p><li> The ID3 algorithm based on the computation of the information gain for classification</li>
</ol>
<p>
<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>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}},
$$
<p>&nbsp;<br>
<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>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}.
$$
<p>&nbsp;<br>
<p>Here the MSE for a specific node is defined as</p>
<p>&nbsp;<br>
$$
\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2,
$$
<p>&nbsp;<br>
<p>with</p>
<p>&nbsp;<br>
$$
\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i,
$$
<p>&nbsp;<br>
<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>
</section>
<section>
<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>
</section>
<section>
<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>
<p><li> Trend of average grades before present course, classified as either below or above the average grade of the whole class</li>
<p><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>
<p><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>
<p><li> The final grade whether it is above or below average</li>
</ol>
</section>
<section>
<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>
</section>
<section>
<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>
</section>
<section>
<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>
</section>
<section>
<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>
</section>
<section>
<h2 id="a-possible-code-using-scikit-learn">A possible code using Scikit-Learn </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #228B22"># Common imports</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> export_graphviz
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.preprocessing</span> <span style="color: #8B008B; font-weight: bold">import</span> StandardScaler, OneHotEncoder
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.compose</span> <span style="color: #8B008B; font-weight: bold">import</span> ColumnTransformer
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> Image
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">pydot</span> <span style="color: #8B008B; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">os</span>
<span style="color: #228B22"># Where to save the figures and data files</span>
PROJECT_ROOT_DIR = <span style="color: #CD5555">&quot;Results&quot;</span>
FIGURE_ID = <span style="color: #CD5555">&quot;Results/FigureFiles&quot;</span>
DATA_ID = <span style="color: #CD5555">&quot;DataFiles/&quot;</span>
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">image_path</span>(fig_id):
<span style="color: #8B008B; font-weight: bold">return</span> os.path.join(FIGURE_ID, fig_id)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">data_path</span>(dat_id):
<span style="color: #8B008B; font-weight: bold">return</span> os.path.join(DATA_ID, dat_id)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">save_fig</span>(fig_id):
plt.savefig(image_path(fig_id) + <span style="color: #CD5555">&quot;.png&quot;</span>, <span style="color: #658b00">format</span>=<span style="color: #CD5555">&#39;png&#39;</span>)
infile = <span style="color: #658b00">open</span>(data_path(<span style="color: #CD5555">&quot;grades.csv&quot;</span>),<span style="color: #CD5555">&#39;r&#39;</span>)
<span style="color: #228B22"># Read the experimental data with Pandas</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> display
grades = pd.read_csv(infile)
grades = pd.DataFrame(grades)
display(grades)
<span style="color: #228B22"># Features and targets</span>
X = grades.loc[:, grades.columns != <span style="color: #CD5555">&#39;Grade&#39;</span>].values
y = grades.loc[:, grades.columns == <span style="color: #CD5555">&#39;Grade&#39;</span>].values
<span style="color: #658b00">print</span>(X)
<span style="color: #228B22"># Then do a Classification tree</span>
tree_clf = DecisionTreeClassifier(max_depth=<span style="color: #B452CD">2</span>)
tree_clf.fit(X, y)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Train set accuracy with Decision Tree: {:.2f}&quot;</span>.format(tree_clf.score(X,y)))
<span style="color: #228B22">#transfer to a decision tree graph</span>
export_graphviz(
tree_clf,
out_file=<span style="color: #CD5555">&quot;DataFiles/grade.dot&quot;</span>,
rounded=<span style="color: #8B008B; font-weight: bold">True</span>,
filled=<span style="color: #8B008B; font-weight: bold">True</span>
)
cmd = <span style="color: #CD5555">&#39;dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png&#39;</span>
os.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>
</section>
<section>
<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>
</section>
<section>
<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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #228B22"># Common imports</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> export_graphviz
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.preprocessing</span> <span style="color: #8B008B; font-weight: bold">import</span> StandardScaler, OneHotEncoder
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.compose</span> <span style="color: #8B008B; font-weight: bold">import</span> ColumnTransformer
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> Image
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">pydot</span> <span style="color: #8B008B; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">os</span>
<span style="color: #228B22"># Where to save the figures and data files</span>
PROJECT_ROOT_DIR = <span style="color: #CD5555">&quot;Results&quot;</span>
FIGURE_ID = <span style="color: #CD5555">&quot;Results/FigureFiles&quot;</span>
DATA_ID = <span style="color: #CD5555">&quot;DataFiles/&quot;</span>
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">image_path</span>(fig_id):
<span style="color: #8B008B; font-weight: bold">return</span> os.path.join(FIGURE_ID, fig_id)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">data_path</span>(dat_id):
<span style="color: #8B008B; font-weight: bold">return</span> os.path.join(DATA_ID, dat_id)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">save_fig</span>(fig_id):
plt.savefig(image_path(fig_id) + <span style="color: #CD5555">&quot;.png&quot;</span>, <span style="color: #658b00">format</span>=<span style="color: #CD5555">&#39;png&#39;</span>)
infile = <span style="color: #658b00">open</span>(data_path(<span style="color: #CD5555">&quot;rideclass.csv&quot;</span>),<span style="color: #CD5555">&#39;r&#39;</span>)
<span style="color: #228B22"># Read the experimental data with Pandas</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> display
ridedata = pd.read_csv(infile,names = (<span style="color: #CD5555">&#39;Outlook&#39;</span>,<span style="color: #CD5555">&#39;Temperature&#39;</span>,<span style="color: #CD5555">&#39;Humidity&#39;</span>,<span style="color: #CD5555">&#39;Wind&#39;</span>,<span style="color: #CD5555">&#39;Ride&#39;</span>))
ridedata = pd.DataFrame(ridedata)
<span style="color: #228B22"># Features and targets</span>
X = ridedata.loc[:, ridedata.columns != <span style="color: #CD5555">&#39;Ride&#39;</span>].values
y = ridedata.loc[:, ridedata.columns == <span style="color: #CD5555">&#39;Ride&#39;</span>].values
<span style="color: #228B22"># Create the encoder.</span>
encoder = OneHotEncoder(handle_unknown=<span style="color: #CD5555">&quot;ignore&quot;</span>)
<span style="color: #228B22"># Assume for simplicity all features are categorical.</span>
encoder.fit(X)
<span style="color: #228B22"># Apply the encoder.</span>
X = encoder.transform(X)
<span style="color: #658b00">print</span>(X)
<span style="color: #228B22"># Then do a Classification tree</span>
tree_clf = DecisionTreeClassifier(max_depth=<span style="color: #B452CD">2</span>)
tree_clf.fit(X, y)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Train set accuracy with Decision Tree: {:.2f}&quot;</span>.format(tree_clf.score(X,y)))
<span style="color: #228B22">#transfer to a decision tree graph</span>
export_graphviz(
tree_clf,
out_file=<span style="color: #CD5555">&quot;DataFiles/ride.dot&quot;</span>,
rounded=<span style="color: #8B008B; font-weight: bold">True</span>,
filled=<span style="color: #8B008B; font-weight: bold">True</span>
)
cmd = <span style="color: #CD5555">&#39;dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png&#39;</span>
os.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>
</section>
<section>
<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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #228B22"># Split a dataset based on an attribute and an attribute value</span>
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">test_split</span>(index, value, dataset):
left, right = <span style="color: #658b00">list</span>(), <span style="color: #658b00">list</span>()
<span style="color: #8B008B; font-weight: bold">for</span> row <span style="color: #8B008B">in</span> dataset:
<span style="color: #8B008B; font-weight: bold">if</span> row[index] &lt; value:
left.append(row)
<span style="color: #8B008B; font-weight: bold">else</span>:
right.append(row)
<span style="color: #8B008B; font-weight: bold">return</span> left, right
<span style="color: #228B22"># Calculate the Gini index for a split dataset</span>
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">gini_index</span>(groups, classes):
<span style="color: #228B22"># count all samples at split point</span>
n_instances = <span style="color: #658b00">float</span>(<span style="color: #658b00">sum</span>([<span style="color: #658b00">len</span>(group) <span style="color: #8B008B; font-weight: bold">for</span> group <span style="color: #8B008B">in</span> groups]))
<span style="color: #228B22"># sum weighted Gini index for each group</span>
gini = <span style="color: #B452CD">0.0</span>
<span style="color: #8B008B; font-weight: bold">for</span> group <span style="color: #8B008B">in</span> groups:
size = <span style="color: #658b00">float</span>(<span style="color: #658b00">len</span>(group))
<span style="color: #228B22"># avoid divide by zero</span>
<span style="color: #8B008B; font-weight: bold">if</span> size == <span style="color: #B452CD">0</span>:
<span style="color: #8B008B; font-weight: bold">continue</span>
score = <span style="color: #B452CD">0.0</span>
<span style="color: #228B22"># score the group based on the score for each class</span>
<span style="color: #8B008B; font-weight: bold">for</span> class_val <span style="color: #8B008B">in</span> classes:
p = [row[-<span style="color: #B452CD">1</span>] <span style="color: #8B008B; font-weight: bold">for</span> row <span style="color: #8B008B">in</span> group].count(class_val) / size
score += p * p
<span style="color: #228B22"># weight the group score by its relative size</span>
gini += (<span style="color: #B452CD">1.0</span> - score) * (size / n_instances)
<span style="color: #8B008B; font-weight: bold">return</span> gini
<span style="color: #228B22"># Select the best split point for a dataset</span>
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">get_split</span>(dataset):
class_values = <span style="color: #658b00">list</span>(<span style="color: #658b00">set</span>(row[-<span style="color: #B452CD">1</span>] <span style="color: #8B008B; font-weight: bold">for</span> row <span style="color: #8B008B">in</span> dataset))
b_index, b_value, b_score, b_groups = <span style="color: #B452CD">999</span>, <span style="color: #B452CD">999</span>, <span style="color: #B452CD">999</span>, <span style="color: #8B008B; font-weight: bold">None</span>
<span style="color: #8B008B; font-weight: bold">for</span> index <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #658b00">len</span>(dataset[<span style="color: #B452CD">0</span>])-<span style="color: #B452CD">1</span>):
<span style="color: #8B008B; font-weight: bold">for</span> row <span style="color: #8B008B">in</span> dataset:
groups = test_split(index, row[index], dataset)
gini = gini_index(groups, class_values)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;X%d &lt; %.3f Gini=%.3f&#39;</span> % ((index+<span style="color: #B452CD">1</span>), row[index], gini))
<span style="color: #8B008B; font-weight: bold">if</span> gini &lt; b_score:
b_index, b_value, b_score, b_groups = index, row[index], gini, groups
<span style="color: #8B008B; font-weight: bold">return</span> {<span style="color: #CD5555">&#39;index&#39;</span>:b_index, <span style="color: #CD5555">&#39;value&#39;</span>:b_value, <span style="color: #CD5555">&#39;groups&#39;</span>:b_groups}
dataset = [[<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>],
[<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">2</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">2</span>,<span style="color: #B452CD">2</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">2</span>,<span style="color: #B452CD">2</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>],
[<span style="color: #B452CD">1</span>,<span style="color: #B452CD">2</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">0</span>],
[<span style="color: #B452CD">0</span>,<span style="color: #B452CD">2</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">2</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>],
[<span style="color: #B452CD">2</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>,<span style="color: #B452CD">1</span>,<span style="color: #B452CD">0</span>]]
split = get_split(dataset)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;Split: [X%d &lt; %.3f]&#39;</span> % ((split[<span style="color: #CD5555">&#39;index&#39;</span>]+<span style="color: #B452CD">1</span>), split[<span style="color: #CD5555">&#39;value&#39;</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>
</section>
<section>
<h2 id="regression-trees">Regression trees </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #228B22"># Quadratic training set + noise</span>
np.random.seed(<span style="color: #B452CD">42</span>)
m = <span style="color: #B452CD">200</span>
X = np.random.rand(m, <span style="color: #B452CD">1</span>)
y = <span style="color: #B452CD">4</span> * (X - <span style="color: #B452CD">0.5</span>) ** <span style="color: #B452CD">2</span>
y = y + np.random.randn(m, <span style="color: #B452CD">1</span>) / <span style="color: #B452CD">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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(max_depth=<span style="color: #B452CD">2</span>, random_state=<span style="color: #B452CD">42</span>)
tree_reg.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>
</section>
<section>
<h2 id="final-regressor-code">Final regressor code </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeRegressor
tree_reg1 = DecisionTreeRegressor(random_state=<span style="color: #B452CD">42</span>, max_depth=<span style="color: #B452CD">2</span>)
tree_reg2 = DecisionTreeRegressor(random_state=<span style="color: #B452CD">42</span>, max_depth=<span style="color: #B452CD">3</span>)
tree_reg1.fit(X, y)
tree_reg2.fit(X, y)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">plot_regression_predictions</span>(tree_reg, X, y, axes=[<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>, -<span style="color: #B452CD">0.2</span>, <span style="color: #B452CD">1</span>], ylabel=<span style="color: #CD5555">&quot;$y$&quot;</span>):
x1 = np.linspace(axes[<span style="color: #B452CD">0</span>], axes[<span style="color: #B452CD">1</span>], <span style="color: #B452CD">500</span>).reshape(-<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>)
y_pred = tree_reg.predict(x1)
plt.axis(axes)
plt.xlabel(<span style="color: #CD5555">&quot;$x_1$&quot;</span>, fontsize=<span style="color: #B452CD">18</span>)
<span style="color: #8B008B; font-weight: bold">if</span> ylabel:
plt.ylabel(ylabel, fontsize=<span style="color: #B452CD">18</span>, rotation=<span style="color: #B452CD">0</span>)
plt.plot(X, y, <span style="color: #CD5555">&quot;b.&quot;</span>)
plt.plot(x1, y_pred, <span style="color: #CD5555">&quot;r.-&quot;</span>, linewidth=<span style="color: #B452CD">2</span>, label=<span style="color: #CD5555">r&quot;$\hat{y}$&quot;</span>)
plt.figure(figsize=(<span style="color: #B452CD">11</span>, <span style="color: #B452CD">4</span>))
plt.subplot(<span style="color: #B452CD">121</span>)
plot_regression_predictions(tree_reg1, X, y)
<span style="color: #8B008B; font-weight: bold">for</span> split, style <span style="color: #8B008B">in</span> ((<span style="color: #B452CD">0.1973</span>, <span style="color: #CD5555">&quot;k-&quot;</span>), (<span style="color: #B452CD">0.0917</span>, <span style="color: #CD5555">&quot;k--&quot;</span>), (<span style="color: #B452CD">0.7718</span>, <span style="color: #CD5555">&quot;k--&quot;</span>)):
plt.plot([split, split], [-<span style="color: #B452CD">0.2</span>, <span style="color: #B452CD">1</span>], style, linewidth=<span style="color: #B452CD">2</span>)
plt.text(<span style="color: #B452CD">0.21</span>, <span style="color: #B452CD">0.65</span>, <span style="color: #CD5555">&quot;Depth=0&quot;</span>, fontsize=<span style="color: #B452CD">15</span>)
plt.text(<span style="color: #B452CD">0.01</span>, <span style="color: #B452CD">0.2</span>, <span style="color: #CD5555">&quot;Depth=1&quot;</span>, fontsize=<span style="color: #B452CD">13</span>)
plt.text(<span style="color: #B452CD">0.65</span>, <span style="color: #B452CD">0.8</span>, <span style="color: #CD5555">&quot;Depth=1&quot;</span>, fontsize=<span style="color: #B452CD">13</span>)
plt.legend(loc=<span style="color: #CD5555">&quot;upper center&quot;</span>, fontsize=<span style="color: #B452CD">18</span>)
plt.title(<span style="color: #CD5555">&quot;max_depth=2&quot;</span>, fontsize=<span style="color: #B452CD">14</span>)
plt.subplot(<span style="color: #B452CD">122</span>)
plot_regression_predictions(tree_reg2, X, y, ylabel=<span style="color: #8B008B; font-weight: bold">None</span>)
<span style="color: #8B008B; font-weight: bold">for</span> split, style <span style="color: #8B008B">in</span> ((<span style="color: #B452CD">0.1973</span>, <span style="color: #CD5555">&quot;k-&quot;</span>), (<span style="color: #B452CD">0.0917</span>, <span style="color: #CD5555">&quot;k--&quot;</span>), (<span style="color: #B452CD">0.7718</span>, <span style="color: #CD5555">&quot;k--&quot;</span>)):
plt.plot([split, split], [-<span style="color: #B452CD">0.2</span>, <span style="color: #B452CD">1</span>], style, linewidth=<span style="color: #B452CD">2</span>)
<span style="color: #8B008B; font-weight: bold">for</span> split <span style="color: #8B008B">in</span> (<span style="color: #B452CD">0.0458</span>, <span style="color: #B452CD">0.1298</span>, <span style="color: #B452CD">0.2873</span>, <span style="color: #B452CD">0.9040</span>):
plt.plot([split, split], [-<span style="color: #B452CD">0.2</span>, <span style="color: #B452CD">1</span>], <span style="color: #CD5555">&quot;k:&quot;</span>, linewidth=<span style="color: #B452CD">1</span>)
plt.text(<span style="color: #B452CD">0.3</span>, <span style="color: #B452CD">0.5</span>, <span style="color: #CD5555">&quot;Depth=2&quot;</span>, fontsize=<span style="color: #B452CD">13</span>)
plt.title(<span style="color: #CD5555">&quot;max_depth=3&quot;</span>, fontsize=<span style="color: #B452CD">14</span>)
plt.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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;">tree_reg1 = DecisionTreeRegressor(random_state=<span style="color: #B452CD">42</span>)
tree_reg2 = DecisionTreeRegressor(random_state=<span style="color: #B452CD">42</span>, min_samples_leaf=<span style="color: #B452CD">10</span>)
tree_reg1.fit(X, y)
tree_reg2.fit(X, y)
x1 = np.linspace(<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>, <span style="color: #B452CD">500</span>).reshape(-<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>)
y_pred1 = tree_reg1.predict(x1)
y_pred2 = tree_reg2.predict(x1)
plt.figure(figsize=(<span style="color: #B452CD">11</span>, <span style="color: #B452CD">4</span>))
plt.subplot(<span style="color: #B452CD">121</span>)
plt.plot(X, y, <span style="color: #CD5555">&quot;b.&quot;</span>)
plt.plot(x1, y_pred1, <span style="color: #CD5555">&quot;r.-&quot;</span>, linewidth=<span style="color: #B452CD">2</span>, label=<span style="color: #CD5555">r&quot;$\hat{y}$&quot;</span>)
plt.axis([<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>, -<span style="color: #B452CD">0.2</span>, <span style="color: #B452CD">1.1</span>])
plt.xlabel(<span style="color: #CD5555">&quot;$x_1$&quot;</span>, fontsize=<span style="color: #B452CD">18</span>)
plt.ylabel(<span style="color: #CD5555">&quot;$y$&quot;</span>, fontsize=<span style="color: #B452CD">18</span>, rotation=<span style="color: #B452CD">0</span>)
plt.legend(loc=<span style="color: #CD5555">&quot;upper center&quot;</span>, fontsize=<span style="color: #B452CD">18</span>)
plt.title(<span style="color: #CD5555">&quot;No restrictions&quot;</span>, fontsize=<span style="color: #B452CD">14</span>)
plt.subplot(<span style="color: #B452CD">122</span>)
plt.plot(X, y, <span style="color: #CD5555">&quot;b.&quot;</span>)
plt.plot(x1, y_pred2, <span style="color: #CD5555">&quot;r.-&quot;</span>, linewidth=<span style="color: #B452CD">2</span>, label=<span style="color: #CD5555">r&quot;$\hat{y}$&quot;</span>)
plt.axis([<span style="color: #B452CD">0</span>, <span style="color: #B452CD">1</span>, -<span style="color: #B452CD">0.2</span>, <span style="color: #B452CD">1.1</span>])
plt.xlabel(<span style="color: #CD5555">&quot;$x_1$&quot;</span>, fontsize=<span style="color: #B452CD">18</span>)
plt.title(<span style="color: #CD5555">&quot;min_samples_leaf={}&quot;</span>.format(tree_reg2.min_samples_leaf), fontsize=<span style="color: #B452CD">14</span>)
plt.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>
</section>
<section>
<h2 id="pros-and-cons-of-trees-pros">Pros and cons of trees, pros </h2>
<ul>
<p><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>
<p><li> Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!</li>
<p><li> No feature normalization needed</li>
<p><li> Tree models can handle both continuous and categorical data (Classification and Regression Trees)</li>
<p><li> Can model nonlinear relationships</li>
<p><li> Can model interactions between the different descriptive features</li>
<p><li> Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)</li>
</ul>
</section>
<section>
<h2 id="disadvantages">Disadvantages </h2>
<ul>
<p><li> Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches</li>
<p><li> If continuous features are used the tree may become quite large and hence less interpretable</li>
<p><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>
<p><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>
<p><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>
<p><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>
<p><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>
<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>
</section>
<section>
<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>
<p><li> Voting classifiers</li>
<p><li> Bagging and Pasting</li>
<p><li> Random forests</li>
<p><li> Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)</li>
</ol>
<p>
<p>We discuss these methods here.</p>
</section>
<section>
<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/>
</section>
<section>
<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>
</section>
<section>
<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>
</section>
<section>
<h2 id="standard-imports-first">Standard imports first </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #228B22"># Common imports</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> Image
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">pydot</span> <span style="color: #8B008B; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">pandas</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">pd</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> export_graphviz
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.preprocessing</span> <span style="color: #8B008B; font-weight: bold">import</span> StandardScaler, OneHotEncoder
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.compose</span> <span style="color: #8B008B; font-weight: bold">import</span> ColumnTransformer
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">IPython.display</span> <span style="color: #8B008B; font-weight: bold">import</span> Image
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">pydot</span> <span style="color: #8B008B; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">os</span>
<span style="color: #228B22"># Where to save the figures and data files</span>
PROJECT_ROOT_DIR = <span style="color: #CD5555">&quot;Results&quot;</span>
FIGURE_ID = <span style="color: #CD5555">&quot;Results/FigureFiles&quot;</span>
DATA_ID = <span style="color: #CD5555">&quot;DataFiles/&quot;</span>
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
<span style="color: #8B008B; font-weight: bold">if</span> <span style="color: #8B008B">not</span> os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">image_path</span>(fig_id):
<span style="color: #8B008B; font-weight: bold">return</span> os.path.join(FIGURE_ID, fig_id)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">data_path</span>(dat_id):
<span style="color: #8B008B; font-weight: bold">return</span> os.path.join(DATA_ID, dat_id)
<span style="color: #8B008B; font-weight: bold">def</span> <span style="color: #008b45">save_fig</span>(fig_id):
plt.savefig(image_path(fig_id) + <span style="color: #CD5555">&quot;.png&quot;</span>, <span style="color: #658b00">format</span>=<span style="color: #CD5555">&#39;png&#39;</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>
</section>
<section>
<h2 id="simple-voting-example-head-or-tail">Simple Voting Example, head or tail </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #228B22"># Common imports</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">matplotlib.colors</span> <span style="color: #8B008B; font-weight: bold">import</span> ListedColormap
plt.rcParams[<span style="color: #CD5555">&#39;axes.labelsize&#39;</span>] = <span style="color: #B452CD">14</span>
plt.rcParams[<span style="color: #CD5555">&#39;xtick.labelsize&#39;</span>] = <span style="color: #B452CD">12</span>
plt.rcParams[<span style="color: #CD5555">&#39;ytick.labelsize&#39;</span>] = <span style="color: #B452CD">12</span>
heads_proba = <span style="color: #B452CD">0.51</span>
coin_tosses = (np.random.rand(<span style="color: #B452CD">10000</span>, <span style="color: #B452CD">10</span>) &lt; heads_proba).astype(np.int32)
cumulative_heads_ratio = np.cumsum(coin_tosses, axis=<span style="color: #B452CD">0</span>) / np.arange(<span style="color: #B452CD">1</span>, <span style="color: #B452CD">10001</span>).reshape(-<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>)
plt.figure(figsize=(<span style="color: #B452CD">8</span>,<span style="color: #B452CD">3.5</span>))
plt.plot(cumulative_heads_ratio)
plt.plot([<span style="color: #B452CD">0</span>, <span style="color: #B452CD">10000</span>], [<span style="color: #B452CD">0.51</span>, <span style="color: #B452CD">0.51</span>], <span style="color: #CD5555">&quot;k--&quot;</span>, linewidth=<span style="color: #B452CD">2</span>, label=<span style="color: #CD5555">&quot;51%&quot;</span>)
plt.plot([<span style="color: #B452CD">0</span>, <span style="color: #B452CD">10000</span>], [<span style="color: #B452CD">0.5</span>, <span style="color: #B452CD">0.5</span>], <span style="color: #CD5555">&quot;k-&quot;</span>, label=<span style="color: #CD5555">&quot;50%&quot;</span>)
plt.xlabel(<span style="color: #CD5555">&quot;Number of coin tosses&quot;</span>)
plt.ylabel(<span style="color: #CD5555">&quot;Heads ratio&quot;</span>)
plt.legend(loc=<span style="color: #CD5555">&quot;lower right&quot;</span>)
plt.axis([<span style="color: #B452CD">0</span>, <span style="color: #B452CD">10000</span>, <span style="color: #B452CD">0.42</span>, <span style="color: #B452CD">0.58</span>])
save_fig(<span style="color: #CD5555">&quot;votingsimple&quot;</span>)
plt.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>
</section>
<section>
<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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> make_moons
X, y = make_moons(n_samples=<span style="color: #B452CD">500</span>, noise=<span style="color: #B452CD">0.30</span>, random_state=<span style="color: #B452CD">42</span>)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=<span style="color: #B452CD">42</span>)
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> RandomForestClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> VotingClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.linear_model</span> <span style="color: #8B008B; font-weight: bold">import</span> LogisticRegression
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.svm</span> <span style="color: #8B008B; font-weight: bold">import</span> SVC
log_clf = LogisticRegression(solver=<span style="color: #CD5555">&quot;liblinear&quot;</span>, random_state=<span style="color: #B452CD">42</span>)
rnd_clf = RandomForestClassifier(n_estimators=<span style="color: #B452CD">10</span>, random_state=<span style="color: #B452CD">42</span>)
svm_clf = SVC(gamma=<span style="color: #CD5555">&quot;auto&quot;</span>, random_state=<span style="color: #B452CD">42</span>)
voting_clf = VotingClassifier(
estimators=[(<span style="color: #CD5555">&#39;lr&#39;</span>, log_clf), (<span style="color: #CD5555">&#39;rf&#39;</span>, rnd_clf), (<span style="color: #CD5555">&#39;svc&#39;</span>, svm_clf)],
voting=<span style="color: #CD5555">&#39;hard&#39;</span>)
voting_clf.fit(X_train, y_train)
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.metrics</span> <span style="color: #8B008B; font-weight: bold">import</span> accuracy_score
<span style="color: #8B008B; font-weight: bold">for</span> clf <span style="color: #8B008B">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
<span style="color: #658b00">print</span>(clf.<span style="color: #00688B">__class__</span>.<span style="color: #00688B">__name__</span>, accuracy_score(y_test, y_pred))
log_clf = LogisticRegression(solver=<span style="color: #CD5555">&quot;liblinear&quot;</span>, random_state=<span style="color: #B452CD">42</span>)
rnd_clf = RandomForestClassifier(n_estimators=<span style="color: #B452CD">10</span>, random_state=<span style="color: #B452CD">42</span>)
svm_clf = SVC(gamma=<span style="color: #CD5555">&quot;auto&quot;</span>, probability=<span style="color: #8B008B; font-weight: bold">True</span>, random_state=<span style="color: #B452CD">42</span>)
voting_clf = VotingClassifier(
estimators=[(<span style="color: #CD5555">&#39;lr&#39;</span>, log_clf), (<span style="color: #CD5555">&#39;rf&#39;</span>, rnd_clf), (<span style="color: #CD5555">&#39;svc&#39;</span>, svm_clf)],
voting=<span style="color: #CD5555">&#39;soft&#39;</span>)
voting_clf.fit(X_train, y_train)
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.metrics</span> <span style="color: #8B008B; font-weight: bold">import</span> accuracy_score
<span style="color: #8B008B; font-weight: bold">for</span> clf <span style="color: #8B008B">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
<span style="color: #658b00">print</span>(clf.<span style="color: #00688B">__class__</span>.<span style="color: #00688B">__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>
</section>
<section>
<h2 id="voting-and-bagging">Voting and Bagging </h2>
<!-- code=python (!bc pycod) typeset with pygments style "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> make_moons
X, y = make_moons(n_samples=<span style="color: #B452CD">500</span>, noise=<span style="color: #B452CD">0.30</span>, random_state=<span style="color: #B452CD">42</span>)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=<span style="color: #B452CD">42</span>)
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> RandomForestClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> VotingClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.linear_model</span> <span style="color: #8B008B; font-weight: bold">import</span> LogisticRegression
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.svm</span> <span style="color: #8B008B; font-weight: bold">import</span> SVC
log_clf = LogisticRegression(random_state=<span style="color: #B452CD">42</span>)
rnd_clf = RandomForestClassifier(random_state=<span style="color: #B452CD">42</span>)
svm_clf = SVC(random_state=<span style="color: #B452CD">42</span>)
voting_clf = VotingClassifier(
estimators=[(<span style="color: #CD5555">&#39;lr&#39;</span>, log_clf), (<span style="color: #CD5555">&#39;rf&#39;</span>, rnd_clf), (<span style="color: #CD5555">&#39;svc&#39;</span>, svm_clf)],
voting=<span style="color: #CD5555">&#39;hard&#39;</span>)
voting_clf.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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.metrics</span> <span style="color: #8B008B; font-weight: bold">import</span> accuracy_score
<span style="color: #8B008B; font-weight: bold">for</span> clf <span style="color: #8B008B">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
<span style="color: #658b00">print</span>(clf.<span style="color: #00688B">__class__</span>.<span style="color: #00688B">__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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;">log_clf = LogisticRegression(random_state=<span style="color: #B452CD">42</span>)
rnd_clf = RandomForestClassifier(random_state=<span style="color: #B452CD">42</span>)
svm_clf = SVC(probability=<span style="color: #8B008B; font-weight: bold">True</span>, random_state=<span style="color: #B452CD">42</span>)
voting_clf = VotingClassifier(
estimators=[(<span style="color: #CD5555">&#39;lr&#39;</span>, log_clf), (<span style="color: #CD5555">&#39;rf&#39;</span>, rnd_clf), (<span style="color: #CD5555">&#39;svc&#39;</span>, svm_clf)],
voting=<span style="color: #CD5555">&#39;soft&#39;</span>)
voting_clf.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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.metrics</span> <span style="color: #8B008B; font-weight: bold">import</span> accuracy_score
<span style="color: #8B008B; font-weight: bold">for</span> clf <span style="color: #8B008B">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
<span style="color: #658b00">print</span>(clf.<span style="color: #00688B">__class__</span>.<span style="color: #00688B">__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>
</section>
<section>
<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>
</section>
<section>
<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>
</section>
<section>
<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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.pipeline</span> <span style="color: #8B008B; font-weight: bold">import</span> make_pipeline
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.utils</span> <span style="color: #8B008B; font-weight: bold">import</span> resample
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeRegressor
n = <span style="color: #B452CD">100</span>
n_boostraps = <span style="color: #B452CD">100</span>
maxdepth = <span style="color: #B452CD">8</span>
<span style="color: #228B22"># Make data set.</span>
x = np.linspace(-<span style="color: #B452CD">3</span>, <span style="color: #B452CD">3</span>, n).reshape(-<span style="color: #B452CD">1</span>, <span style="color: #B452CD">1</span>)
y = np.exp(-x**<span style="color: #B452CD">2</span>) + <span style="color: #B452CD">1.5</span> * np.exp(-(x-<span style="color: #B452CD">2</span>)**<span style="color: #B452CD">2</span>)+ np.random.normal(<span style="color: #B452CD">0</span>, <span style="color: #B452CD">0.1</span>, x.shape)
error = np.zeros(maxdepth)
bias = np.zeros(maxdepth)
variance = np.zeros(maxdepth)
polydegree = np.zeros(maxdepth)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=<span style="color: #B452CD">0.2</span>)
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.preprocessing</span> <span style="color: #8B008B; font-weight: bold">import</span> StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
<span style="color: #228B22"># we produce a simple tree first as benchmark</span>
simpletree = DecisionTreeRegressor(max_depth=<span style="color: #B452CD">3</span>)
simpletree.fit(X_train_scaled, y_train)
simpleprediction = simpletree.predict(X_test_scaled)
<span style="color: #8B008B; font-weight: bold">for</span> degree <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(<span style="color: #B452CD">1</span>,maxdepth):
model = DecisionTreeRegressor(max_depth=degree)
y_pred = np.empty((y_test.shape[<span style="color: #B452CD">0</span>], n_boostraps))
<span style="color: #8B008B; font-weight: bold">for</span> i <span style="color: #8B008B">in</span> <span style="color: #658b00">range</span>(n_boostraps):
x_, y_ = resample(X_train_scaled, y_train)
model.fit(x_, y_)
y_pred[:, i] = model.predict(X_test_scaled)<span style="color: #228B22">#.ravel()</span>
polydegree[degree] = degree
error[degree] = np.mean( np.mean((y_test - y_pred)**<span style="color: #B452CD">2</span>, axis=<span style="color: #B452CD">1</span>, keepdims=<span style="color: #8B008B; font-weight: bold">True</span>) )
bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=<span style="color: #B452CD">1</span>, keepdims=<span style="color: #8B008B; font-weight: bold">True</span>))**<span style="color: #B452CD">2</span> )
variance[degree] = np.mean( np.var(y_pred, axis=<span style="color: #B452CD">1</span>, keepdims=<span style="color: #8B008B; font-weight: bold">True</span>) )
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;Polynomial degree:&#39;</span>, degree)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;Error:&#39;</span>, error[degree])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;Bias^2:&#39;</span>, bias[degree])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;Var:&#39;</span>, variance[degree])
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&#39;{} &gt;= {} + {} = {}&#39;</span>.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**<span style="color: #B452CD">2</span>))
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Simple tree:&quot;</span>,mse_simpletree)
plt.xlim(<span style="color: #B452CD">1</span>,maxdepth)
plt.plot(polydegree, error, label=<span style="color: #CD5555">&#39;MSE&#39;</span>)
plt.plot(polydegree, bias, label=<span style="color: #CD5555">&#39;bias&#39;</span>)
plt.plot(polydegree, variance, label=<span style="color: #CD5555">&#39;Variance&#39;</span>)
plt.legend()
save_fig(<span style="color: #CD5555">&quot;baggingboot&quot;</span>)
plt.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>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
m\approx \sqrt{p}.
$$
<p>&nbsp;<br>
<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>
</section>
<section>
<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>
<p><li> For \( b=1:B \)</li>
<ul>
<p><li> Draw a bootstrap sample from the training data organized in our \( \boldsymbol{X} \) matrix.</li>
<p><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>
<p><li> we select \( m \le p \) variables at random from the \( p \) predictors/features</li>
<p><li> pick the best split point among the \( m \) features using for example the CART algorithm and create a new node</li>
<p><li> split the node into daughter nodes</li>
</ol>
<p>
</ul>
<p>
<p><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>
</section>
<section>
<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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">matplotlib.pyplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">plt</span>
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">numpy</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">np</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> train_test_split
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.datasets</span> <span style="color: #8B008B; font-weight: bold">import</span> load_breast_cancer
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.svm</span> <span style="color: #8B008B; font-weight: bold">import</span> SVC
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.linear_model</span> <span style="color: #8B008B; font-weight: bold">import</span> LogisticRegression
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.tree</span> <span style="color: #8B008B; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> BaggingClassifier
<span style="color: #228B22"># Load the data</span>
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=<span style="color: #B452CD">0</span>)
<span style="color: #658b00">print</span>(X_train.shape)
<span style="color: #658b00">print</span>(X_test.shape)
<span style="color: #228B22">#define methods</span>
<span style="color: #228B22"># Logistic Regression</span>
logreg = LogisticRegression(solver=<span style="color: #CD5555">&#39;lbfgs&#39;</span>)
<span style="color: #228B22"># Support vector machine</span>
svm = SVC(gamma=<span style="color: #CD5555">&#39;auto&#39;</span>, C=<span style="color: #B452CD">100</span>)
<span style="color: #228B22"># Decision Trees</span>
deep_tree_clf = DecisionTreeClassifier(max_depth=<span style="color: #8B008B; font-weight: bold">None</span>)
<span style="color: #228B22">#Scale the data</span>
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.preprocessing</span> <span style="color: #8B008B; font-weight: bold">import</span> StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
<span style="color: #228B22"># Logistic Regression</span>
logreg.fit(X_train_scaled, y_train)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy Logistic Regression with scaled data: {:.2f}&quot;</span>.format(logreg.score(X_test_scaled,y_test)))
<span style="color: #228B22"># Support Vector Machine</span>
svm.fit(X_train_scaled, y_train)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy SVM with scaled data: {:.2f}&quot;</span>.format(logreg.score(X_test_scaled,y_test)))
<span style="color: #228B22"># Decision Trees</span>
deep_tree_clf.fit(X_train_scaled, y_train)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy with Decision Trees and scaled data: {:.2f}&quot;</span>.format(deep_tree_clf.score(X_test_scaled,y_test)))
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> RandomForestClassifier
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.preprocessing</span> <span style="color: #8B008B; font-weight: bold">import</span> LabelEncoder
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.model_selection</span> <span style="color: #8B008B; font-weight: bold">import</span> cross_validate
<span style="color: #228B22"># Data set not specificied</span>
<span style="color: #228B22">#Instantiate the model with 500 trees and entropy as splitting criteria</span>
Random_Forest_model = RandomForestClassifier(n_estimators=<span style="color: #B452CD">500</span>,criterion=<span style="color: #CD5555">&quot;entropy&quot;</span>)
Random_Forest_model.fit(X_train_scaled, y_train)
<span style="color: #228B22">#Cross validation</span>
accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=<span style="color: #B452CD">10</span>)[<span style="color: #CD5555">&#39;test_score&#39;</span>]
<span style="color: #658b00">print</span>(accuracy)
<span style="color: #658b00">print</span>(<span style="color: #CD5555">&quot;Test set accuracy with Random Forests and scaled data: {:.2f}&quot;</span>.format(Random_Forest_model.score(X_test_scaled,y_test)))
<span style="color: #8B008B; font-weight: bold">import</span> <span style="color: #008b45; text-decoration: underline">scikitplot</span> <span style="color: #8B008B; font-weight: bold">as</span> <span style="color: #008b45; text-decoration: underline">skplt</span>
y_pred = Random_Forest_model.predict(X_test_scaled)
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=<span style="color: #8B008B; font-weight: bold">True</span>)
plt.show()
y_probas = Random_Forest_model.predict_proba(X_test_scaled)
skplt.metrics.plot_roc(y_test, y_probas)
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()
</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>
</section>
<section>
<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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;">bag_clf = BaggingClassifier(
DecisionTreeClassifier(splitter=<span style="color: #CD5555">&quot;random&quot;</span>, max_leaf_nodes=<span style="color: #B452CD">16</span>, random_state=<span style="color: #B452CD">42</span>),
n_estimators=<span style="color: #B452CD">500</span>, max_samples=<span style="color: #B452CD">1.0</span>, bootstrap=<span style="color: #8B008B; font-weight: bold">True</span>, n_jobs=-<span style="color: #B452CD">1</span>, random_state=<span style="color: #B452CD">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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;">bag_clf.fit(X_train, y_train)
y_pred = bag_clf.predict(X_test)
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> RandomForestClassifier
rnd_clf = RandomForestClassifier(n_estimators=<span style="color: #B452CD">500</span>, max_leaf_nodes=<span style="color: #B452CD">16</span>, n_jobs=-<span style="color: #B452CD">1</span>, random_state=<span style="color: #B452CD">42</span>)
rnd_clf.fit(X_train, y_train)
y_pred_rf = rnd_clf.predict(X_test)
np.sum(y_pred == y_pred_rf) / <span style="color: #658b00">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>
</section>
<section>
<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>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
$$
<p>&nbsp;<br>
<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>
<p>&nbsp;<br>
$$
\sigma(t) = \frac{1}{1+\exp{(-t)}},
$$
<p>&nbsp;<br>
<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>
<p>&nbsp;<br>
$$
C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
<p>&nbsp;<br>
<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>
<p>&nbsp;<br>
$$
\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
<p>&nbsp;<br>
<p>In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).</p>
</section>
<section>
<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>
<p><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>
<p><li> Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.</li>
<p><li> For \( m=1:M \)
<ol type="a"></li>
<p><li> minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)</li>
<p><li> This gives the optimal values \( \beta_m \) and \( \gamma_m \)</li>
<p><li> Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)</li>
</ol>
<p>
</ol>
<p>
<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>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
(\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>&nbsp;<br>
<p>We start our iteration by simply setting \( f_0(x)=0 \).
Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
</p>
<p>&nbsp;<br>
$$
\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
$$
<p>&nbsp;<br>
<p>and</p>
<p>&nbsp;<br>
$$
\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
$$
<p>&nbsp;<br>
<p>We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)</p>
<p>&nbsp;<br>
$$
\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0,
$$
<p>&nbsp;<br>
<p>which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have </p>
<p>&nbsp;<br>
$$
\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0,
$$
<p>&nbsp;<br>
<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>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
$$
<p>&nbsp;<br>
<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>
<p>&nbsp;<br>
$$
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
$$
<p>&nbsp;<br>
<p>will be a function of </p>
<p>&nbsp;<br>
$$
G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
$$
<p>&nbsp;<br>
</section>
<section>
<h2 id="adaptive-boosting-adaboost">Adaptive Boosting, AdaBoost </h2>
<p>In our iterative procedure we define thus</p>
<p>&nbsp;<br>
$$
f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
$$
<p>&nbsp;<br>
<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>
<p>&nbsp;<br>
$$
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
$$
<p>&nbsp;<br>
<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>
<p>&nbsp;<br>
$$
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
$$
<p>&nbsp;<br>
<p>where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).</p>
</section>
<section>
<h2 id="building-up-adaboost">Building up AdaBoost </h2>
<p>First, for any \( \beta > 0 \), we optimize \( G \) by setting</p>
<p>&nbsp;<br>
$$
G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
$$
<p>&nbsp;<br>
<p>which is the classifier that minimizes the weighted error rate in predicting \( y \).</p>
<p>We can do this by rewriting</p>
<p>&nbsp;<br>
$$
\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
$$
<p>&nbsp;<br>
<p>which can be rewritten as</p>
<p>&nbsp;<br>
$$
(\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>&nbsp;<br>
<p>which leads to</p>
<p>&nbsp;<br>
$$
\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
$$
<p>&nbsp;<br>
<p>where we have redefined the error as </p>
<p>&nbsp;<br>
$$
\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>&nbsp;<br>
<p>which leads to an update of</p>
<p>&nbsp;<br>
$$
f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
$$
<p>&nbsp;<br>
<p>This leads to the new weights</p>
<p>&nbsp;<br>
$$
w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
$$
<p>&nbsp;<br>
</section>
<section>
<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>
<p>&nbsp;<br>
$$
\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
$$
<p>&nbsp;<br>
<p>where the function \( I() \) is one if we misclassify and zero if we classify correctly. </p>
</section>
<section>
<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>
<p><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>
<p><li> We rewrite the misclassification error as</li>
</ol>
<p>
<p>&nbsp;<br>
$$
\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},
$$
<p>&nbsp;<br>
<ol>
<p><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>
<p><li> Fit then a given classifier to the training set using the weights \( w_i \).</li>
<p><li> Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.</li>
<p><li> Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)</li>
<p><li> Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).</li>
</ol>
<p>
<p><li> Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).</li>
</ol>
<p>
<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>
</section>
<section>
<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 "perldoc" -->
<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: #eeeedd">
<pre style="font-size: 80%; line-height: 125%;"><span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> AdaBoostClassifier
ada_clf = AdaBoostClassifier(
DecisionTreeClassifier(max_depth=<span style="color: #B452CD">1</span>), n_estimators=<span style="color: #B452CD">200</span>,
algorithm=<span style="color: #CD5555">&quot;SAMME.R&quot;</span>, learning_rate=<span style="color: #B452CD">0.5</span>, random_state=<span style="color: #B452CD">42</span>)
ada_clf.fit(X_train, y_train)
<span style="color: #8B008B; font-weight: bold">from</span> <span style="color: #008b45; text-decoration: underline">sklearn.ensemble</span> <span style="color: #8B008B; font-weight: bold">import</span> AdaBoostClassifier
ada_clf = AdaBoostClassifier(
DecisionTreeClassifier(max_depth=<span style="color: #B452CD">1</span>), n_estimators=<span style="color: #B452CD">200</span>,
algorithm=<span style="color: #CD5555">&quot;SAMME.R&quot;</span>, learning_rate=<span style="color: #B452CD">0.5</span>, random_state=<span style="color: #B452CD">42</span>)
ada_clf.fit(X_train_scaled, y_train)
y_pred = ada_clf.predict(X_test_scaled)
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=<span style="color: #8B008B; font-weight: bold">True</span>)
plt.show()
y_probas = ada_clf.predict_proba(X_test_scaled)
skplt.metrics.plot_roc(y_test, y_probas)
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()
</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>
</section>
</div> <!-- class="slides" -->
</div> <!-- class="reveal" -->
<script src="reveal.js/lib/js/head.min.js"></script>
<script src="reveal.js/js/reveal.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
// Display navigation controls in the bottom right corner
controls: true,
// Display progress bar (below the horiz. slider)
progress: true,
// Display the page number of the current slide
slideNumber: true,
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Enable the slide overview mode
overview: true,
// Vertical centering of slides
//center: true,
center: false,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Hides the address bar on mobile devices
hideAddressBar: true,
// Opens links in an iframe preview overlay
previewLinks: false,
// Transition style
transition: 'default', // default/cube/page/concave/zoom/linear/fade/none
// Transition speed
transitionSpeed: 'default', // default/fast/slow
// Transition style for full page slide backgrounds
backgroundTransition: 'default', // default/none/slide/concave/convex/zoom
// Number of slides away from the current that are visible
viewDistance: 3,
// Parallax background image
//parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
// Parallax background size
//parallaxBackgroundSize: '' // CSS syntax, e.g. "2100px 900px"
theme: Reveal.getQueryHash().theme, // available themes are in reveal.js/css/theme
transition: Reveal.getQueryHash().transition || 'none', // default/cube/page/concave/zoom/linear/none
});
Reveal.initialize({
dependencies: [
// Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/
{ src: 'reveal.js/lib/js/classList.js', condition: function() { return !document.body.classList; } },
// Interpret Markdown in <section> elements
{ src: 'reveal.js/plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'reveal.js/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
// Syntax highlight for <code> elements
{ src: 'reveal.js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
// Zoom in and out with Alt+click
{ src: 'reveal.js/plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
// Speaker notes
{ src: 'reveal.js/plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } },
// Remote control your reveal.js presentation using a touch device
//{ src: 'reveal.js/plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } },
// MathJax
//{ src: 'reveal.js/plugin/math/math.js', async: true }
]
});
Reveal.initialize({
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions. Can be
// specified using percentage units.
width: 1170, // original: 960,
height: 700,
// Factor of the display size that should remain empty around the content
margin: 0.1,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 1.0
});
</script>
<!-- begin footer logo
<div style="position: absolute; bottom: 0px; left: 0; margin-left: 0px">
<img src="somelogo.png">
</div>
end footer logo -->
</body>
</html>