Files
FYS-STK4155/doc/pub/week44/html/week44.html
T
Morten Hjorth-Jensen d4628d5ab0 updating
2022-08-23 11:02:37 +02:00

3045 lines
208 KiB
HTML

<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week44.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week44 --no_mako
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/doconce/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees">
<title>Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees</title>
<style type="text/css">
/* bloodish style */
body {
font-family: Helvetica, Verdana, Arial, Sans-serif;
color: #404040;
background: #ffffff;
}
h1 { font-size: 1.8em; color: #8A0808; }
h2 { font-size: 1.6em; color: #8A0808; }
h3 { font-size: 1.4em; color: #8A0808; }
h4 { font-size: 1.2em; color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
p { text-indent: 0px; }
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
p.caption { width: 80%; font-style: normal; text-align: left; }
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa; }div.highlight {
border: 1px solid #cfcfcf;
border-radius: 2px;
line-height: 1.21429em;
}
div.cell {
width: 100%;
padding: 5px 5px 5px 0;
margin: 0;
outline: none;
}
div.input {
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.inner_cell {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
box-flex: 1;
flex: 1;
}
div.input_area {
border: 1px solid #cfcfcf;
border-radius: 4px;
background: #f7f7f7;
line-height: 1.21429em;
}
div.input_area > div.highlight {
margin: .4em;
border: none;
padding: 0;
background-color: transparent;
}
div.output_wrapper {
position: relative;
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
.output {
box-orient: vertical;
box-align: stretch;
display: flex;
flex-direction: column;
align-items: stretch;
}
div.output_area {
padding: 0;
page-break-inside: avoid;
box-orient: horizontal;
box-align: stretch;
display: flex;
flex-direction: row;
align-items: stretch;
}
div.output_subarea {
padding: .4em .4em 0 .4em;
box-flex: 1;
flex: 1;
}
div.output_text {
text-align: left;
color: #000;
line-height: 1.21429em;
}
.alert-text-small { font-size: 80%; }
.alert-text-large { font-size: 130%; }
.alert-text-normal { font-size: 90%; }
.alert {
padding:8px 35px 8px 14px; margin-bottom:18px;
text-shadow:0 1px 0 rgba(255,255,255,0.5);
border:1px solid #bababa;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
color: #555;
background-color: #f8f8f8;
background-position: 10px 5px;
background-repeat: no-repeat;
background-size: 38px;
padding-left: 55px;
width: 75%;
}
.alert-block {padding-top:14px; padding-bottom:14px}
.alert-block > p, .alert-block > ul {margin-bottom:1em}
.alert li {margin-top: 1em}
.alert-block p+p {margin-top:5px}
.alert-notice { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_notice.png); }
.alert-summary { background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_summary.png); }
.alert-warning { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_warning.png); }
.alert-question {background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_gray_question.png); }
div { text-align: justify; text-justify: inter-word; }
.tab {
padding-left: 1.5em;
}
div.toc p,a {
line-height: 1.3;
margin-top: 1.1;
margin-bottom: 1.1;
}
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Overview of week 44', 2, None, 'overview-of-week-44'),
('Digression First', 2, None, 'digression-first'),
('A short Discussion of Project 2',
2,
None,
'a-short-discussion-of-project-2'),
('Learning Rate and more', 2, None, 'learning-rate-and-more'),
('Thursday, Principal Component Analysis',
2,
None,
'thursday-principal-component-analysis'),
("A kind of Bird's view on PCA",
2,
None,
'a-kind-of-bird-s-view-on-pca'),
('Thursday: Clustering and Unsupervised Learning',
2,
None,
'thursday-clustering-and-unsupervised-learning'),
('Basic Idea of the $k$-means Clustering Algorithm',
2,
None,
'basic-idea-of-the-k-means-clustering-algorithm'),
('The $k$-means Algorithm', 2, None, 'the-k-means-algorithm'),
('Basic Math of the $k$-means Algorithm',
2,
None,
'basic-math-of-the-k-means-algorithm'),
('Within Cluster Point Scatter',
2,
None,
'within-cluster-point-scatter'),
('More Details', 2, None, 'more-details'),
('Total Cluster Variance', 2, None, 'total-cluster-variance'),
('The $k$-means Clustering Algorithm',
2,
None,
'the-k-means-clustering-algorithm'),
('Summarizing', 2, None, 'summarizing'),
('Writing our own Code, the Data Set',
2,
None,
'writing-our-own-code-the-data-set'),
('Implementing the $k$-means Algorithm',
2,
None,
'implementing-the-k-means-algorithm'),
('Plotting', 2, None, 'plotting'),
('Continuing', 2, None, 'continuing'),
('Wrapping it up', 2, None, 'wrapping-it-up'),
('Decision trees, overarching aims',
2,
None,
'decision-trees-overarching-aims'),
('Basics of a tree', 2, None, 'basics-of-a-tree'),
('A Sketch of a Tree, Regression problem',
2,
None,
'a-sketch-of-a-tree-regression-problem'),
('A Sketch of a Tree, Classification problem',
2,
None,
'a-sketch-of-a-tree-classification-problem'),
('A typical Decision Tree with its pertinent Jargon, '
'Classification Problem',
2,
None,
'a-typical-decision-tree-with-its-pertinent-jargon-classification-problem'),
('General Features', 2, None, 'general-features'),
('How do we set it up?', 2, None, 'how-do-we-set-it-up'),
('Decision trees and Regression',
2,
None,
'decision-trees-and-regression'),
('Building a tree, regression',
2,
None,
'building-a-tree-regression'),
('A top-down approach, recursive binary splitting',
2,
None,
'a-top-down-approach-recursive-binary-splitting'),
('Making a tree', 2, None, 'making-a-tree'),
('Pruning the tree', 2, None, 'pruning-the-tree'),
('Cost complexity pruning', 2, None, 'cost-complexity-pruning'),
('Schematic Regression Procedure',
2,
None,
'schematic-regression-procedure'),
('A Classification Tree', 2, None, 'a-classification-tree'),
('Growing a classification tree',
2,
None,
'growing-a-classification-tree'),
('Classification tree, how to split nodes',
2,
None,
'classification-tree-how-to-split-nodes'),
('Visualizing the Tree, Classification',
2,
None,
'visualizing-the-tree-classification'),
('Visualizing the Tree, The Moons',
2,
None,
'visualizing-the-tree-the-moons'),
('Other ways of visualizing the trees',
2,
None,
'other-ways-of-visualizing-the-trees'),
('Printing out as text', 2, None, 'printing-out-as-text'),
('Algorithms for Setting up Decision Trees',
2,
None,
'algorithms-for-setting-up-decision-trees'),
('The CART algorithm for Classification',
2,
None,
'the-cart-algorithm-for-classification'),
('The CART algorithm for Regression',
2,
None,
'the-cart-algorithm-for-regression'),
('Computing the Gini index', 2, None, 'computing-the-gini-index'),
('Simple Python Code to read in Data and perform Classification',
2,
None,
'simple-python-code-to-read-in-data-and-perform-classification'),
('Computing the Gini Factor',
2,
None,
'computing-the-gini-factor'),
('Entropy and the ID3 algorithm',
2,
None,
'entropy-and-the-id3-algorithm'),
('Cancer Data again now with Decision Trees and other Methods',
2,
None,
'cancer-data-again-now-with-decision-trees-and-other-methods'),
('Another example, the moons again',
2,
None,
'another-example-the-moons-again'),
('Playing around with regions',
2,
None,
'playing-around-with-regions'),
('Regression trees', 2, None, 'regression-trees'),
('Final regressor code', 2, None, 'final-regressor-code'),
('Pros and cons of trees, pros',
2,
None,
'pros-and-cons-of-trees-pros'),
('Disadvantages', 2, None, 'disadvantages'),
('Ensemble Methods: From a Single Tree to Many Trees and Extreme '
'Boosting, Meet the Jungle of Methods',
2,
None,
'ensemble-methods-from-a-single-tree-to-many-trees-and-extreme-boosting-meet-the-jungle-of-methods'),
('An Overview of Ensemble Methods',
2,
None,
'an-overview-of-ensemble-methods'),
('Bagging', 2, None, 'bagging'),
('More bagging', 2, None, 'more-bagging'),
('Simple Voting Example, head or tail',
2,
None,
'simple-voting-example-head-or-tail'),
('Using the Voting Classifier',
2,
None,
'using-the-voting-classifier'),
('Please, not the moons again! Voting and Bagging',
2,
None,
'please-not-the-moons-again-voting-and-bagging'),
('Bagging Examples', 2, None, 'bagging-examples'),
('Making your own Bootstrap: Changing the Level of the Decision '
'Tree',
2,
None,
'making-your-own-bootstrap-changing-the-level-of-the-decision-tree')]}
end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "AMS" },
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
}
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- ------------------- main content ---------------------- -->
<center>
<h1>Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees</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>Aug 23, 2022</h4>
</center> <!-- date -->
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="overview-of-week-44">Overview of week 44 </h2>
<ul>
<li> Thursday: Wrapping up PCA from last week, Clustering and basics of decision trees, classification and regression algorithms</li>
<li> Friday: Decision trees, voting models and bagging</li>
</ul>
<div class="alert alert-block alert-block alert-text-normal">
<b>Videos</b>
<p>
<ol>
<li> <a href="https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn" target="_blank">Video on Decision trees</a></li>
<li> <a href="https://www.youtube.com/watch?v=FgakZw6K1QQ&ab_channel=StatQuestwithJoshStarmer" target="_blank">Video on Principal Component Analysis</a></li>
<li> <a href="https://www.youtube.com/watch?v=esmzYhuFnds&ab_channel=MITOpenCourseWare" target="_blank">Video on Clustering</a></li>
</ol>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b>Reading</b>
<p>
<ol>
<li> Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from <a href="https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf" target="_blank">STK-IN4300, lecture 7</a>. Chapter 9.2 of Hastie et al contains also a good discussion.</li>
<li> Clustering and PCA, see Geron's chapter 8 and <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter8.html" target="_blank">Lecture notes</a>. Bishop's chapter 9.1 is also a good read.</li>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="digression-first">Digression First </h2>
<p>For those of you interested in the fast growing areas of applications of Machine Learning, this article about <a href="https://arxiv.org/abs/2110.13041" target="_blank">Applications and techniques for fast machine learning in science</a> may be interesting.</p>
<p>It has several interesting perspectives and highly interesting
applications that link scientific discoveries with efficient software
and hardware. The emphasis is onintegrating power Machine Learning
methods into the real-time experimental data processing loop to
accelerate scientific discovery.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-short-discussion-of-project-2">A short Discussion of Project 2 </h2>
<p>For neural networks and regression, should I use a design matrix with information about a polynomial fit or not?
Discuss pros and cons. The example here shows some of these issues.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic">Code to test Ridge and NNs using Scikit-Learn only</span>
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.neural_network</span> <span style="color: #008000; font-weight: bold">import</span> MLPRegressor
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">seaborn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sns</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">315</span>)
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(n)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> <span style="color: #666666">1.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>)
Maxpolydegree <span style="color: #666666">=</span> <span style="color: #666666">5</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n,Maxpolydegree<span style="color: #666666">-1</span>))
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,Maxpolydegree): <span style="color: #408080; font-style: italic">#No intercept column</span>
X[:,degree<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> x<span style="color: #666666">**</span>(degree)
<span style="color: #408080; font-style: italic"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">10</span>
lmbd_vals <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">0</span>, nlambdas)
MSERidgePredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
lmb <span style="color: #666666">=</span> lmbd_vals[i]
RegRidge <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Ridge(lmb)
RegRidge<span style="color: #666666">.</span>fit(X_train,y_train)
ypredictRidge <span style="color: #666666">=</span> RegRidge<span style="color: #666666">.</span>predict(X_test)
MSERidgePredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictRidge)
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lmbd_vals), MSERidgePredict, <span style="color: #BA2121">&#39;g--&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE SL Ridge Test&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;log10(lambda)&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;MSE&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
<span style="color: #408080; font-style: italic"># Neural Network part</span>
n_hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">50</span>
epochs <span style="color: #666666">=</span> <span style="color: #666666">100</span>
<span style="color: #408080; font-style: italic"># store models for later use</span>
eta_vals <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">0</span>, <span style="color: #666666">10</span>)
<span style="color: #408080; font-style: italic"># store the models for later use</span>
DNN_scikit <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)), dtype<span style="color: #666666">=</span><span style="color: #008000">object</span>)
test_accuracy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)))
sns<span style="color: #666666">.</span>set()
<span style="color: #008000; font-weight: bold">for</span> i, eta <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(eta_vals):
<span style="color: #008000; font-weight: bold">for</span> j, lmbd <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(lmbd_vals):
dnn <span style="color: #666666">=</span> MLPRegressor(hidden_layer_sizes<span style="color: #666666">=</span>(n_hidden_neurons), activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;logistic&#39;</span>,
alpha<span style="color: #666666">=</span>lmbd, learning_rate_init<span style="color: #666666">=</span>eta, max_iter<span style="color: #666666">=</span>epochs)
dnn<span style="color: #666666">.</span>fit(X_train, y_train)
ypredictMLP <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X_test)
test_accuracy[i][j] <span style="color: #666666">=</span> MSE(ypredictMLP, y_test)
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots(figsize <span style="color: #666666">=</span> (<span style="color: #666666">10</span>, <span style="color: #666666">10</span>))
sns<span style="color: #666666">.</span>heatmap(test_accuracy, annot<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, ax<span style="color: #666666">=</span>ax, cmap<span style="color: #666666">=</span><span style="color: #BA2121">&quot;viridis&quot;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&quot;Training Accuracy&quot;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&quot;$\eta$&quot;</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&quot;$\lambda$&quot;</span>)
plt<span style="color: #666666">.</span>show()
<span style="color: #408080; font-style: italic"># Now we redefine our design matrix to include only the x-values and try out our NN</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n,<span style="color: #666666">1</span>))
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> x
<span style="color: #408080; font-style: italic"># We split the data in test and training data again</span>
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #408080; font-style: italic"># Repeat the NN calculation</span>
DNN_scikit <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)), dtype<span style="color: #666666">=</span><span style="color: #008000">object</span>)
test_accuracy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(eta_vals), <span style="color: #008000">len</span>(lmbd_vals)))
sns<span style="color: #666666">.</span>set()
<span style="color: #008000; font-weight: bold">for</span> i, eta <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(eta_vals):
<span style="color: #008000; font-weight: bold">for</span> j, lmbd <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(lmbd_vals):
dnn <span style="color: #666666">=</span> MLPRegressor(hidden_layer_sizes<span style="color: #666666">=</span>(n_hidden_neurons), activation<span style="color: #666666">=</span><span style="color: #BA2121">&#39;logistic&#39;</span>,
alpha<span style="color: #666666">=</span>lmbd, learning_rate_init<span style="color: #666666">=</span>eta, max_iter<span style="color: #666666">=</span>epochs)
dnn<span style="color: #666666">.</span>fit(X_train, y_train)
ypredictMLP <span style="color: #666666">=</span> dnn<span style="color: #666666">.</span>predict(X_test)
test_accuracy[i][j] <span style="color: #666666">=</span> MSE(ypredictMLP, y_test)
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots(figsize <span style="color: #666666">=</span> (<span style="color: #666666">10</span>, <span style="color: #666666">10</span>))
sns<span style="color: #666666">.</span>heatmap(test_accuracy, annot<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, ax<span style="color: #666666">=</span>ax, cmap<span style="color: #666666">=</span><span style="color: #BA2121">&quot;viridis&quot;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&quot;Training Accuracy&quot;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&quot;$\eta$&quot;</span>)
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">&quot;$\lambda$&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="learning-rate-and-more">Learning Rate and more </h2>
<p>When developing your own gradient descent code, it is useful to test
it first on a standard ordinary least squares problem. Then the
Hessian matrix is determined by the design matrix only, namely
\( \boldsymbol{H}\propto \boldsymbol{X}^T\boldsymbol{X} \).
</p>
<p>The optimal learning rate is determined by the inverse of the largest
eigenvalue of \( \boldsymbol{H} \). This can be used as a guideline for the
learning rate guess.
</p>
<p>Keeping this fixed, can aid in studyng the dependence on say the mean
square value for OLS as function of the number of batches and epochs
in your stochastic gradient descent code. See for example the code
examples for week 40 (right before the neural network material).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="thursday-principal-component-analysis">Thursday, Principal Component Analysis </h2>
<p>For the principal component analysis,
see slides from <a href="https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-reveal.html" target="_blank">week 43</a>, in particular from slide 28 and forward
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-kind-of-bird-s-view-on-pca">A kind of Bird's view on PCA </h2>
<b>Why do we maximize variance during Principal Component Analysis?</b>
<p>Variance is a measure of the <em>variability</em> of the data you
have. Potentially the number of components is infinite, so you want to "squeeze" the most
information in each component of the finite set you build.
</p>
<p>If, to exaggerate, you were to select a single principal component,
you would want it to account for the most variability possible: hence
the search for maximum variance, so that the one component collects
the most "uniqueness" from the data set.
</p>
<p>Maximizing the component vector variances is the same as maximizing
the 'uniqueness' of those vectors. The vectors are as distant
from each other as possible (orthogonal to each other).
</p>
<p>Take for example a situation where you have 2 lines that are
orthogonal in a 3D space. You can capture the environment much more
completely with those orthogonal lines than 2 lines that are parallel
(or nearly parallel). When applied to very high dimensional states
using very few vectors, this becomes a much more important
relationship among the vectors to maintain. In a linear algebra sense
you want independent rows to be produced by PCA, otherwise some of
those rows will be redundant.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="thursday-clustering-and-unsupervised-learning">Thursday: Clustering and Unsupervised Learning </h2>
<p>In general terms cluster analysis, or clustering, is the task of grouping a
data-set into different distinct categories based on some measure of equality of
the data. This measure is often referred to as a <b>metric</b> or <b>similarity
measure</b> in the literature (note: sometimes we deal with a <b>dissimilarity
measure</b> instead). Usually, these metrics are formulated as some kind of
distance function between points in a high-dimensional space.
</p>
<p>The simplest, and also the most
common is the <b>Euclidean distance</b>.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="basic-idea-of-the-k-means-clustering-algorithm">Basic Idea of the \( k \)-means Clustering Algorithm </h2>
<p>The simplest of all clustering algorithms is the <b>k-means algorithm</b>
, sometimes also referred to as <em>Lloyds algorithm</em>. It is the simplest and also
the most common. From its simplicity it obtains both strengths and weaknesses.
These will be discussed in more detail later. The \( k \)-means algorithm is a
<b>centroid based</b> clustering algorithm.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-k-means-algorithm">The \( k \)-means Algorithm </h2>
<p>Assume, we are given \( n \) data points and we wish to split the data into \( K < n \)
different categories, or clusters. We label each cluster by an integer
</p>
$$ k\in\{1, \cdots, K \}.
$$
<p>In the basic k-means algorithm each point is assigned to only
one cluster \( k \), and these assignments are <em>non-injective</em> i.e. many-to-one. We
can think of these mappings as an encoder \( k = C(i) \), which assigns the \( i \)-th
data-point \( \bf x_i \) to the \( k \)-th cluster.
</p>
<p>\( k \)-means algorithm in words:</p>
<ol>
<li> We start with guesses / random initializations of our \( k \) cluster centers/centroids</li>
<li> For each centroid the points that are most similar are identified</li>
<li> Then we move / replace each centroid with a coordinate average of all the points that were assigned to that centroid.</li>
<li> Iterate 2-3 until the centroids no longer move (to some tolerance)</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="basic-math-of-the-k-means-algorithm">Basic Math of the \( k \)-means Algorithm </h2>
<p>We assume we have \( n \) data-points</p>
$$
\begin{equation}\label{eq:kmeanspoints}
\boldsymbol{x_i} = \{x_{i, 1}, \cdots, x_{i, p}\}\in\mathbb{R}^p.
\end{equation}
$$
<p>which we wish to group into \( K < n \) clusters. For our dissimilarity measure we
use the <em>squared Euclidean distance</em>
</p>
$$
\begin{equation}\label{eq:squaredeuclidean}
d(\boldsymbol{x_i}, \boldsymbol{x_i'}) = \sum_{j=1}^p(x_{ij} - x_{i'j})^2
= ||\boldsymbol{x_i} - \boldsymbol{x_{i'}}||^2
\end{equation}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="within-cluster-point-scatter">Within Cluster Point Scatter </h2>
<p>We define the so called <em>within-cluster point scatter</em> which gives us a
measure of how close each data point assigned to the same cluster tends to be to
the all the others.
</p>
$$
\begin{equation}\label{eq:withincluster}
W(C) = \frac{1}{2}\sum_{k=1}^K\sum_{C(i)=k}
\sum_{C(i')=k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}}) =
\sum_{k=1}^KN_k\sum_{C(i)=k}||\boldsymbol{x_i} - \boldsymbol{\overline{x_k}}||^2
\end{equation}
$$
<p>where \( \boldsymbol{\overline{x_k}} \) is the mean vector associated with the \( k \)-th
cluster, and \( N_k = \sum_{i=1}^nI(C(i) = k) \), where the \( I() \) notation is
similar to the Kronecker delta (<em>Commonly used in statistics, it just means that
when \( i = k \) we have the encoder \( C(i) \)</em>). In other words, the within-cluster
scatter measures the compactness of each cluster with respect to the data points
assigned to each cluster. This is the quantity that the \( k \)-means algorithm aims
to minimize. We refer to this quantity \( W(C) \) as the within cluster scatter
because of its relation to the <em>total scatter</em>.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-details">More Details </h2>
<p>We have</p>
$$
\begin{equation}\label{eq:totalscatter}
T = W(C) + B(C) = \frac{1}{2}\sum_{i=1}^n
\sum_{i'=1}^nd(\boldsymbol{x_i}, \boldsymbol{x_{i'}})
= \frac{1}{2}\sum_{k=1}^K\sum_{C(i)=k}
\Big(\sum_{C(i') = k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}})
+ \sum_{C(i')\neq k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}})\Big).
\end{equation}
$$
<p>This is a quantity that is conserved throughout the \( k \)-means algorithm. It can
be thought of as the total amount of information in the data, and it is composed
of the aforementioned within-cluster scatter and the <em>between-cluster scatter</em>
\( B(C) \). In methods such as principle component analysis the total scatter is not
conserved.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="total-cluster-variance">Total Cluster Variance </h2>
<p>Given a cluster mean \( \boldsymbol{m_k} \) we define the <b>total cluster variance</b></p>
$$
\begin{equation}\label{eq:totalclustervariance}
\min_{C, \{\boldsymbol{m_k}\}_1^K}\sum_{k=1}^KN_k\sum||\boldsymbol{x_i} - \boldsymbol{m_k}||^2
\end{equation}
$$
<p>Now we have all the pieces necessary to formally revisit the \( k \)-means algorithm.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-k-means-clustering-algorithm">The \( k \)-means Clustering Algorithm </h2>
<p>The \( k \)-means clustering algorithm goes as follows </p>
<ol>
<li> For a given cluster assignment \( C \), and \( k \) cluster means \( \left\{m_1, \cdots, m_k\right\} \). We minimize the total cluster variance with respect to the cluster means \( \{m_k\} \) yielding the means of the currently assigned clusters.</li>
<li> Given a current set of \( k \) means \( \{m_k\} \) the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is $$C(i) = \underset{1\leq k\leq K}{\mathrm{argmin}} ||\boldsymbol{x_i} - \boldsymbol{m_k}||^2$$</li>
<li> Steps 1 and 2 are repeated until the assignments do not change.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="summarizing">Summarizing </h2>
<ol>
<li> Before we start we specify a number \( k \) which is the number of clusters we want to try to separate our data into.</li>
<li> We initially choose \( k \) random data points in our data as our initial centroids, <em>or means</em> (this is where the name comes from).</li>
<li> Assign each data point to their closest centroid, based on the squared Euclidean distance.</li>
<li> For each of the \( k \) cluster we update the centroid by calculating new mean values for all the data points in the cluster.</li>
<li> Iteratively minimize the within cluster scatter by performing steps (3, 4) until the new assignments stop changing (can be to some tolerance) or until a maximum number of iterations have passed.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="writing-our-own-code-the-data-set">Writing our own Code, the Data Set </h2>
<p>Let us now program the most basic version of the algorithm using nothing but
Python with numpy arrays. This code is kept intentionally simple to gradually
progress our understanding. There is no vectorization of any kind, and even most
helper functions are not utilized.
</p>
<p>We need first a dataset to do our cluster analysis on. In our case
this is a plain <em>vanilla</em> data set using random numbers using a
Gaussian distribution.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">time</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">tensorflow</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">tf</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> image
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.cluster</span> <span style="color: #008000; font-weight: bold">import</span> KMeans
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">2021</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>
<p>Next we define functions, for ease of use later, to generate Gaussians and to
set up our toy data set.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">gaussian_points</span>(dim<span style="color: #666666">=2</span>, n_points<span style="color: #666666">=1000</span>, mean_vector<span style="color: #666666">=</span>np<span style="color: #666666">.</span>array([<span style="color: #666666">0</span>, <span style="color: #666666">0</span>]),
sample_variance<span style="color: #666666">=1</span>):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Very simple custom function to generate gaussian distributed point clusters</span>
<span style="color: #BA2121; font-style: italic"> with variable dimension, number of points, means in each direction</span>
<span style="color: #BA2121; font-style: italic"> (must match dim) and sample variance.</span>
<span style="color: #BA2121; font-style: italic"> Inputs:</span>
<span style="color: #BA2121; font-style: italic"> dim (int)</span>
<span style="color: #BA2121; font-style: italic"> n_points (int)</span>
<span style="color: #BA2121; font-style: italic"> mean_vector (np.array) (where index 0 is x, index 1 is y etc.)</span>
<span style="color: #BA2121; font-style: italic"> sample_variance (float)</span>
<span style="color: #BA2121; font-style: italic"> Returns:</span>
<span style="color: #BA2121; font-style: italic"> data (np.array): with dimensions (dim x n_points)</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
mean_matrix <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(dim) <span style="color: #666666">+</span> mean_vector
covariance_matrix <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(dim) <span style="color: #666666">*</span> sample_variance
data <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>multivariate_normal(mean_matrix, covariance_matrix,
n_points)
<span style="color: #008000; font-weight: bold">return</span> data
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">generate_simple_clustering_dataset</span>(dim<span style="color: #666666">=2</span>, n_points<span style="color: #666666">=1000</span>, plotting<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
return_data<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>):
<span style="color: #BA2121; font-style: italic">&quot;&quot;&quot;</span>
<span style="color: #BA2121; font-style: italic"> Toy model to illustrate k-means clustering</span>
<span style="color: #BA2121; font-style: italic"> &quot;&quot;&quot;</span>
data1 <span style="color: #666666">=</span> gaussian_points(mean_vector<span style="color: #666666">=</span>np<span style="color: #666666">.</span>array([<span style="color: #666666">5</span>, <span style="color: #666666">5</span>]))
data2 <span style="color: #666666">=</span> gaussian_points()
data3 <span style="color: #666666">=</span> gaussian_points(mean_vector<span style="color: #666666">=</span>np<span style="color: #666666">.</span>array([<span style="color: #666666">1</span>, <span style="color: #666666">4.5</span>]))
data4 <span style="color: #666666">=</span> gaussian_points(mean_vector<span style="color: #666666">=</span>np<span style="color: #666666">.</span>array([<span style="color: #666666">5</span>, <span style="color: #666666">1</span>]))
data <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((data1, data2, data3, data4), axis<span style="color: #666666">=0</span>)
<span style="color: #008000; font-weight: bold">if</span> plotting:
fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots()
ax<span style="color: #666666">.</span>scatter(data[:, <span style="color: #666666">0</span>], data[:, <span style="color: #666666">1</span>], alpha<span style="color: #666666">=0.2</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Toy Model Dataset&#39;</span>)
plt<span style="color: #666666">.</span>show()
<span style="color: #008000; font-weight: bold">if</span> return_data:
<span style="color: #008000; font-weight: bold">return</span> data
data <span style="color: #666666">=</span> generate_simple_clustering_dataset()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="implementing-the-k-means-algorithm">Implementing the \( k \)-means Algorithm </h2>
<p>With the above dataset we start
implementing the \( k \)-means algorithm.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">n_samples, dimensions <span style="color: #666666">=</span> data<span style="color: #666666">.</span>shape
n_clusters <span style="color: #666666">=</span> <span style="color: #666666">4</span>
<span style="color: #408080; font-style: italic"># we randomly initialize our centroids</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">2021</span>)
centroids <span style="color: #666666">=</span> data[np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice(n_samples, n_clusters, replace<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>), :]
distances <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n_samples, n_clusters))
<span style="color: #408080; font-style: italic"># first we need to calculate the distance to each centroid from our data</span>
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
dist <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> d <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(dimensions):
dist <span style="color: #666666">+=</span> np<span style="color: #666666">.</span>abs(data[n, d] <span style="color: #666666">-</span> centroids[k, d])<span style="color: #666666">**2</span>
distances[n, k] <span style="color: #666666">=</span> dist
<span style="color: #408080; font-style: italic"># we initialize an array to keep track of to which cluster each point belongs</span>
<span style="color: #408080; font-style: italic"># the way we set it up here the index tracks which point and the value which</span>
<span style="color: #408080; font-style: italic"># cluster the point belongs to</span>
cluster_labels <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n_samples, dtype<span style="color: #666666">=</span><span style="color: #BA2121">&#39;int&#39;</span>)
<span style="color: #408080; font-style: italic"># next we loop through our samples and for every point assign it to the cluster</span>
<span style="color: #408080; font-style: italic"># to which it has the smallest distance to</span>
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
<span style="color: #408080; font-style: italic"># tracking variables (all of this is basically just an argmin)</span>
smallest <span style="color: #666666">=</span> <span style="color: #666666">1e10</span>
smallest_row_index <span style="color: #666666">=</span> <span style="color: #666666">1e10</span>
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #008000; font-weight: bold">if</span> distances[n, k] <span style="color: #666666">&lt;</span> smallest:
smallest <span style="color: #666666">=</span> distances[n, k]
smallest_row_index <span style="color: #666666">=</span> k
cluster_labels[n] <span style="color: #666666">=</span> smallest_row_index
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="plotting">Plotting </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot()
unique_cluster_labels <span style="color: #666666">=</span> np<span style="color: #666666">.</span>unique(cluster_labels)
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> unique_cluster_labels:
ax<span style="color: #666666">.</span>scatter(data[cluster_labels <span style="color: #666666">==</span> i, <span style="color: #666666">0</span>],
data[cluster_labels <span style="color: #666666">==</span> i, <span style="color: #666666">1</span>],
label <span style="color: #666666">=</span> i,
alpha <span style="color: #666666">=</span> <span style="color: #666666">0.2</span>)
ax<span style="color: #666666">.</span>scatter(centroids[:, <span style="color: #666666">0</span>], centroids[:, <span style="color: #666666">1</span>], c<span style="color: #666666">=</span><span style="color: #BA2121">&#39;black&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&quot;First Grouping of Points to Centroids&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>So what do we have so far? We have 'picked' \( k \) centroids at random from our
data points. There are other ways of more intelligently choosing their
initializations, however for our purposes randomly is fine. Then we have
initialized an array 'distances' which holds the information of the distance,
<em>or dissimilarity</em>, of every point to of our centroids. Finally, we have
initialized an array 'cluster_labels' which according to our distances array
holds the information of to which centroid every point is assigned. This was the
first pass of our algorithm. Essentially, all we need to do now is repeat the
distance and assignment steps above until we have reached a desired convergence
or a maximum amount of iterations.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="continuing">Continuing </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">max_iterations <span style="color: #666666">=</span> <span style="color: #666666">100</span>
tolerance <span style="color: #666666">=</span> <span style="color: #666666">1e-8</span>
<span style="color: #008000; font-weight: bold">for</span> iteration <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(max_iterations):
prev_centroids <span style="color: #666666">=</span> centroids<span style="color: #666666">.</span>copy()
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #408080; font-style: italic"># this array will be used to update our centroid positions</span>
vector_mean <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(dimensions)
mean_divisor <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
<span style="color: #008000; font-weight: bold">if</span> cluster_labels[n] <span style="color: #666666">==</span> k:
vector_mean <span style="color: #666666">+=</span> data[n, :]
mean_divisor <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
<span style="color: #408080; font-style: italic"># update according to the k means</span>
centroids[k, :] <span style="color: #666666">=</span> vector_mean <span style="color: #666666">/</span> mean_divisor
<span style="color: #408080; font-style: italic"># we find the dissimilarity</span>
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
dist <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> d <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(dimensions):
dist <span style="color: #666666">+=</span> np<span style="color: #666666">.</span>abs(data[n, d] <span style="color: #666666">-</span> centroids[k, d])<span style="color: #666666">**2</span>
distances[n, k] <span style="color: #666666">=</span> dist
<span style="color: #408080; font-style: italic"># assign each point</span>
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
smallest <span style="color: #666666">=</span> <span style="color: #666666">1e10</span>
smallest_row_index <span style="color: #666666">=</span> <span style="color: #666666">1e10</span>
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #008000; font-weight: bold">if</span> distances[n, k] <span style="color: #666666">&lt;</span> smallest:
smallest <span style="color: #666666">=</span> distances[n, k]
smallest_row_index <span style="color: #666666">=</span> k
cluster_labels[n] <span style="color: #666666">=</span> smallest_row_index
<span style="color: #408080; font-style: italic"># convergence criteria</span>
centroid_difference <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(np<span style="color: #666666">.</span>abs(centroids <span style="color: #666666">-</span> prev_centroids))
<span style="color: #008000; font-weight: bold">if</span> centroid_difference <span style="color: #666666">&lt;</span> tolerance:
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&#39;Converged at iteration </span><span style="color: #BB6688; font-weight: bold">{</span>iteration<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&#39;</span>)
<span style="color: #008000; font-weight: bold">break</span>
<span style="color: #008000; font-weight: bold">elif</span> iteration <span style="color: #666666">==</span> max_iterations:
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&#39;Did not converge in </span><span style="color: #BB6688; font-weight: bold">{</span>max_iterations<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> iterations&#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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="wrapping-it-up">Wrapping it up </h2>
<p>We now have a simple , un-optimized \( k \)-means
clustering implementation. Lets plot the final result
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot()
unique_cluster_labels <span style="color: #666666">=</span> np<span style="color: #666666">.</span>unique(cluster_labels)
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> unique_cluster_labels:
ax<span style="color: #666666">.</span>scatter(data[cluster_labels <span style="color: #666666">==</span> i, <span style="color: #666666">0</span>],
data[cluster_labels <span style="color: #666666">==</span> i, <span style="color: #666666">1</span>],
label <span style="color: #666666">=</span> i,
alpha <span style="color: #666666">=</span> <span style="color: #666666">0.2</span>)
ax<span style="color: #666666">.</span>scatter(centroids[:, <span style="color: #666666">0</span>], centroids[:, <span style="color: #666666">1</span>], c<span style="color: #666666">=</span><span style="color: #BA2121">&#39;black&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&quot;Final Result of K-means Clustering&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">naive_kmeans</span>(data, n_clusters<span style="color: #666666">=4</span>, max_iterations<span style="color: #666666">=100</span>, tolerance<span style="color: #666666">=1e-8</span>):
start_time <span style="color: #666666">=</span> time<span style="color: #666666">.</span>time()
n_samples, dimensions <span style="color: #666666">=</span> data<span style="color: #666666">.</span>shape
n_clusters <span style="color: #666666">=</span> <span style="color: #666666">4</span>
<span style="color: #408080; font-style: italic">#np.random.seed(2021)</span>
centroids <span style="color: #666666">=</span> data[np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice(n_samples, n_clusters, replace<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>), :]
distances <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n_samples, n_clusters))
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
dist <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> d <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(dimensions):
dist <span style="color: #666666">+=</span> np<span style="color: #666666">.</span>abs(data[n, d] <span style="color: #666666">-</span> centroids[k, d])<span style="color: #666666">**2</span>
distances[n, k] <span style="color: #666666">=</span> dist
cluster_labels <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n_samples, dtype<span style="color: #666666">=</span><span style="color: #BA2121">&#39;int&#39;</span>)
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
smallest <span style="color: #666666">=</span> <span style="color: #666666">1e10</span>
smallest_row_index <span style="color: #666666">=</span> <span style="color: #666666">1e10</span>
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #008000; font-weight: bold">if</span> distances[n, k] <span style="color: #666666">&lt;</span> smallest:
smallest <span style="color: #666666">=</span> distances[n, k]
smallest_row_index <span style="color: #666666">=</span> k
cluster_labels[n] <span style="color: #666666">=</span> smallest_row_index
<span style="color: #008000; font-weight: bold">for</span> iteration <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(max_iterations):
prev_centroids <span style="color: #666666">=</span> centroids<span style="color: #666666">.</span>copy()
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
vector_mean <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(dimensions)
mean_divisor <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
<span style="color: #008000; font-weight: bold">if</span> cluster_labels[n] <span style="color: #666666">==</span> k:
vector_mean <span style="color: #666666">+=</span> data[n, :]
mean_divisor <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
centroids[k, :] <span style="color: #666666">=</span> vector_mean <span style="color: #666666">/</span> mean_divisor
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
dist <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000; font-weight: bold">for</span> d <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(dimensions):
dist <span style="color: #666666">+=</span> np<span style="color: #666666">.</span>abs(data[n, d] <span style="color: #666666">-</span> centroids[k, d])<span style="color: #666666">**2</span>
distances[n, k] <span style="color: #666666">=</span> dist
<span style="color: #008000; font-weight: bold">for</span> n <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_samples):
smallest <span style="color: #666666">=</span> <span style="color: #666666">1e10</span>
smallest_row_index <span style="color: #666666">=</span> <span style="color: #666666">1e10</span>
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_clusters):
<span style="color: #008000; font-weight: bold">if</span> distances[n, k] <span style="color: #666666">&lt;</span> smallest:
smallest <span style="color: #666666">=</span> distances[n, k]
smallest_row_index <span style="color: #666666">=</span> k
cluster_labels[n] <span style="color: #666666">=</span> smallest_row_index
centroid_difference <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(np<span style="color: #666666">.</span>abs(centroids <span style="color: #666666">-</span> prev_centroids))
<span style="color: #008000; font-weight: bold">if</span> centroid_difference <span style="color: #666666">&lt;</span> tolerance:
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&#39;Converged at iteration </span><span style="color: #BB6688; font-weight: bold">{</span>iteration<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">&#39;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&#39;Runtime: </span><span style="color: #BB6688; font-weight: bold">{</span>time<span style="color: #666666">.</span>time() <span style="color: #666666">-</span> start_time<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> seconds&#39;</span>)
<span style="color: #008000; font-weight: bold">return</span> cluster_labels, centroids
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&#39;Did not converge in </span><span style="color: #BB6688; font-weight: bold">{</span>max_iterations<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> iterations&#39;</span>)
<span style="color: #008000">print</span>(<span style="color: #BA2121">f&#39;Runtime: </span><span style="color: #BB6688; font-weight: bold">{</span>time<span style="color: #666666">.</span>time() <span style="color: #666666">-</span> start_time<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121"> seconds&#39;</span>)
<span style="color: #008000; font-weight: bold">return</span> cluster_labels, centroids
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="decision-trees-overarching-aims">Decision trees, overarching aims </h2>
<p>We start here with the most basic algorithm, the so-called decision
tree. With this basic algorithm we can in turn build more complex
networks, spanning from homogeneous and heterogenous forests (bagging,
random forests and more) to one of the most popular supervised
algorithms nowadays, the extreme gradient boosting, or just
XGBoost. But let us start with the simplest possible ingredient.
</p>
<p>Decision trees are supervised learning algorithms used for both,
classification and regression tasks.
</p>
<p>The main idea of decision trees
is to find those descriptive features which contain the most
<b>information</b> regarding the target feature and then split the dataset
along the values of these features such that the target feature values
for the resulting underlying datasets are as pure as possible.
</p>
<p>The descriptive features which reproduce best the target/output features are normally said
to be the most informative ones. The process of finding the <b>most
informative</b> feature is done until we accomplish a stopping criteria
where we then finally end up in so called <b>leaf nodes</b>.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="basics-of-a-tree">Basics of a tree </h2>
<p>A decision tree is typically divided into a <b>root node</b>, the <b>interior nodes</b>,
and the final <b>leaf nodes</b> or just <b>leaves</b>. These entities are then connected by so-called <b>branches</b>.
</p>
<p>The leaf nodes
contain the predictions we will make for new query instances presented
to our trained model. This is possible since the model has
learned the underlying structure of the training data and hence can,
given some assumptions, make predictions about the target feature value
(class) of unseen query instances.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-sketch-of-a-tree-regression-problem">A Sketch of a Tree, Regression problem </h2>
<!-- FIGURE: [DataFiles/Regsimpletree.png, width=600 frac=0.8] -->
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-sketch-of-a-tree-classification-problem">A Sketch of a Tree, Classification problem </h2>
<!-- FIGURE: [DataFiles/Classimpletree.png, width=600 frac=0.8] -->
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-typical-decision-tree-with-its-pertinent-jargon-classification-problem">A typical Decision Tree with its pertinent Jargon, Classification Problem </h2>
<br/><br/>
<center>
<p><img src="DataFiles/cancer.png" width="600" align="bottom"></p>
</center>
<br/><br/>
<p>This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using <b>Scikit-Learn</b>'s decision tree classifier. Here we have used the so-called <b>gini</b> index (see below) to split the various branches.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="general-features">General Features </h2>
<p>The overarching approach to decision trees is a top-down approach.</p>
<ul>
<li> A leaf provides the classification of a given instance.</li>
<li> A node specifies a test of some attribute of the instance.</li>
<li> A branch corresponds to a possible values of an attribute.</li>
<li> An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.</li>
</ul>
<p>This process is then repeated for the subtree rooted at the new
node.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="how-do-we-set-it-up">How do we set it up? </h2>
<p>In simplified terms, the process of training a decision tree and
predicting the target features of query instances is as follows:
</p>
<ol>
<li> Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature</li>
<li> Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process</li>
<li> Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the <em>predictions</em> we want to make for new query instances</li>
<li> Show query instances to the tree and run down the tree until we arrive at leaf nodes</li>
</ol>
<p>Then we are essentially done!</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="decision-trees-and-regression">Decision trees and Regression </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> PolynomialFeatures
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
steps<span style="color: #666666">=250</span>
distance<span style="color: #666666">=0</span>
x<span style="color: #666666">=0</span>
distance_list<span style="color: #666666">=</span>[]
steps_list<span style="color: #666666">=</span>[]
<span style="color: #008000; font-weight: bold">while</span> x<span style="color: #666666">&lt;</span>steps:
distance<span style="color: #666666">+=</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randint(<span style="color: #666666">-1</span>,<span style="color: #666666">2</span>)
distance_list<span style="color: #666666">.</span>append(distance)
x<span style="color: #666666">+=1</span>
steps_list<span style="color: #666666">.</span>append(x)
plt<span style="color: #666666">.</span>plot(steps_list,distance_list, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;green&#39;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Random Walk Data&quot;</span>)
steps_list<span style="color: #666666">=</span>np<span style="color: #666666">.</span>asarray(steps_list)
distance_list<span style="color: #666666">=</span>np<span style="color: #666666">.</span>asarray(distance_list)
X<span style="color: #666666">=</span>steps_list[:,np<span style="color: #666666">.</span>newaxis]
<span style="color: #408080; font-style: italic">#Polynomial fits</span>
<span style="color: #408080; font-style: italic">#Degree 2</span>
poly_features<span style="color: #666666">=</span>PolynomialFeatures(degree<span style="color: #666666">=2</span>, include_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
X_poly<span style="color: #666666">=</span>poly_features<span style="color: #666666">.</span>fit_transform(X)
lin_reg<span style="color: #666666">=</span>LinearRegression()
poly_fit<span style="color: #666666">=</span>lin_reg<span style="color: #666666">.</span>fit(X_poly,distance_list)
b<span style="color: #666666">=</span>lin_reg<span style="color: #666666">.</span>coef_
c<span style="color: #666666">=</span>lin_reg<span style="color: #666666">.</span>intercept_
<span style="color: #008000">print</span> (<span style="color: #BA2121">&quot;2nd degree coefficients:&quot;</span>)
<span style="color: #008000">print</span> (<span style="color: #BA2121">&quot;zero power: &quot;</span>,c)
<span style="color: #008000">print</span> (<span style="color: #BA2121">&quot;first power: &quot;</span>, b[<span style="color: #666666">0</span>])
<span style="color: #008000">print</span> (<span style="color: #BA2121">&quot;second power: &quot;</span>,b[<span style="color: #666666">1</span>])
z <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0</span>, steps, <span style="color: #666666">.01</span>)
z_mod<span style="color: #666666">=</span>b[<span style="color: #666666">1</span>]<span style="color: #666666">*</span>z<span style="color: #666666">**2+</span>b[<span style="color: #666666">0</span>]<span style="color: #666666">*</span>z<span style="color: #666666">+</span>c
fit_mod<span style="color: #666666">=</span>b[<span style="color: #666666">1</span>]<span style="color: #666666">*</span>X<span style="color: #666666">**2+</span>b[<span style="color: #666666">0</span>]<span style="color: #666666">*</span>X<span style="color: #666666">+</span>c
plt<span style="color: #666666">.</span>plot(z, z_mod, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;r&#39;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;2nd Degree Fit&quot;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Polynomial Regression&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;Steps&quot;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&quot;Distance&quot;</span>)
<span style="color: #408080; font-style: italic">#Degree 10</span>
poly_features10<span style="color: #666666">=</span>PolynomialFeatures(degree<span style="color: #666666">=10</span>, include_bias<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
X_poly10<span style="color: #666666">=</span>poly_features10<span style="color: #666666">.</span>fit_transform(X)
poly_fit10<span style="color: #666666">=</span>lin_reg<span style="color: #666666">.</span>fit(X_poly10,distance_list)
y_plot<span style="color: #666666">=</span>poly_fit10<span style="color: #666666">.</span>predict(X_poly10)
plt<span style="color: #666666">.</span>plot(X, y_plot, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;black&#39;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;10th Degree Fit&quot;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
<span style="color: #408080; font-style: italic">#Decision Tree Regression</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
regr_1<span style="color: #666666">=</span>DecisionTreeRegressor(max_depth<span style="color: #666666">=2</span>)
regr_2<span style="color: #666666">=</span>DecisionTreeRegressor(max_depth<span style="color: #666666">=5</span>)
regr_3<span style="color: #666666">=</span>DecisionTreeRegressor(max_depth<span style="color: #666666">=7</span>)
regr_1<span style="color: #666666">.</span>fit(X, distance_list)
regr_2<span style="color: #666666">.</span>fit(X, distance_list)
regr_3<span style="color: #666666">.</span>fit(X, distance_list)
X_test <span style="color: #666666">=</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">0.0</span>, steps, <span style="color: #666666">0.01</span>)[:, np<span style="color: #666666">.</span>newaxis]
y_1 <span style="color: #666666">=</span> regr_1<span style="color: #666666">.</span>predict(X_test)
y_2 <span style="color: #666666">=</span> regr_2<span style="color: #666666">.</span>predict(X_test)
y_3<span style="color: #666666">=</span>regr_3<span style="color: #666666">.</span>predict(X_test)
<span style="color: #408080; font-style: italic"># Plot the results</span>
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>scatter(X, distance_list, s<span style="color: #666666">=2.5</span>, c<span style="color: #666666">=</span><span style="color: #BA2121">&quot;black&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;data&quot;</span>)
plt<span style="color: #666666">.</span>plot(X_test, y_1, color<span style="color: #666666">=</span><span style="color: #BA2121">&quot;red&quot;</span>,
label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;max_depth=2&quot;</span>, linewidth<span style="color: #666666">=2</span>)
plt<span style="color: #666666">.</span>plot(X_test, y_2, color<span style="color: #666666">=</span><span style="color: #BA2121">&quot;green&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;max_depth=5&quot;</span>, linewidth<span style="color: #666666">=2</span>)
plt<span style="color: #666666">.</span>plot(X_test, y_3, color<span style="color: #666666">=</span><span style="color: #BA2121">&quot;m&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;max_depth=7&quot;</span>, linewidth<span style="color: #666666">=2</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;Data&quot;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&quot;Darget&quot;</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Decision Tree Regression&quot;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="building-a-tree-regression">Building a tree, regression </h2>
<p>There are mainly two steps</p>
<ol>
<li> We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).</li>
<li> For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).</li>
</ol>
<p>How do we construct the regions \( R_1,\dots,R_J \)? In theory, the
regions could have any shape. However, we choose to divide the
predictor space into high-dimensional rectangles, or boxes, for
simplicity and for ease of interpretation of the resulting predictive
model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the
MSE, given by
</p>
$$
\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2,
$$
<p>where \( \overline{y}_{R_j} \) is the mean response for the training observations
within box \( j \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-top-down-approach-recursive-binary-splitting">A top-down approach, recursive binary splitting </h2>
<p>Unfortunately, it is computationally infeasible to consider every
possible partition of the feature space into \( J \) boxes. The common
strategy is to take a top-down approach
</p>
<p>The approach is top-down because it begins at the top of the tree (all
observations belong to a single region) and then successively splits
the predictor space; each split is indicated via two new branches
further down on the tree. It is greedy because at each step of the
tree-building process, the best split is made at that particular step,
rather than looking ahead and picking a split that will lead to a
better tree in some future step.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="making-a-tree">Making a tree </h2>
<p>In order to implement the recursive binary splitting we start by selecting
the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \)
</p>
$$
\left\{X\vert x_j < s\right\},
$$
<p>and</p>
$$
\left\{X\vert x_j \geq s\right\},
$$
<p>so that we obtain the lowest MSE, that is</p>
$$
\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2,
$$
<p>which we want to minimize by considering all predictors
\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for
each predictor. These values could be determined by randomly assigned
numbers or by starting at the midpoint and then proceed till we find
an optimal value.
</p>
<p>For any \( j \) and \( s \), we define the pair of half-planes where
\( \overline{y}_{R_1} \) is the mean response for the training
observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean
response for the training observations in \( R_2(j,s) \).
</p>
<p>Finding the values of \( j \) and \( s \) that minimize the above equation can be
done quite quickly, especially when the number of features \( p \) is not
too large.
</p>
<p>Next, we repeat the process, looking
for the best predictor and best cutpoint in order to split the data
further so as to minimize the MSE within each of the resulting
regions. However, this time, instead of splitting the entire predictor
space, we split one of the two previously identified regions. We now
have three regions. Again, we look to split one of these three regions
further, so as to minimize the MSE. The process continues until a
stopping criterion is reached; for instance, we may continue until no
region contains more than five observations.
</p>
<!-- !split -->
<h2 id="pruning-the-tree">Pruning the tree </h2>
<p>The above procedure is rather straightforward, but leads often to
overfitting and unnecessarily large and complicated trees. The basic
idea is to grow a large tree \( T_0 \) and then prune it back in order to
obtain a subtree. A smaller tree with fewer splits (fewer regions) can
lead to smaller variance and better interpretation at the cost of a
little more bias.
</p>
<p>The so-called Cost complexity pruning algorithm gives us a
way to do just this. Rather than considering every possible subtree,
we consider a sequence of trees indexed by a nonnegative tuning
parameter \( \alpha \).
</p>
<p>Read more at the following <a href="https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py" target="_blank">Scikit-Learn link on pruning</a>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cost-complexity-pruning">Cost complexity pruning </h2>
<p>For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that</p>
$$
\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T},
$$
<p>is as small as possible. Here \( \overline{T} \) is
the number of terminal nodes of the tree \( T \) , \( R_m \) is the
rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node.
</p>
<p>The tuning parameter \( \alpha \) controls a trade-off between the subtree&#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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="schematic-regression-procedure">Schematic Regression Procedure </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Building a Regression Tree</b>
<p>
<ol>
<li> Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.</li>
<li> Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).</li>
<li> Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:</li>
<ul>
<li> repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.</li>
<li> Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).</li>
<li> Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.</li>
</ul>
<li> Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).</li>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-classification-tree">A Classification Tree </h2>
<p>A classification tree is very similar to a regression tree, except
that it is used to predict a qualitative response rather than a
quantitative one. Recall that for a regression tree, the predicted
response for an observation is given by the mean response of the
training observations that belong to the same terminal node. In
contrast, for a classification tree, we predict that each observation
belongs to the most commonly occurring class of training observations
in the region to which it belongs. In interpreting the results of a
classification tree, we are often interested not only in the class
prediction corresponding to a particular terminal node region, but
also in the class proportions among the training observations that
fall into that region.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="growing-a-classification-tree">Growing a classification tree </h2>
<p>The task of growing a
classification tree is quite similar to the task of growing a
regression tree. Just as in the regression setting, we use recursive
binary splitting to grow a classification tree. However, in the
classification setting, the MSE cannot be used as a criterion for making
the binary splits. A natural alternative to MSE is the <b>classification
error rate</b>. Since we plan to assign an observation in a given region
to the most commonly occurring error rate class of training
observations in that region, the classification error rate is simply
the fraction of the training observations in that region that do not
belong to the most common class.
</p>
<p>When building a classification tree, either the Gini index or the
entropy are typically used to evaluate the quality of a particular
split, since these two approaches are more sensitive to node purity
than is the classification error rate.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="classification-tree-how-to-split-nodes">Classification tree, how to split nodes </h2>
<p>If our targets are the outcome of a classification process that takes
for example \( k=1,2,\dots,K \) values, the only thing we need to think of
is to set up the splitting criteria for each node.
</p>
<p>We define a PDF \( p_{mk} \) that represents the number of observations of
a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent
this likelihood function in terms of the proportion \( I(y_i=k) \) of
observations of this class in the region \( R_m \) as
</p>
$$
p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k).
$$
<p>We let \( p_{mk} \) represent the majority class of observations in region
\( m \). The three most common ways of splitting a node are given by
</p>
<ul>
<li> Misclassification error</li>
</ul>
$$
p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}.
$$
<ul>
<li> Gini index \( g \)</li>
</ul>
$$
g = \sum_{k=1}^K p_{mk}(1-p_{mk}).
$$
<ul>
<li> Information entropy or just entropy \( s \)</li>
</ul>
$$
s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="visualizing-the-tree-classification">Visualizing the Tree, Classification </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> confusion_matrix
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> Image
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
cancer <span style="color: #666666">=</span> load_breast_cancer()
X <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(cancer<span style="color: #666666">.</span>data, columns<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>feature_names)
<span style="color: #008000">print</span>(X)
y <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>Categorical<span style="color: #666666">.</span>from_codes(cancer<span style="color: #666666">.</span>target, cancer<span style="color: #666666">.</span>target_names)
y <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>get_dummies(y)
<span style="color: #008000">print</span>(y)
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, random_state<span style="color: #666666">=1</span>)
tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=5</span>)
tree_clf<span style="color: #666666">.</span>fit(X_train, y_train)
export_graphviz(
tree_clf,
out_file<span style="color: #666666">=</span><span style="color: #BA2121">&quot;DataFiles/cancer.dot&quot;</span>,
feature_names<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>feature_names,
class_names<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>target_names,
rounded<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
filled<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>
)
cmd <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png&#39;</span>
os<span style="color: #666666">.</span>system(cmd)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="visualizing-the-tree-the-moons">Visualizing the Tree, The Moons </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">42</span>)
X, y <span style="color: #666666">=</span> make_moons(n_samples<span style="color: #666666">=100</span>, noise<span style="color: #666666">=0.25</span>, random_state<span style="color: #666666">=53</span>)
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X,y,random_state<span style="color: #666666">=0</span>)
tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=5</span>)
tree_clf<span style="color: #666666">.</span>fit(X_train, y_train)
export_graphviz(
tree_clf,
out_file<span style="color: #666666">=</span><span style="color: #BA2121">&quot;DataFiles/moons.dot&quot;</span>,
rounded<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
filled<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>
)
cmd <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png&#39;</span>
os<span style="color: #666666">.</span>system(cmd)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="other-ways-of-visualizing-the-trees">Other ways of visualizing the trees </h2>
<p><b>Scikit-Learn</b> has also another way to visualize the trees which is very useful, here with the Iris data.</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_iris
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> tree
X, y <span style="color: #666666">=</span> load_iris(return_X_y<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
tree_clf <span style="color: #666666">=</span> tree<span style="color: #666666">.</span>DecisionTreeClassifier()
tree_clf <span style="color: #666666">=</span> tree_clf<span style="color: #666666">.</span>fit(X, y)
<span style="color: #408080; font-style: italic"># and then plot the tree</span>
tree<span style="color: #666666">.</span>plot_tree(tree_clf)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="printing-out-as-text">Printing out as text </h2>
<p>Alternatively, the tree can also be exported in textual format with the function exporttext.
This method doesn&#8217;t require the installation of external libraries and is more compact:
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_iris
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_text
iris <span style="color: #666666">=</span> load_iris()
decision_tree <span style="color: #666666">=</span> DecisionTreeClassifier(random_state<span style="color: #666666">=0</span>, max_depth<span style="color: #666666">=2</span>)
decision_tree <span style="color: #666666">=</span> decision_tree<span style="color: #666666">.</span>fit(iris<span style="color: #666666">.</span>data, iris<span style="color: #666666">.</span>target)
r <span style="color: #666666">=</span> export_text(decision_tree, feature_names<span style="color: #666666">=</span>iris[<span style="color: #BA2121">&#39;feature_names&#39;</span>])
<span style="color: #008000">print</span>(r)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="algorithms-for-setting-up-decision-trees">Algorithms for Setting up Decision Trees </h2>
<p>Two algorithms stand out in the set up of decision trees:</p>
<ol>
<li> The CART (Classification And Regression Tree) algorithm for both classification and regression</li>
<li> The ID3 algorithm based on the computation of the information gain for classification</li>
</ol>
<p>We discuss both algorithms with applications here. The popular library
<b>Scikit-Learn</b> uses the CART algorithm. For classification problems
you can use either the <b>gini</b> index or the <b>entropy</b> to split a tree
in two branches.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-cart-algorithm-for-classification">The CART algorithm for Classification </h2>
<p>For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \).
This could be for example a threshold set by a number below a certain circumference of a malign tumor.
</p>
<p>How do we find these two quantities?
We search for the pair \( (k,t_k) \) that produces the purest subset using for example the <b>gini</b> factor \( G \).
The cost function it tries to minimize is then
</p>
$$
C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}},
$$
<p>where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \)
is the number of instances in the left/right subset
</p>
<p>Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets
and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the
\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other
hyperparameters control additional stopping conditions such as the \( min\_samples\_split \),
\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-cart-algorithm-for-regression">The CART algorithm for Regression </h2>
<p>The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the
training set in a way that minimizes say the <b>gini</b> or <b>entropy</b> impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now
</p>
$$
C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}.
$$
<p>Here the MSE for a specific node is defined as</p>
$$
\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2,
$$
<p>with</p>
$$
\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i,
$$
<p>the mean value of all observations in a specific node.</p>
<p>Without any regularization, the regression task for decision trees,
just like for classification tasks, is prone to overfitting.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="computing-the-gini-index">Computing the Gini index </h2>
<p>The example we will look at is a classical one in many Machine
Learning applications. Based on various meteorological features, we
have several so-called attributes which decide whether we at the end
will do some outdoor activity like skiing, going for a bike ride etc
etc. The table here contains the feautures <b>outlook</b>, <b>temperature</b>,
<b>humidity</b> and <b>wind</b>. The target or output is whether we ride
(True=1) or whether we do something else that day (False=0). The
attributes for each feature are then sunny, overcast and rain for the
outlook, hot, cold and mild for temperature, high and normal for
humidity and weak and strong for wind.
</p>
<p>The table here summarizes the various attributes and</p>
<table class="dotable" border="1">
<thead>
<tr><th align="center">Day</th> <th align="center">Outlook </th> <th align="center">Temperature</th> <th align="center">Humidity</th> <th align="center"> Wind </th> <th align="center">Ride</th> </tr>
</thead>
<tbody>
<tr><td align="center"> 1 </td> <td align="center"> Sunny </td> <td align="center"> Hot </td> <td align="center"> High </td> <td align="center"> Weak </td> <td align="center"> 0 </td> </tr>
<tr><td align="center"> 2 </td> <td align="center"> Sunny </td> <td align="center"> Hot </td> <td align="center"> High </td> <td align="center"> Strong </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 3 </td> <td align="center"> Overcast </td> <td align="center"> Hot </td> <td align="center"> High </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 4 </td> <td align="center"> Rain </td> <td align="center"> Mild </td> <td align="center"> High </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 5 </td> <td align="center"> Rain </td> <td align="center"> Cool </td> <td align="center"> Normal </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 6 </td> <td align="center"> Rain </td> <td align="center"> Cool </td> <td align="center"> Normal </td> <td align="center"> Strong </td> <td align="center"> 0 </td> </tr>
<tr><td align="center"> 7 </td> <td align="center"> Overcast </td> <td align="center"> Cool </td> <td align="center"> Normal </td> <td align="center"> Strong </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 8 </td> <td align="center"> Sunny </td> <td align="center"> Mild </td> <td align="center"> High </td> <td align="center"> Weak </td> <td align="center"> 0 </td> </tr>
<tr><td align="center"> 9 </td> <td align="center"> Sunny </td> <td align="center"> Cool </td> <td align="center"> Normal </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 10 </td> <td align="center"> Rain </td> <td align="center"> Mild </td> <td align="center"> Normal </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 11 </td> <td align="center"> Sunny </td> <td align="center"> Mild </td> <td align="center"> Normal </td> <td align="center"> Strong </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 12 </td> <td align="center"> Overcast </td> <td align="center"> Mild </td> <td align="center"> High </td> <td align="center"> Strong </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 13 </td> <td align="center"> Overcast </td> <td align="center"> Hot </td> <td align="center"> Normal </td> <td align="center"> Weak </td> <td align="center"> 1 </td> </tr>
<tr><td align="center"> 14 </td> <td align="center"> Rain </td> <td align="center"> Mild </td> <td align="center"> High </td> <td align="center"> Strong </td> <td align="center"> 0 </td> </tr>
</tbody>
</table>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="simple-python-code-to-read-in-data-and-perform-classification">Simple Python Code to read in Data and perform Classification </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Common imports</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler, OneHotEncoder
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.compose</span> <span style="color: #008000; font-weight: bold">import</span> ColumnTransformer
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> Image
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pydot</span> <span style="color: #008000; font-weight: bold">import</span> graph_from_dot_data
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #408080; font-style: italic"># Where to save the figures and data files</span>
PROJECT_ROOT_DIR <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;Results&quot;</span>
FIGURE_ID <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;Results/FigureFiles&quot;</span>
DATA_ID <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;DataFiles/&quot;</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(PROJECT_ROOT_DIR):
os<span style="color: #666666">.</span>mkdir(PROJECT_ROOT_DIR)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(FIGURE_ID):
os<span style="color: #666666">.</span>makedirs(FIGURE_ID)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(DATA_ID):
os<span style="color: #666666">.</span>makedirs(DATA_ID)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">image_path</span>(fig_id):
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(FIGURE_ID, fig_id)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">data_path</span>(dat_id):
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(DATA_ID, dat_id)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;.png&quot;</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">&#39;png&#39;</span>)
infile <span style="color: #666666">=</span> <span style="color: #008000">open</span>(data_path(<span style="color: #BA2121">&quot;rideclass.csv&quot;</span>),<span style="color: #BA2121">&#39;r&#39;</span>)
<span style="color: #408080; font-style: italic"># Read the experimental data with Pandas</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
ridedata <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>read_csv(infile,names <span style="color: #666666">=</span> (<span style="color: #BA2121">&#39;Outlook&#39;</span>,<span style="color: #BA2121">&#39;Temperature&#39;</span>,<span style="color: #BA2121">&#39;Humidity&#39;</span>,<span style="color: #BA2121">&#39;Wind&#39;</span>,<span style="color: #BA2121">&#39;Ride&#39;</span>))
ridedata <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(ridedata)
<span style="color: #408080; font-style: italic"># Features and targets</span>
X <span style="color: #666666">=</span> ridedata<span style="color: #666666">.</span>loc[:, ridedata<span style="color: #666666">.</span>columns <span style="color: #666666">!=</span> <span style="color: #BA2121">&#39;Ride&#39;</span>]<span style="color: #666666">.</span>values
y <span style="color: #666666">=</span> ridedata<span style="color: #666666">.</span>loc[:, ridedata<span style="color: #666666">.</span>columns <span style="color: #666666">==</span> <span style="color: #BA2121">&#39;Ride&#39;</span>]<span style="color: #666666">.</span>values
<span style="color: #408080; font-style: italic"># Create the encoder.</span>
encoder <span style="color: #666666">=</span> OneHotEncoder(handle_unknown<span style="color: #666666">=</span><span style="color: #BA2121">&quot;ignore&quot;</span>)
<span style="color: #408080; font-style: italic"># Assume for simplicity all features are categorical.</span>
encoder<span style="color: #666666">.</span>fit(X)
<span style="color: #408080; font-style: italic"># Apply the encoder.</span>
X <span style="color: #666666">=</span> encoder<span style="color: #666666">.</span>transform(X)
<span style="color: #008000">print</span>(X)
<span style="color: #408080; font-style: italic"># Then do a Classification tree</span>
tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=2</span>)
tree_clf<span style="color: #666666">.</span>fit(X, y)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Train set accuracy with Decision Tree: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(tree_clf<span style="color: #666666">.</span>score(X,y)))
<span style="color: #408080; font-style: italic">#transfer to a decision tree graph</span>
export_graphviz(
tree_clf,
out_file<span style="color: #666666">=</span><span style="color: #BA2121">&quot;DataFiles/ride.dot&quot;</span>,
rounded<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>,
filled<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>
)
cmd <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png&#39;</span>
os<span style="color: #666666">.</span>system(cmd)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="computing-the-gini-factor">Computing the Gini Factor </h2>
<p>The above functions (gini, entropy and misclassification error) are
important components of the so-called CART algorithm. We will discuss
this algorithm below after we have discussed the information gain
algorithm ID3.
</p>
<p>In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Split a dataset based on an attribute and an attribute value</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">test_split</span>(index, value, dataset):
left, right <span style="color: #666666">=</span> <span style="color: #008000">list</span>(), <span style="color: #008000">list</span>()
<span style="color: #008000; font-weight: bold">for</span> row <span style="color: #AA22FF; font-weight: bold">in</span> dataset:
<span style="color: #008000; font-weight: bold">if</span> row[index] <span style="color: #666666">&lt;</span> value:
left<span style="color: #666666">.</span>append(row)
<span style="color: #008000; font-weight: bold">else</span>:
right<span style="color: #666666">.</span>append(row)
<span style="color: #008000; font-weight: bold">return</span> left, right
<span style="color: #408080; font-style: italic"># Calculate the Gini index for a split dataset</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">gini_index</span>(groups, classes):
<span style="color: #408080; font-style: italic"># count all samples at split point</span>
n_instances <span style="color: #666666">=</span> <span style="color: #008000">float</span>(<span style="color: #008000">sum</span>([<span style="color: #008000">len</span>(group) <span style="color: #008000; font-weight: bold">for</span> group <span style="color: #AA22FF; font-weight: bold">in</span> groups]))
<span style="color: #408080; font-style: italic"># sum weighted Gini index for each group</span>
gini <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
<span style="color: #008000; font-weight: bold">for</span> group <span style="color: #AA22FF; font-weight: bold">in</span> groups:
size <span style="color: #666666">=</span> <span style="color: #008000">float</span>(<span style="color: #008000">len</span>(group))
<span style="color: #408080; font-style: italic"># avoid divide by zero</span>
<span style="color: #008000; font-weight: bold">if</span> size <span style="color: #666666">==</span> <span style="color: #666666">0</span>:
<span style="color: #008000; font-weight: bold">continue</span>
score <span style="color: #666666">=</span> <span style="color: #666666">0.0</span>
<span style="color: #408080; font-style: italic"># score the group based on the score for each class</span>
<span style="color: #008000; font-weight: bold">for</span> class_val <span style="color: #AA22FF; font-weight: bold">in</span> classes:
p <span style="color: #666666">=</span> [row[<span style="color: #666666">-1</span>] <span style="color: #008000; font-weight: bold">for</span> row <span style="color: #AA22FF; font-weight: bold">in</span> group]<span style="color: #666666">.</span>count(class_val) <span style="color: #666666">/</span> size
score <span style="color: #666666">+=</span> p <span style="color: #666666">*</span> p
<span style="color: #408080; font-style: italic"># weight the group score by its relative size</span>
gini <span style="color: #666666">+=</span> (<span style="color: #666666">1.0</span> <span style="color: #666666">-</span> score) <span style="color: #666666">*</span> (size <span style="color: #666666">/</span> n_instances)
<span style="color: #008000; font-weight: bold">return</span> gini
<span style="color: #408080; font-style: italic"># Select the best split point for a dataset</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">get_split</span>(dataset):
class_values <span style="color: #666666">=</span> <span style="color: #008000">list</span>(<span style="color: #008000">set</span>(row[<span style="color: #666666">-1</span>] <span style="color: #008000; font-weight: bold">for</span> row <span style="color: #AA22FF; font-weight: bold">in</span> dataset))
b_index, b_value, b_score, b_groups <span style="color: #666666">=</span> <span style="color: #666666">999</span>, <span style="color: #666666">999</span>, <span style="color: #666666">999</span>, <span style="color: #008000; font-weight: bold">None</span>
<span style="color: #008000; font-weight: bold">for</span> index <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">len</span>(dataset[<span style="color: #666666">0</span>])<span style="color: #666666">-1</span>):
<span style="color: #008000; font-weight: bold">for</span> row <span style="color: #AA22FF; font-weight: bold">in</span> dataset:
groups <span style="color: #666666">=</span> test_split(index, row[index], dataset)
gini <span style="color: #666666">=</span> gini_index(groups, class_values)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;X</span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> &lt; </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121"> Gini=</span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">&#39;</span> <span style="color: #666666">%</span> ((index<span style="color: #666666">+1</span>), row[index], gini))
<span style="color: #008000; font-weight: bold">if</span> gini <span style="color: #666666">&lt;</span> b_score:
b_index, b_value, b_score, b_groups <span style="color: #666666">=</span> index, row[index], gini, groups
<span style="color: #008000; font-weight: bold">return</span> {<span style="color: #BA2121">&#39;index&#39;</span>:b_index, <span style="color: #BA2121">&#39;value&#39;</span>:b_value, <span style="color: #BA2121">&#39;groups&#39;</span>:b_groups}
dataset <span style="color: #666666">=</span> [[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>],
[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">2</span>,<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">2</span>,<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>],
[<span style="color: #666666">1</span>,<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">0</span>],
[<span style="color: #666666">0</span>,<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">1</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>],
[<span style="color: #666666">2</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,<span style="color: #666666">0</span>]]
split <span style="color: #666666">=</span> get_split(dataset)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Split: [X</span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> &lt; </span><span style="color: #BB6688; font-weight: bold">%.3f</span><span style="color: #BA2121">]&#39;</span> <span style="color: #666666">%</span> ((split[<span style="color: #BA2121">&#39;index&#39;</span>]<span style="color: #666666">+1</span>), split[<span style="color: #BA2121">&#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>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="entropy-and-the-id3-algorithm">Entropy and the ID3 algorithm </h2>
<p>The ID3 algorithm learns decision trees by constructing
them in a top down way, beginning with the question <b>which attribute should be tested at the root of the tree</b>?
</p>
<ol>
<li> Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.</li>
<li> The best attribute is selected and used as the test at the root node of the tree.</li>
<li> A descendant of the root node is then created for each possible value of this attribute.</li>
<li> Training examples are sorted to the appropriate descendant node.</li>
<li> The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.</li>
<li> This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.</li>
</ol>
<p>The ID3 algorithm selects which attribute to test at each node in the
tree.
</p>
<p>We would like to select the attribute that is most useful for classifying
examples.
</p>
<p>What is a good quantitative measure of the worth of an attribute?</p>
<p>Information gain measures how well a given attribute separates the
training examples according to their target classification.
</p>
<p>The ID3 algorithm uses this information gain measure to select among the candidate
attributes at each step while growing the tree.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="cancer-data-again-now-with-decision-trees-and-other-methods">Cancer Data again now with Decision Trees and other Methods </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #408080; font-style: italic"># Load the data</span>
cancer <span style="color: #666666">=</span> load_breast_cancer()
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(cancer<span style="color: #666666">.</span>data,cancer<span style="color: #666666">.</span>target,random_state<span style="color: #666666">=0</span>)
<span style="color: #008000">print</span>(X_train<span style="color: #666666">.</span>shape)
<span style="color: #008000">print</span>(X_test<span style="color: #666666">.</span>shape)
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
logreg <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">&#39;lbfgs&#39;</span>)
logreg<span style="color: #666666">.</span>fit(X_train, y_train)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Logistic Regression: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test,y_test)))
<span style="color: #408080; font-style: italic"># Support vector machine</span>
svm <span style="color: #666666">=</span> SVC(gamma<span style="color: #666666">=</span><span style="color: #BA2121">&#39;auto&#39;</span>, C<span style="color: #666666">=100</span>)
svm<span style="color: #666666">.</span>fit(X_train, y_train)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with SVM: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(svm<span style="color: #666666">.</span>score(X_test,y_test)))
<span style="color: #408080; font-style: italic"># Decision Trees</span>
deep_tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>)
deep_tree_clf<span style="color: #666666">.</span>fit(X_train, y_train)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Decision Trees: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(deep_tree_clf<span style="color: #666666">.</span>score(X_test,y_test)))
<span style="color: #408080; font-style: italic">#now scale the data</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler
scaler <span style="color: #666666">=</span> StandardScaler()
scaler<span style="color: #666666">.</span>fit(X_train)
X_train_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
X_test_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_test)
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
logreg<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy Logistic Regression with scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
<span style="color: #408080; font-style: italic"># Support Vector Machine</span>
svm<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy SVM with scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
<span style="color: #408080; font-style: italic"># Decision Trees</span>
deep_tree_clf<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Decision Trees and scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(deep_tree_clf<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="another-example-the-moons-again">Another example, the moons again </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">__future__</span> <span style="color: #008000; font-weight: bold">import</span> division, print_function, unicode_literals
<span style="color: #408080; font-style: italic"># Common imports</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #408080; font-style: italic"># to make this notebook&#39;s output stable across runs</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">42</span>)
<span style="color: #408080; font-style: italic"># To plot pretty figures</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib.colors</span> <span style="color: #008000; font-weight: bold">import</span> ListedColormap
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;axes.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">14</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;xtick.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;ytick.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> export_graphviz
Xm, ym <span style="color: #666666">=</span> make_moons(n_samples<span style="color: #666666">=100</span>, noise<span style="color: #666666">=0.25</span>, random_state<span style="color: #666666">=53</span>)
deep_tree_clf1 <span style="color: #666666">=</span> DecisionTreeClassifier(random_state<span style="color: #666666">=42</span>)
deep_tree_clf2 <span style="color: #666666">=</span> DecisionTreeClassifier(min_samples_leaf<span style="color: #666666">=4</span>, random_state<span style="color: #666666">=42</span>)
deep_tree_clf1<span style="color: #666666">.</span>fit(Xm, ym)
deep_tree_clf2<span style="color: #666666">.</span>fit(Xm, ym)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plot_decision_boundary</span>(clf, X, y, axes<span style="color: #666666">=</span>[<span style="color: #666666">0</span>, <span style="color: #666666">7.5</span>, <span style="color: #666666">0</span>, <span style="color: #666666">3</span>], iris<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, legend<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>, plot_training<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>):
x1s <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(axes[<span style="color: #666666">0</span>], axes[<span style="color: #666666">1</span>], <span style="color: #666666">100</span>)
x2s <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(axes[<span style="color: #666666">2</span>], axes[<span style="color: #666666">3</span>], <span style="color: #666666">100</span>)
x1, x2 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x1s, x2s)
X_new <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[x1<span style="color: #666666">.</span>ravel(), x2<span style="color: #666666">.</span>ravel()]
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_new)<span style="color: #666666">.</span>reshape(x1<span style="color: #666666">.</span>shape)
custom_cmap <span style="color: #666666">=</span> ListedColormap([<span style="color: #BA2121">&#39;#fafab0&#39;</span>,<span style="color: #BA2121">&#39;#9898ff&#39;</span>,<span style="color: #BA2121">&#39;#a0faa0&#39;</span>])
plt<span style="color: #666666">.</span>contourf(x1, x2, y_pred, alpha<span style="color: #666666">=0.3</span>, cmap<span style="color: #666666">=</span>custom_cmap)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> iris:
custom_cmap2 <span style="color: #666666">=</span> ListedColormap([<span style="color: #BA2121">&#39;#7d7d58&#39;</span>,<span style="color: #BA2121">&#39;#4c4c7f&#39;</span>,<span style="color: #BA2121">&#39;#507d50&#39;</span>])
plt<span style="color: #666666">.</span>contour(x1, x2, y_pred, cmap<span style="color: #666666">=</span>custom_cmap2, alpha<span style="color: #666666">=0.8</span>)
<span style="color: #008000; font-weight: bold">if</span> plot_training:
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==0</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==0</span>], <span style="color: #BA2121">&quot;yo&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Iris-Setosa&quot;</span>)
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==1</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==1</span>], <span style="color: #BA2121">&quot;bs&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Iris-Versicolor&quot;</span>)
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==2</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==2</span>], <span style="color: #BA2121">&quot;g^&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;Iris-Virginica&quot;</span>)
plt<span style="color: #666666">.</span>axis(axes)
<span style="color: #008000; font-weight: bold">if</span> iris:
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;Petal length&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&quot;Petal width&quot;</span>, fontsize<span style="color: #666666">=14</span>)
<span style="color: #008000; font-weight: bold">else</span>:
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&quot;$x_2$&quot;</span>, fontsize<span style="color: #666666">=18</span>, rotation<span style="color: #666666">=0</span>)
<span style="color: #008000; font-weight: bold">if</span> legend:
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&quot;lower right&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
plot_decision_boundary(deep_tree_clf1, Xm, ym, axes<span style="color: #666666">=</span>[<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>], iris<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;No restrictions&quot;</span>, fontsize<span style="color: #666666">=16</span>)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
plot_decision_boundary(deep_tree_clf2, Xm, ym, axes<span style="color: #666666">=</span>[<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>], iris<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;min_samples_leaf = </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(deep_tree_clf2<span style="color: #666666">.</span>min_samples_leaf), fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="playing-around-with-regions">Playing around with regions </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">6</span>)
Xs <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>, <span style="color: #666666">2</span>) <span style="color: #666666">-</span> <span style="color: #666666">0.5</span>
ys <span style="color: #666666">=</span> (Xs[:, <span style="color: #666666">0</span>] <span style="color: #666666">&gt;</span> <span style="color: #666666">0</span>)<span style="color: #666666">.</span>astype(np<span style="color: #666666">.</span>float32) <span style="color: #666666">*</span> <span style="color: #666666">2</span>
angle <span style="color: #666666">=</span> np<span style="color: #666666">.</span>pi<span style="color: #666666">/4</span>
rotation_matrix <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[np<span style="color: #666666">.</span>cos(angle), <span style="color: #666666">-</span>np<span style="color: #666666">.</span>sin(angle)], [np<span style="color: #666666">.</span>sin(angle), np<span style="color: #666666">.</span>cos(angle)]])
Xsr <span style="color: #666666">=</span> Xs<span style="color: #666666">.</span>dot(rotation_matrix)
tree_clf_s <span style="color: #666666">=</span> DecisionTreeClassifier(random_state<span style="color: #666666">=42</span>)
tree_clf_s<span style="color: #666666">.</span>fit(Xs, ys)
tree_clf_sr <span style="color: #666666">=</span> DecisionTreeClassifier(random_state<span style="color: #666666">=42</span>)
tree_clf_sr<span style="color: #666666">.</span>fit(Xsr, ys)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
plot_decision_boundary(tree_clf_s, Xs, ys, axes<span style="color: #666666">=</span>[<span style="color: #666666">-0.7</span>, <span style="color: #666666">0.7</span>, <span style="color: #666666">-0.7</span>, <span style="color: #666666">0.7</span>], iris<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
plot_decision_boundary(tree_clf_sr, Xsr, ys, axes<span style="color: #666666">=</span>[<span style="color: #666666">-0.7</span>, <span style="color: #666666">0.7</span>, <span style="color: #666666">-0.7</span>, <span style="color: #666666">0.7</span>], iris<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="regression-trees">Regression trees </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Quadratic training set + noise</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">42</span>)
m <span style="color: #666666">=</span> <span style="color: #666666">200</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(m, <span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">4</span> <span style="color: #666666">*</span> (X <span style="color: #666666">-</span> <span style="color: #666666">0.5</span>) <span style="color: #666666">**</span> <span style="color: #666666">2</span>
y <span style="color: #666666">=</span> y <span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(m, <span style="color: #666666">1</span>) <span style="color: #666666">/</span> <span style="color: #666666">10</span>
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
tree_reg <span style="color: #666666">=</span> DecisionTreeRegressor(max_depth<span style="color: #666666">=2</span>, random_state<span style="color: #666666">=42</span>)
tree_reg<span style="color: #666666">.</span>fit(X, y)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="final-regressor-code">Final regressor code </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
tree_reg1 <span style="color: #666666">=</span> DecisionTreeRegressor(random_state<span style="color: #666666">=42</span>, max_depth<span style="color: #666666">=2</span>)
tree_reg2 <span style="color: #666666">=</span> DecisionTreeRegressor(random_state<span style="color: #666666">=42</span>, max_depth<span style="color: #666666">=3</span>)
tree_reg1<span style="color: #666666">.</span>fit(X, y)
tree_reg2<span style="color: #666666">.</span>fit(X, y)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plot_regression_predictions</span>(tree_reg, X, y, axes<span style="color: #666666">=</span>[<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">-0.2</span>, <span style="color: #666666">1</span>], ylabel<span style="color: #666666">=</span><span style="color: #BA2121">&quot;$y$&quot;</span>):
x1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(axes[<span style="color: #666666">0</span>], axes[<span style="color: #666666">1</span>], <span style="color: #666666">500</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
y_pred <span style="color: #666666">=</span> tree_reg<span style="color: #666666">.</span>predict(x1)
plt<span style="color: #666666">.</span>axis(axes)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
<span style="color: #008000; font-weight: bold">if</span> ylabel:
plt<span style="color: #666666">.</span>ylabel(ylabel, fontsize<span style="color: #666666">=18</span>, rotation<span style="color: #666666">=0</span>)
plt<span style="color: #666666">.</span>plot(X, y, <span style="color: #BA2121">&quot;b.&quot;</span>)
plt<span style="color: #666666">.</span>plot(x1, y_pred, <span style="color: #BA2121">&quot;r.-&quot;</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">r&quot;$\hat</span><span style="color: #BB6688; font-weight: bold">{y}</span><span style="color: #BA2121">$&quot;</span>)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
plot_regression_predictions(tree_reg1, X, y)
<span style="color: #008000; font-weight: bold">for</span> split, style <span style="color: #AA22FF; font-weight: bold">in</span> ((<span style="color: #666666">0.1973</span>, <span style="color: #BA2121">&quot;k-&quot;</span>), (<span style="color: #666666">0.0917</span>, <span style="color: #BA2121">&quot;k--&quot;</span>), (<span style="color: #666666">0.7718</span>, <span style="color: #BA2121">&quot;k--&quot;</span>)):
plt<span style="color: #666666">.</span>plot([split, split], [<span style="color: #666666">-0.2</span>, <span style="color: #666666">1</span>], style, linewidth<span style="color: #666666">=2</span>)
plt<span style="color: #666666">.</span>text(<span style="color: #666666">0.21</span>, <span style="color: #666666">0.65</span>, <span style="color: #BA2121">&quot;Depth=0&quot;</span>, fontsize<span style="color: #666666">=15</span>)
plt<span style="color: #666666">.</span>text(<span style="color: #666666">0.01</span>, <span style="color: #666666">0.2</span>, <span style="color: #BA2121">&quot;Depth=1&quot;</span>, fontsize<span style="color: #666666">=13</span>)
plt<span style="color: #666666">.</span>text(<span style="color: #666666">0.65</span>, <span style="color: #666666">0.8</span>, <span style="color: #BA2121">&quot;Depth=1&quot;</span>, fontsize<span style="color: #666666">=13</span>)
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&quot;upper center&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;max_depth=2&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
plot_regression_predictions(tree_reg2, X, y, ylabel<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>)
<span style="color: #008000; font-weight: bold">for</span> split, style <span style="color: #AA22FF; font-weight: bold">in</span> ((<span style="color: #666666">0.1973</span>, <span style="color: #BA2121">&quot;k-&quot;</span>), (<span style="color: #666666">0.0917</span>, <span style="color: #BA2121">&quot;k--&quot;</span>), (<span style="color: #666666">0.7718</span>, <span style="color: #BA2121">&quot;k--&quot;</span>)):
plt<span style="color: #666666">.</span>plot([split, split], [<span style="color: #666666">-0.2</span>, <span style="color: #666666">1</span>], style, linewidth<span style="color: #666666">=2</span>)
<span style="color: #008000; font-weight: bold">for</span> split <span style="color: #AA22FF; font-weight: bold">in</span> (<span style="color: #666666">0.0458</span>, <span style="color: #666666">0.1298</span>, <span style="color: #666666">0.2873</span>, <span style="color: #666666">0.9040</span>):
plt<span style="color: #666666">.</span>plot([split, split], [<span style="color: #666666">-0.2</span>, <span style="color: #666666">1</span>], <span style="color: #BA2121">&quot;k:&quot;</span>, linewidth<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>text(<span style="color: #666666">0.3</span>, <span style="color: #666666">0.5</span>, <span style="color: #BA2121">&quot;Depth=2&quot;</span>, fontsize<span style="color: #666666">=13</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;max_depth=3&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">tree_reg1 <span style="color: #666666">=</span> DecisionTreeRegressor(random_state<span style="color: #666666">=42</span>)
tree_reg2 <span style="color: #666666">=</span> DecisionTreeRegressor(random_state<span style="color: #666666">=42</span>, min_samples_leaf<span style="color: #666666">=10</span>)
tree_reg1<span style="color: #666666">.</span>fit(X, y)
tree_reg2<span style="color: #666666">.</span>fit(X, y)
x1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">500</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
y_pred1 <span style="color: #666666">=</span> tree_reg1<span style="color: #666666">.</span>predict(x1)
y_pred2 <span style="color: #666666">=</span> tree_reg2<span style="color: #666666">.</span>predict(x1)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
plt<span style="color: #666666">.</span>plot(X, y, <span style="color: #BA2121">&quot;b.&quot;</span>)
plt<span style="color: #666666">.</span>plot(x1, y_pred1, <span style="color: #BA2121">&quot;r.-&quot;</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">r&quot;$\hat</span><span style="color: #BB6688; font-weight: bold">{y}</span><span style="color: #BA2121">$&quot;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">-0.2</span>, <span style="color: #666666">1.1</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&quot;$y$&quot;</span>, fontsize<span style="color: #666666">=18</span>, rotation<span style="color: #666666">=0</span>)
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&quot;upper center&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;No restrictions&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
plt<span style="color: #666666">.</span>plot(X, y, <span style="color: #BA2121">&quot;b.&quot;</span>)
plt<span style="color: #666666">.</span>plot(x1, y_pred2, <span style="color: #BA2121">&quot;r.-&quot;</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">r&quot;$\hat</span><span style="color: #BB6688; font-weight: bold">{y}</span><span style="color: #BA2121">$&quot;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">-0.2</span>, <span style="color: #666666">1.1</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;min_samples_leaf=</span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">.</span>format(tree_reg2<span style="color: #666666">.</span>min_samples_leaf), fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="pros-and-cons-of-trees-pros">Pros and cons of trees, pros </h2>
<ul>
<li> White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)</li>
<li> Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!</li>
<li> No feature normalization needed</li>
<li> Tree models can handle both continuous and categorical data (Classification and Regression Trees)</li>
<li> Can model nonlinear relationships</li>
<li> Can model interactions between the different descriptive features</li>
<li> Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="disadvantages">Disadvantages </h2>
<ul>
<li> Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches</li>
<li> If continuous features are used the tree may become quite large and hence less interpretable</li>
<li> Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented</li>
<li> Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests</li>
<li> Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.</li>
<li> If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data</li>
<li> Features with many levels may be preferred over features with less levels since for them it is <em>more easy</em> to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain</li>
</ul>
<p>However, by aggregating many decision trees, using methods like
bagging, random forests, and boosting, the predictive performance of
trees can be substantially improved.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="ensemble-methods-from-a-single-tree-to-many-trees-and-extreme-boosting-meet-the-jungle-of-methods">Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods </h2>
<p>As stated above and seen in many of the examples discussed here about
a single decision tree, we often end up overfitting our training
data. This normally means that we have a high variance. Can we reduce
the variance of a statistical learning method?
</p>
<p>This leads us to a set of different methods that can combine different
machine learning algorithms or just use one of them to construct
forests and jungles of trees, homogeneous ones or heterogenous
ones. These methods are recognized by different names which we will
try to explain here. These are
</p>
<ol>
<li> Voting classifiers</li>
<li> Bagging and Pasting</li>
<li> Random forests</li>
<li> Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)</li>
</ol>
<p>We discuss these methods here.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="an-overview-of-ensemble-methods">An Overview of Ensemble Methods </h2>
<br/><br/>
<center>
<p><img src="DataFiles/ensembleoverview.png" width="600" align="bottom"></p>
</center>
<br/><br/>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="bagging">Bagging </h2>
<p>The <b>plain</b> decision trees suffer from high
variance. This means that if we split the training data into two parts
at random, and fit a decision tree to both halves, the results that we
get could be quite different. In contrast, a procedure with low
variance will yield similar results if applied repeatedly to distinct
data sets; linear regression tends to have low variance, if the ratio
of \( n \) to \( p \) is moderately large.
</p>
<p><b>Bootstrap aggregation</b>, or just <b>bagging</b>, is a
general-purpose procedure for reducing the variance of a statistical
learning method.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-bagging">More bagging </h2>
<p>Bagging typically results in improved accuracy
over prediction using a single tree. Unfortunately, however, it can be
difficult to interpret the resulting model. Recall that one of the
advantages of decision trees is the attractive and easily interpreted
diagram that results.
</p>
<p>However, when we bag a large number of trees, it is no longer
possible to represent the resulting statistical learning procedure
using a single tree, and it is no longer clear which variables are
most important to the procedure. Thus, bagging improves prediction
accuracy at the expense of interpretability. Although the collection
of bagged trees is much more difficult to interpret than a single
tree, one can obtain an overall summary of the importance of each
predictor using the MSE (for bagging regression trees) or the Gini
index (for bagging classification trees). In the case of bagging
regression trees, we can record the total amount that the MSE is
decreased due to splits over a given predictor, averaged over all \( B \) possible
trees. A large value indicates an important predictor. Similarly, in
the context of bagging classification trees, we can add up the total
amount that the Gini index is decreased by splits over a given
predictor, averaged over all \( B \) trees.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="simple-voting-example-head-or-tail">Simple Voting Example, head or tail </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">heads_proba <span style="color: #666666">=</span> <span style="color: #666666">0.51</span>
coin_tosses <span style="color: #666666">=</span> (np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">10000</span>, <span style="color: #666666">10</span>) <span style="color: #666666">&lt;</span> heads_proba)<span style="color: #666666">.</span>astype(np<span style="color: #666666">.</span>int32)
cumulative_heads_ratio <span style="color: #666666">=</span> np<span style="color: #666666">.</span>cumsum(coin_tosses, axis<span style="color: #666666">=0</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>arange(<span style="color: #666666">1</span>, <span style="color: #666666">10001</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">8</span>,<span style="color: #666666">3.5</span>))
plt<span style="color: #666666">.</span>plot(cumulative_heads_ratio)
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">0</span>, <span style="color: #666666">10000</span>], [<span style="color: #666666">0.51</span>, <span style="color: #666666">0.51</span>], <span style="color: #BA2121">&quot;k--&quot;</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;51%&quot;</span>)
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">0</span>, <span style="color: #666666">10000</span>], [<span style="color: #666666">0.5</span>, <span style="color: #666666">0.5</span>], <span style="color: #BA2121">&quot;k-&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;50%&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;Number of coin tosses&quot;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&quot;Heads ratio&quot;</span>)
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&quot;lower right&quot;</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>, <span style="color: #666666">10000</span>, <span style="color: #666666">0.42</span>, <span style="color: #666666">0.58</span>])
save_fig(<span style="color: #BA2121">&quot;votingsimple&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="using-the-voting-classifier">Using the Voting Classifier </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
X, y <span style="color: #666666">=</span> make_moons(n_samples<span style="color: #666666">=500</span>, noise<span style="color: #666666">=0.30</span>, random_state<span style="color: #666666">=42</span>)
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, random_state<span style="color: #666666">=42</span>)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> RandomForestClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> VotingClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
log_clf <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">&quot;liblinear&quot;</span>, random_state<span style="color: #666666">=42</span>)
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(n_estimators<span style="color: #666666">=10</span>, random_state<span style="color: #666666">=42</span>)
svm_clf <span style="color: #666666">=</span> SVC(gamma<span style="color: #666666">=</span><span style="color: #BA2121">&quot;auto&quot;</span>, random_state<span style="color: #666666">=42</span>)
voting_clf <span style="color: #666666">=</span> VotingClassifier(
estimators<span style="color: #666666">=</span>[(<span style="color: #BA2121">&#39;lr&#39;</span>, log_clf), (<span style="color: #BA2121">&#39;rf&#39;</span>, rnd_clf), (<span style="color: #BA2121">&#39;svc&#39;</span>, svm_clf)],
voting<span style="color: #666666">=</span><span style="color: #BA2121">&#39;hard&#39;</span>)
voting_clf<span style="color: #666666">.</span>fit(X_train, y_train)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #008000; font-weight: bold">for</span> clf <span style="color: #AA22FF; font-weight: bold">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
<span style="color: #008000">print</span>(clf<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span>, accuracy_score(y_test, y_pred))
log_clf <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">&quot;liblinear&quot;</span>, random_state<span style="color: #666666">=42</span>)
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(n_estimators<span style="color: #666666">=10</span>, random_state<span style="color: #666666">=42</span>)
svm_clf <span style="color: #666666">=</span> SVC(gamma<span style="color: #666666">=</span><span style="color: #BA2121">&quot;auto&quot;</span>, probability<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, random_state<span style="color: #666666">=42</span>)
voting_clf <span style="color: #666666">=</span> VotingClassifier(
estimators<span style="color: #666666">=</span>[(<span style="color: #BA2121">&#39;lr&#39;</span>, log_clf), (<span style="color: #BA2121">&#39;rf&#39;</span>, rnd_clf), (<span style="color: #BA2121">&#39;svc&#39;</span>, svm_clf)],
voting<span style="color: #666666">=</span><span style="color: #BA2121">&#39;soft&#39;</span>)
voting_clf<span style="color: #666666">.</span>fit(X_train, y_train)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #008000; font-weight: bold">for</span> clf <span style="color: #AA22FF; font-weight: bold">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
<span style="color: #008000">print</span>(clf<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span>, accuracy_score(y_test, y_pred))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="please-not-the-moons-again-voting-and-bagging">Please, not the moons again! Voting and Bagging </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
X, y <span style="color: #666666">=</span> make_moons(n_samples<span style="color: #666666">=500</span>, noise<span style="color: #666666">=0.30</span>, random_state<span style="color: #666666">=42</span>)
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, random_state<span style="color: #666666">=42</span>)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> RandomForestClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> VotingClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
log_clf <span style="color: #666666">=</span> LogisticRegression(random_state<span style="color: #666666">=42</span>)
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(random_state<span style="color: #666666">=42</span>)
svm_clf <span style="color: #666666">=</span> SVC(random_state<span style="color: #666666">=42</span>)
voting_clf <span style="color: #666666">=</span> VotingClassifier(
estimators<span style="color: #666666">=</span>[(<span style="color: #BA2121">&#39;lr&#39;</span>, log_clf), (<span style="color: #BA2121">&#39;rf&#39;</span>, rnd_clf), (<span style="color: #BA2121">&#39;svc&#39;</span>, svm_clf)],
voting<span style="color: #666666">=</span><span style="color: #BA2121">&#39;hard&#39;</span>)
voting_clf<span style="color: #666666">.</span>fit(X_train, y_train)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #008000; font-weight: bold">for</span> clf <span style="color: #AA22FF; font-weight: bold">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
<span style="color: #008000">print</span>(clf<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span>, accuracy_score(y_test, y_pred))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">log_clf <span style="color: #666666">=</span> LogisticRegression(random_state<span style="color: #666666">=42</span>)
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(random_state<span style="color: #666666">=42</span>)
svm_clf <span style="color: #666666">=</span> SVC(probability<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, random_state<span style="color: #666666">=42</span>)
voting_clf <span style="color: #666666">=</span> VotingClassifier(
estimators<span style="color: #666666">=</span>[(<span style="color: #BA2121">&#39;lr&#39;</span>, log_clf), (<span style="color: #BA2121">&#39;rf&#39;</span>, rnd_clf), (<span style="color: #BA2121">&#39;svc&#39;</span>, svm_clf)],
voting<span style="color: #666666">=</span><span style="color: #BA2121">&#39;soft&#39;</span>)
voting_clf<span style="color: #666666">.</span>fit(X_train, y_train)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #008000; font-weight: bold">for</span> clf <span style="color: #AA22FF; font-weight: bold">in</span> (log_clf, rnd_clf, svm_clf, voting_clf):
clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_test)
<span style="color: #008000">print</span>(clf<span style="color: #666666">.</span><span style="color: #19177C">__class__</span><span style="color: #666666">.</span><span style="color: #19177C">__name__</span>, accuracy_score(y_test, y_pred))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="bagging-examples">Bagging Examples </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> BaggingClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
bag_clf <span style="color: #666666">=</span> BaggingClassifier(
DecisionTreeClassifier(random_state<span style="color: #666666">=42</span>), n_estimators<span style="color: #666666">=500</span>,
max_samples<span style="color: #666666">=100</span>, bootstrap<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, n_jobs<span style="color: #666666">=-1</span>, random_state<span style="color: #666666">=42</span>)
bag_clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred <span style="color: #666666">=</span> bag_clf<span style="color: #666666">.</span>predict(X_test)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> accuracy_score
<span style="color: #008000">print</span>(accuracy_score(y_test, y_pred))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(random_state<span style="color: #666666">=42</span>)
tree_clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred_tree <span style="color: #666666">=</span> tree_clf<span style="color: #666666">.</span>predict(X_test)
<span style="color: #008000">print</span>(accuracy_score(y_test, y_pred_tree))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib.colors</span> <span style="color: #008000; font-weight: bold">import</span> ListedColormap
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plot_decision_boundary</span>(clf, X, y, axes<span style="color: #666666">=</span>[<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>], alpha<span style="color: #666666">=0.5</span>, contour<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>):
x1s <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(axes[<span style="color: #666666">0</span>], axes[<span style="color: #666666">1</span>], <span style="color: #666666">100</span>)
x2s <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(axes[<span style="color: #666666">2</span>], axes[<span style="color: #666666">3</span>], <span style="color: #666666">100</span>)
x1, x2 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x1s, x2s)
X_new <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[x1<span style="color: #666666">.</span>ravel(), x2<span style="color: #666666">.</span>ravel()]
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X_new)<span style="color: #666666">.</span>reshape(x1<span style="color: #666666">.</span>shape)
custom_cmap <span style="color: #666666">=</span> ListedColormap([<span style="color: #BA2121">&#39;#fafab0&#39;</span>,<span style="color: #BA2121">&#39;#9898ff&#39;</span>,<span style="color: #BA2121">&#39;#a0faa0&#39;</span>])
plt<span style="color: #666666">.</span>contourf(x1, x2, y_pred, alpha<span style="color: #666666">=0.3</span>, cmap<span style="color: #666666">=</span>custom_cmap)
<span style="color: #008000; font-weight: bold">if</span> contour:
custom_cmap2 <span style="color: #666666">=</span> ListedColormap([<span style="color: #BA2121">&#39;#7d7d58&#39;</span>,<span style="color: #BA2121">&#39;#4c4c7f&#39;</span>,<span style="color: #BA2121">&#39;#507d50&#39;</span>])
plt<span style="color: #666666">.</span>contour(x1, x2, y_pred, cmap<span style="color: #666666">=</span>custom_cmap2, alpha<span style="color: #666666">=0.8</span>)
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==0</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==0</span>], <span style="color: #BA2121">&quot;yo&quot;</span>, alpha<span style="color: #666666">=</span>alpha)
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==1</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==1</span>], <span style="color: #BA2121">&quot;bs&quot;</span>, alpha<span style="color: #666666">=</span>alpha)
plt<span style="color: #666666">.</span>axis(axes)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&quot;$x_2$&quot;</span>, fontsize<span style="color: #666666">=18</span>, rotation<span style="color: #666666">=0</span>)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>,<span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
plot_decision_boundary(tree_clf, X, y)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Decision Tree&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
plot_decision_boundary(bag_clf, X, y)
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">&quot;Decision Trees with Bagging&quot;</span>, fontsize<span style="color: #666666">=14</span>)
save_fig(<span style="color: #BA2121">&quot;baggingtree&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="making-your-own-bootstrap-changing-the-level-of-the-decision-tree">Making your own Bootstrap: Changing the Level of the Decision Tree </h2>
<p>Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with
a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)).
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.pipeline</span> <span style="color: #008000; font-weight: bold">import</span> make_pipeline
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.utils</span> <span style="color: #008000; font-weight: bold">import</span> resample
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeRegressor
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
n_boostraps <span style="color: #666666">=</span> <span style="color: #666666">100</span>
maxdepth <span style="color: #666666">=</span> <span style="color: #666666">8</span>
<span style="color: #408080; font-style: italic"># Make data set.</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-3</span>, <span style="color: #666666">3</span>, n)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> <span style="color: #666666">1.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(<span style="color: #666666">0</span>, <span style="color: #666666">0.1</span>, x<span style="color: #666666">.</span>shape)
error <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdepth)
bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdepth)
variance <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdepth)
polydegree <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdepth)
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(x, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler
scaler <span style="color: #666666">=</span> StandardScaler()
scaler<span style="color: #666666">.</span>fit(X_train)
X_train_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
X_test_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_test)
<span style="color: #408080; font-style: italic"># we produce a simple tree first as benchmark</span>
simpletree <span style="color: #666666">=</span> DecisionTreeRegressor(max_depth<span style="color: #666666">=3</span>)
simpletree<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
simpleprediction <span style="color: #666666">=</span> simpletree<span style="color: #666666">.</span>predict(X_test_scaled)
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,maxdepth):
model <span style="color: #666666">=</span> DecisionTreeRegressor(max_depth<span style="color: #666666">=</span>degree)
y_pred <span style="color: #666666">=</span> np<span style="color: #666666">.</span>empty((y_test<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], n_boostraps))
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_boostraps):
x_, y_ <span style="color: #666666">=</span> resample(X_train_scaled, y_train)
model<span style="color: #666666">.</span>fit(x_, y_)
y_pred[:, i] <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X_test_scaled)<span style="color: #408080; font-style: italic">#.ravel()</span>
polydegree[degree] <span style="color: #666666">=</span> degree
error[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>mean((y_test <span style="color: #666666">-</span> y_pred)<span style="color: #666666">**2</span>, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) )
bias[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( (y_test <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_pred, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>))<span style="color: #666666">**2</span> )
variance[degree] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>var(y_pred, axis<span style="color: #666666">=1</span>, keepdims<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>) )
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Polynomial degree:&#39;</span>, degree)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Error:&#39;</span>, error[degree])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Bias^2:&#39;</span>, bias[degree])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Var:&#39;</span>, variance[degree])
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;</span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> &gt;= </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> + </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121"> = </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">.</span>format(error[degree], bias[degree], variance[degree], bias[degree]<span style="color: #666666">+</span>variance[degree]))
mse_simpletree<span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean( np<span style="color: #666666">.</span>mean((y_test <span style="color: #666666">-</span> simpleprediction)<span style="color: #666666">**2</span>)
<span style="color: #008000">print</span>(mse_simpletree)
plt<span style="color: #666666">.</span>xlim(<span style="color: #666666">1</span>,maxdepth)
plt<span style="color: #666666">.</span>plot(polydegree, error, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;MSE&#39;</span>)
plt<span style="color: #666666">.</span>plot(polydegree, bias, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;bias&#39;</span>)
plt<span style="color: #666666">.</span>plot(polydegree, variance, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Variance&#39;</span>)
plt<span style="color: #666666">.</span>legend()
save_fig(<span style="color: #BA2121">&quot;baggingboot&quot;</span>)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>