Files
FYS-STK4155/doc/pub/week48/html/week48.html
T
2024-11-25 12:50:16 +01:00

2220 lines
130 KiB
HTML

<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week48.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week48 --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 48: Gradient boosting and summary of course">
<title>Week 48: Gradient boosting and summary of course</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 48', 2, None, 'overview-of-week-48'),
('Lecture Monday, November 25',
2,
None,
'lecture-monday-november-25'),
('Lab sessions', 2, None, 'lab-sessions'),
('Random Forest Algorithm, reminder from last week',
2,
None,
'random-forest-algorithm-reminder-from-last-week'),
('Random Forests Compared with other Methods on the Cancer Data',
2,
None,
'random-forests-compared-with-other-methods-on-the-cancer-data'),
('Compare Bagging on Trees with Random Forests',
2,
None,
'compare-bagging-on-trees-with-random-forests'),
("Boosting, a Bird's Eye View",
2,
None,
'boosting-a-bird-s-eye-view'),
('What is boosting? Additive Modelling/Iterative Fitting',
2,
None,
'what-is-boosting-additive-modelling-iterative-fitting'),
('Iterative Fitting, Regression and Squared-error Cost Function',
2,
None,
'iterative-fitting-regression-and-squared-error-cost-function'),
('Squared-Error Example and Iterative Fitting',
2,
None,
'squared-error-example-and-iterative-fitting'),
('Iterative Fitting, Classification and AdaBoost',
2,
None,
'iterative-fitting-classification-and-adaboost'),
('Adaptive Boosting, AdaBoost',
2,
None,
'adaptive-boosting-adaboost'),
('Building up AdaBoost', 2, None, 'building-up-adaboost'),
('Adaptive boosting: AdaBoost, Basic Algorithm',
2,
None,
'adaptive-boosting-adaboost-basic-algorithm'),
('Basic Steps of AdaBoost', 2, None, 'basic-steps-of-adaboost'),
('AdaBoost Examples', 2, None, 'adaboost-examples'),
('Making an ADAboost code yourself',
2,
None,
'making-an-adaboost-code-yourself'),
('Gradient boosting: Basics with Steepest Descent/Functional '
'Gradient Descent',
2,
None,
'gradient-boosting-basics-with-steepest-descent-functional-gradient-descent'),
('The Squared-Error again! Steepest Descent',
2,
None,
'the-squared-error-again-steepest-descent'),
('Steepest Descent Example', 2, None, 'steepest-descent-example'),
('Gradient Boosting, algorithm',
2,
None,
'gradient-boosting-algorithm'),
('Gradient Boosting, Examples of Regression',
2,
None,
'gradient-boosting-examples-of-regression'),
('Gradient Boosting, Classification Example',
2,
None,
'gradient-boosting-classification-example'),
('XGBoost: Extreme Gradient Boosting',
2,
None,
'xgboost-extreme-gradient-boosting'),
('Xgboost on the Cancer Data',
2,
None,
'xgboost-on-the-cancer-data'),
('Gradient boosting, making our own code for a regression case',
2,
None,
'gradient-boosting-making-our-own-code-for-a-regression-case'),
('Summary of course', 2, None, 'summary-of-course'),
('What? Me worry? No final exam in this course!',
2,
None,
'what-me-worry-no-final-exam-in-this-course'),
('Topics we have covered this year',
2,
None,
'topics-we-have-covered-this-year'),
('Statistical analysis and optimization of data',
2,
None,
'statistical-analysis-and-optimization-of-data'),
('Machine learning', 2, None, 'machine-learning'),
('Learning outcomes and overarching aims of this course',
2,
None,
'learning-outcomes-and-overarching-aims-of-this-course'),
('Perspective on Machine Learning',
2,
None,
'perspective-on-machine-learning'),
('Machine Learning Research',
2,
None,
'machine-learning-research'),
('Starting your Machine Learning Project',
2,
None,
'starting-your-machine-learning-project'),
('Choose a Model and Algorithm',
2,
None,
'choose-a-model-and-algorithm'),
('Preparing Your Data', 2, None, 'preparing-your-data'),
('Which activation and weights to choose in neural networks',
2,
None,
'which-activation-and-weights-to-choose-in-neural-networks'),
('Optimization Methods and Hyperparameters',
2,
None,
'optimization-methods-and-hyperparameters'),
('Resampling', 2, None, 'resampling'),
('Other courses on Data science and Machine Learning at UiO',
2,
None,
'other-courses-on-data-science-and-machine-learning-at-uio'),
('Additional courses of interest',
2,
None,
'additional-courses-of-interest'),
("What's the future like?", 2, None, 'what-s-the-future-like'),
('Types of Machine Learning, a repetition',
2,
None,
'types-of-machine-learning-a-repetition'),
('Why Boltzmann machines?', 2, None, 'why-boltzmann-machines'),
('Boltzmann Machines', 2, None, 'boltzmann-machines'),
('Some similarities and differences from DNNs',
2,
None,
'some-similarities-and-differences-from-dnns'),
('Boltzmann machines (BM)', 2, None, 'boltzmann-machines-bm'),
('A standard BM setup', 2, None, 'a-standard-bm-setup'),
('The structure of the RBM network',
2,
None,
'the-structure-of-the-rbm-network'),
('The network', 2, None, 'the-network'),
('Goals', 2, None, 'goals'),
('Joint distribution', 2, None, 'joint-distribution'),
('Network Elements, the energy function',
2,
None,
'network-elements-the-energy-function'),
('Defining different types of RBMs',
2,
None,
'defining-different-types-of-rbms'),
('More about RBMs', 2, None, 'more-about-rbms'),
('Autoencoders: Overarching view',
2,
None,
'autoencoders-overarching-view'),
('Bayesian Machine Learning',
2,
None,
'bayesian-machine-learning'),
('Reinforcement Learning', 2, None, 'reinforcement-learning'),
('Transfer learning', 2, None, 'transfer-learning'),
('Adversarial learning', 2, None, 'adversarial-learning'),
('Dual learning', 2, None, 'dual-learning'),
('Distributed machine learning',
2,
None,
'distributed-machine-learning'),
('Meta learning', 2, None, 'meta-learning'),
('The Challenges Facing Machine Learning',
2,
None,
'the-challenges-facing-machine-learning'),
('Explainable machine learning',
2,
None,
'explainable-machine-learning'),
('Quantum machine learning', 2, None, 'quantum-machine-learning'),
('Quantum machine learning algorithms based on linear algebra',
2,
None,
'quantum-machine-learning-algorithms-based-on-linear-algebra'),
('Quantum reinforcement learning',
2,
None,
'quantum-reinforcement-learning'),
('Quantum deep learning', 2, None, 'quantum-deep-learning'),
('Social machine learning', 2, None, 'social-machine-learning'),
('The last words?', 2, None, 'the-last-words'),
('Best wishes to you all and thanks so much for your heroic '
'efforts this semester',
2,
None,
'best-wishes-to-you-all-and-thanks-so-much-for-your-heroic-efforts-this-semester')]}
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 48: Gradient boosting and summary of course</h1>
</center> <!-- document title -->
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b>
</center>
<!-- institution -->
<center>
<b>Department of Physics and Center for Computing in Science Education, University of Oslo, Norway</b>
</center>
<br>
<center>
<h4>Nov 25, 2024</h4>
</center> <!-- date -->
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="overview-of-week-48">Overview of week 48 </h2>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lecture-monday-november-25">Lecture Monday, November 25 </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Plans for the lecture Monday 25 November, with video suggestions etc</b>
<p>
<ol>
<li> Boosting and gradient boosting and ensemble models</li>
<li> Summary of course</li>
<li> Readings and Videos:
<ol type="a"></li>
<li> These lecture notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week48/ipynb/week48.ipynb" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week48/ipynb/week48.ipynb</tt></a></li>
<li> See also lecture notes from week 47 at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week47/ipynb/week47.ipynb" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week47/ipynb/week47.ipynb</tt></a>. The lecture on Monday starts with a repetition on AdaBoost before we move over to gradient boosting with examples</li>
<li> Video of lecture at <a href="https://youtu.be/iTaRdAPQnDA" target="_blank"><tt>https://youtu.be/iTaRdAPQnDA</tt></a></li>
<li> Whiteboard notes at <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember25.pdf" target="_blank"><tt>https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember25.pdf</tt></a></li>
<li> Video on Decision trees <a href="https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn" target="_blank"><tt>https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn</tt></a></li>
<li> Video on boosting methods <a href="https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai" target="_blank"><tt>https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai</tt></a></li>
<li> Video on AdaBoost <a href="https://www.youtube.com/watch?v=LsK-xG1cLYA" target="_blank"><tt>https://www.youtube.com/watch?v=LsK-xG1cLYA</tt></a></li>
<li> Video on Gradient boost, part 1, parts 2-4 follow thereafter <a href="https://www.youtube.com/watch?v=3CC4N4z3GJc" target="_blank"><tt>https://www.youtube.com/watch?v=3CC4N4z3GJc</tt></a></li>
<li> Decision Trees: Rashcka et al chapter 3 pages 86-98, and chapter 7 on Ensemble methods, Voting and Bagging and Gradient Boosting. See also lecture from STK-IN4300, lecture 7 at <a href="https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf" target="_blank"><tt>https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf</tt></a>.</li>
</ol>
</ol>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="lab-sessions">Lab sessions </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b>Lab sessions on Tuesday and Wednesday</b>
<p>
<ul>
<li> Work and Discussion of project 3</li>
<li> Last weekly exercise</li>
<li> Lab sessions at usual times.</li>
<li> For the week of December 2-6, lab sessions start at 10am and end at 4pm, room F&#216;434, Tuesday and Wednesday</li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="random-forest-algorithm-reminder-from-last-week">Random Forest Algorithm, reminder from last week </h2>
<p>The algorithm described here can be applied to both classification and regression problems.</p>
<p>We will grow of forest of say \( B \) trees.</p>
<ul>
<li> For \( b=1:B \)
<ol type="a"></li>
<li> Draw a bootstrap sample from the training data organized in our \( \boldsymbol{X} \) matrix.</li>
<li> We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached</li>
<ol>
<li> we select \( m \le p \) variables at random from the \( p \) predictors/features</li>
<li> pick the best split point among the \( m \) features using for example the CART algorithm and create a new node</li>
<li> split the node into daughter nodes</li>
</ol>
</ol>
</ul>
<p>Finally we output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="random-forests-compared-with-other-methods-on-the-cancer-data">Random Forests Compared with other Methods on the Cancer Data </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.tree</span> <span style="color: #008000; font-weight: bold">import</span> DecisionTreeClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> BaggingClassifier
<span style="color: #408080; font-style: italic"># Load the data</span>
cancer <span style="color: #666666">=</span> load_breast_cancer()
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(cancer<span style="color: #666666">.</span>data,cancer<span style="color: #666666">.</span>target,random_state<span style="color: #666666">=0</span>)
<span style="color: #008000">print</span>(X_train<span style="color: #666666">.</span>shape)
<span style="color: #008000">print</span>(X_test<span style="color: #666666">.</span>shape)
<span style="color: #408080; font-style: italic">#define methods</span>
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
logreg <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">&#39;lbfgs&#39;</span>)
<span style="color: #408080; font-style: italic"># Support vector machine</span>
svm <span style="color: #666666">=</span> SVC(gamma<span style="color: #666666">=</span><span style="color: #BA2121">&#39;auto&#39;</span>, C<span style="color: #666666">=100</span>)
<span style="color: #408080; font-style: italic"># Decision Trees</span>
deep_tree_clf <span style="color: #666666">=</span> DecisionTreeClassifier(max_depth<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">None</span>)
<span style="color: #408080; font-style: italic">#Scale the data</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler
scaler <span style="color: #666666">=</span> StandardScaler()
scaler<span style="color: #666666">.</span>fit(X_train)
X_train_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
X_test_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_test)
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
logreg<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&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)))
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> RandomForestClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> LabelEncoder
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> cross_validate
<span style="color: #408080; font-style: italic"># Data set not specificied</span>
<span style="color: #408080; font-style: italic">#Instantiate the model with 500 trees and entropy as splitting criteria</span>
Random_Forest_model <span style="color: #666666">=</span> RandomForestClassifier(n_estimators<span style="color: #666666">=500</span>,criterion<span style="color: #666666">=</span><span style="color: #BA2121">&quot;entropy&quot;</span>)
Random_Forest_model<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
<span style="color: #408080; font-style: italic">#Cross validation</span>
accuracy <span style="color: #666666">=</span> cross_validate(Random_Forest_model,X_test_scaled,y_test,cv<span style="color: #666666">=10</span>)[<span style="color: #BA2121">&#39;test_score&#39;</span>]
<span style="color: #008000">print</span>(accuracy)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Random Forests 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(Random_Forest_model<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scikitplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skplt</span>
y_pred <span style="color: #666666">=</span> Random_Forest_model<span style="color: #666666">.</span>predict(X_test_scaled)
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_confusion_matrix(y_test, y_pred, normalize<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
plt<span style="color: #666666">.</span>show()
y_probas <span style="color: #666666">=</span> Random_Forest_model<span style="color: #666666">.</span>predict_proba(X_test_scaled)
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_roc(y_test, y_probas)
plt<span style="color: #666666">.</span>show()
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_cumulative_gain(y_test, y_probas)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>Recall that the cumulative gains curve shows the percentage of the
overall number of cases in a given category <em>gained</em> by targeting a
percentage of the total number of cases.
</p>
<p>Similarly, the receiver operating characteristic curve, or ROC curve,
displays the diagnostic ability of a binary classifier system as its
discrimination threshold is varied. It plots the true positive rate against the false positive rate.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="compare-bagging-on-trees-with-random-forests">Compare Bagging on Trees with Random Forests </h2>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">bag_clf <span style="color: #666666">=</span> BaggingClassifier(
DecisionTreeClassifier(splitter<span style="color: #666666">=</span><span style="color: #BA2121">&quot;random&quot;</span>, max_leaf_nodes<span style="color: #666666">=16</span>, random_state<span style="color: #666666">=42</span>),
n_estimators<span style="color: #666666">=500</span>, max_samples<span style="color: #666666">=1.0</span>, bootstrap<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>, n_jobs<span style="color: #666666">=-1</span>, random_state<span style="color: #666666">=42</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">bag_clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred <span style="color: #666666">=</span> bag_clf<span style="color: #666666">.</span>predict(X_test)
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> RandomForestClassifier
rnd_clf <span style="color: #666666">=</span> RandomForestClassifier(n_estimators<span style="color: #666666">=500</span>, max_leaf_nodes<span style="color: #666666">=16</span>, n_jobs<span style="color: #666666">=-1</span>, random_state<span style="color: #666666">=42</span>)
rnd_clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred_rf <span style="color: #666666">=</span> rnd_clf<span style="color: #666666">.</span>predict(X_test)
np<span style="color: #666666">.</span>sum(y_pred <span style="color: #666666">==</span> y_pred_rf) <span style="color: #666666">/</span> <span style="color: #008000">len</span>(y_pred)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="boosting-a-bird-s-eye-view">Boosting, a Bird's Eye View </h2>
<p>The basic idea is to combine weak classifiers in order to create a good
classifier. With a weak classifier we often intend a classifier which
produces results which are only slightly better than we would get by
random guesses.
</p>
<p>This is done by applying in an iterative way a weak (or a standard
classifier like decision trees) to modify the data. In each iteration
we emphasize those observations which are misclassified by weighting
them with a factor.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="what-is-boosting-additive-modelling-iterative-fitting">What is boosting? Additive Modelling/Iterative Fitting </h2>
<p>Boosting is a way of fitting an additive expansion in a set of
elementary basis functions like for example some simple polynomials.
Assume for example that we have a function
</p>
$$
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
$$
<p>where \( \beta_m \) are the expansion parameters to be determined in a
minimization process and \( b(x;\gamma_m) \) are some simple functions of
the multivariable parameter \( x \) which is characterized by the
parameters \( \gamma_m \).
</p>
<p>As an example, consider the Sigmoid function we used in logistic
regression. In that case, we can translate the function
\( b(x;\gamma_m) \) into the Sigmoid function
</p>
$$
\sigma(t) = \frac{1}{1+\exp{(-t)}},
$$
<p>where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and
\( \gamma_1 \) were determined by the Logistic Regression fitting
algorithm.
</p>
<p>As another example, consider the cost function we defined for linear regression</p>
$$
C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
<p>In this case the function \( f(x) \) was replaced by the design matrix
\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \),
that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can
simply invert a matrix and obtain the parameters \( \beta \) by
</p>
$$
\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
<p>In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="iterative-fitting-regression-and-squared-error-cost-function">Iterative Fitting, Regression and Squared-error Cost Function </h2>
<p>The way we proceed is as follows (here we specialize to the squared-error cost function)</p>
<ol>
<li> Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).</li>
<li> Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.</li>
<li> For \( m=1:M \)
<ol type="a"></li>
<li> minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)</li>
<li> This gives the optimal values \( \beta_m \) and \( \gamma_m \)</li>
<li> Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)</li>
</ol>
</ol>
<p>We could use any of the algorithms we have discussed till now. If we
use trees, \( \gamma \) parameterizes the split variables and split points
at the internal nodes, and the predictions at the terminal nodes.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="squared-error-example-and-iterative-fitting">Squared-Error Example and Iterative Fitting </h2>
<p>To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.</p>
<p>For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). </p>
<p>This means that for every iteration \( m \), we need to optimize</p>
$$
(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2.
$$
<p>We start our iteration by simply setting \( f_0(x)=0 \).
Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
</p>
$$
\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
$$
<p>and</p>
$$
\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
$$
<p>We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)</p>
$$
\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0,
$$
<p>which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have </p>
$$
\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0,
$$
<p>which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting
for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically.
</p>
<p>The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as
\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="iterative-fitting-classification-and-adaboost">Iterative Fitting, Classification and AdaBoost </h2>
<p>Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of
observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values
\( \{-1,1\} \).
</p>
<p>The error rate of the training sample is then</p>
$$
\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
$$
<p>The iterative procedure starts with defining a weak classifier whose
error rate is barely better than random guessing. The iterative
procedure in boosting is to sequentially apply a weak
classification algorithm to repeatedly modified versions of the data
producing a sequence of weak classifiers \( G_m(x) \).
</p>
<p>Here we will express our function \( f(x) \) in terms of \( G(x) \). That is</p>
$$
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
$$
<p>will be a function of </p>
$$
G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adaptive-boosting-adaboost">Adaptive Boosting, AdaBoost </h2>
<p>In our iterative procedure we define thus</p>
$$
f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
$$
<p>The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
exponential cost/loss function defined as
</p>
$$
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
$$
<p>We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case.
This is normally done in two steps. Let us however first rewrite the cost function as
</p>
$$
C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
$$
<p>where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="building-up-adaboost">Building up AdaBoost </h2>
<p>First, for any \( \beta > 0 \), we optimize \( G \) by setting</p>
$$
G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
$$
<p>which is the classifier that minimizes the weighted error rate in predicting \( y \).</p>
<p>We can do this by rewriting</p>
$$
\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
$$
<p>which can be rewritten as</p>
$$
(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,
$$
<p>which leads to</p>
$$
\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
$$
<p>where we have redefined the error as </p>
$$
\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},
$$
<p>which leads to an update of</p>
$$
f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
$$
<p>This leads to the new weights</p>
$$
w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adaptive-boosting-adaboost-basic-algorithm">Adaptive boosting: AdaBoost, Basic Algorithm </h2>
<p>The algorithm here is rather straightforward. Assume that our weak
classifier is a decision tree and we consider a binary set of outputs
with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of
observations. Our design matrix is given in terms of the
feature/predictor vectors
\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a
classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \).
</p>
<p>We have already defined the misclassification error \( \mathrm{err} \) as</p>
$$
\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
$$
<p>where the function \( I() \) is one if we misclassify and zero if we classify correctly. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="basic-steps-of-adaboost">Basic Steps of AdaBoost </h2>
<p>With the above definitions we are now ready to set up the algorithm for AdaBoost.
The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.
</p>
<ol>
<li> We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).</li>
<li> We rewrite the misclassification error as</li>
</ol>
$$
\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i},
$$
<ol>
<li> Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree.
<ol type="a"></li>
<li> Fit then a given classifier to the training set using the weights \( w_i \).</li>
<li> Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.</li>
<li> Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)</li>
<li> Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).</li>
</ol>
<li> Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).</li>
</ol>
<p>For the iterations with \( m \le 2 \) the weights are modified
individually at each steps. The observations which were misclassified
at iteration \( m-1 \) have a weight which is larger than those which were
classified properly. As this proceeds, the observations which were
difficult to classifiy correctly are given a larger influence. Each
new classification step \( m \) is then forced to concentrate on those
observations that are missed in the previous iterations.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adaboost-examples">AdaBoost Examples </h2>
<p>Using <b>Scikit-Learn</b> it is easy to apply the adaptive boosting algorithm, as done here.</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> AdaBoostClassifier
ada_clf <span style="color: #666666">=</span> AdaBoostClassifier(
DecisionTreeClassifier(max_depth<span style="color: #666666">=2</span>), n_estimators<span style="color: #666666">=200</span>,
algorithm<span style="color: #666666">=</span><span style="color: #BA2121">&quot;SAMME.R&quot;</span>, learning_rate<span style="color: #666666">=0.01</span>, random_state<span style="color: #666666">=42</span>)
ada_clf<span style="color: #666666">.</span>fit(X_train, y_train)
y_pred <span style="color: #666666">=</span> ada_clf<span style="color: #666666">.</span>predict(X_test)
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_confusion_matrix(y_test, y_pred, normalize<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
plt<span style="color: #666666">.</span>show()
y_probas <span style="color: #666666">=</span> ada_clf<span style="color: #666666">.</span>predict_proba(X_test)
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_roc(y_test, y_probas)
plt<span style="color: #666666">.</span>show()
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_cumulative_gain(y_test, y_probas)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="making-an-adaboost-code-yourself">Making an ADAboost code yourself </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">class</span> <span style="color: #0000FF; font-weight: bold">DecisionStump</span>:
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">fit</span>(<span style="color: #008000">self</span>, X, y, weights):
m, n <span style="color: #666666">=</span> X<span style="color: #666666">.</span>shape
<span style="color: #008000">self</span><span style="color: #666666">.</span>alpha <span style="color: #666666">=</span> <span style="color: #666666">0</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>threshold <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>polarity <span style="color: #666666">=</span> <span style="color: #666666">1</span>
min_error <span style="color: #666666">=</span> <span style="color: #008000">float</span>(<span style="color: #BA2121">&#39;inf&#39;</span>)
<span style="color: #008000; font-weight: bold">for</span> feature <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n):
feature_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>unique(X[:, feature])
<span style="color: #008000; font-weight: bold">for</span> threshold <span style="color: #AA22FF; font-weight: bold">in</span> feature_values:
<span style="color: #008000; font-weight: bold">for</span> polarity <span style="color: #AA22FF; font-weight: bold">in</span> [<span style="color: #666666">1</span>, <span style="color: #666666">-1</span>]:
predictions <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ones(m)
predictions[X[:, feature] <span style="color: #666666">&lt;</span> threshold] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
predictions <span style="color: #666666">*=</span> polarity
error <span style="color: #666666">=</span> <span style="color: #008000">sum</span>(weights[predictions <span style="color: #666666">!=</span> y])
<span style="color: #008000; font-weight: bold">if</span> error <span style="color: #666666">&lt;</span> min_error:
min_error <span style="color: #666666">=</span> error
<span style="color: #008000">self</span><span style="color: #666666">.</span>alpha <span style="color: #666666">=</span> <span style="color: #666666">0.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>log((<span style="color: #666666">1</span> <span style="color: #666666">-</span> error) <span style="color: #666666">/</span> (error <span style="color: #666666">+</span> <span style="color: #666666">1e-10</span>))
<span style="color: #008000">self</span><span style="color: #666666">.</span>threshold <span style="color: #666666">=</span> threshold
<span style="color: #008000">self</span><span style="color: #666666">.</span>feature_index <span style="color: #666666">=</span> feature
<span style="color: #008000">self</span><span style="color: #666666">.</span>polarity <span style="color: #666666">=</span> polarity
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">predict</span>(<span style="color: #008000">self</span>, X):
m <span style="color: #666666">=</span> X<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]
predictions <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ones(m)
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>polarity <span style="color: #666666">==</span> <span style="color: #666666">1</span>:
predictions[X[:, <span style="color: #008000">self</span><span style="color: #666666">.</span>feature_index] <span style="color: #666666">&lt;</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>threshold] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
<span style="color: #008000; font-weight: bold">else</span>:
predictions[X[:, <span style="color: #008000">self</span><span style="color: #666666">.</span>feature_index] <span style="color: #666666">&gt;=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>threshold] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
<span style="color: #008000; font-weight: bold">return</span> predictions
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">AdaBoost</span>:
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">fit</span>(<span style="color: #008000">self</span>, X, y, n_estimators):
m <span style="color: #666666">=</span> X<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>]
<span style="color: #008000">self</span><span style="color: #666666">.</span>alphas <span style="color: #666666">=</span> []
<span style="color: #008000">self</span><span style="color: #666666">.</span>models <span style="color: #666666">=</span> []
weights <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ones(m) <span style="color: #666666">/</span> m
<span style="color: #008000; font-weight: bold">for</span> _ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_estimators):
stump <span style="color: #666666">=</span> DecisionStump()
stump<span style="color: #666666">.</span>fit(X, y, weights)
predictions <span style="color: #666666">=</span> stump<span style="color: #666666">.</span>predict(X)
error <span style="color: #666666">=</span> <span style="color: #008000">sum</span>(weights[predictions <span style="color: #666666">!=</span> y])
<span style="color: #008000; font-weight: bold">if</span> error <span style="color: #666666">==</span> <span style="color: #666666">0</span>:
<span style="color: #008000; font-weight: bold">break</span>
<span style="color: #008000">self</span><span style="color: #666666">.</span>models<span style="color: #666666">.</span>append(stump)
<span style="color: #008000">self</span><span style="color: #666666">.</span>alphas<span style="color: #666666">.</span>append(stump<span style="color: #666666">.</span>alpha)
weights <span style="color: #666666">*=</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>stump<span style="color: #666666">.</span>alpha <span style="color: #666666">*</span> y <span style="color: #666666">*</span> predictions)
weights <span style="color: #666666">/=</span> np<span style="color: #666666">.</span>sum(weights)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">predict</span>(<span style="color: #008000">self</span>, X):
final_predictions <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(X<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>])
<span style="color: #008000; font-weight: bold">for</span> alpha, model <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">zip</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>alphas, <span style="color: #008000">self</span><span style="color: #666666">.</span>models):
final_predictions <span style="color: #666666">+=</span> alpha <span style="color: #666666">*</span> model<span style="color: #666666">.</span>predict(X)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sign(final_predictions)
<span style="color: #408080; font-style: italic"># Example dataset (X, y)</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">1</span>], [<span style="color: #666666">2</span>], [<span style="color: #666666">3</span>], [<span style="color: #666666">4</span>], [<span style="color: #666666">5</span>], [<span style="color: #666666">6</span>], [<span style="color: #666666">7</span>], [<span style="color: #666666">8</span>], [<span style="color: #666666">9</span>], [<span style="color: #666666">10</span>]])
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<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">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>]) <span style="color: #408080; font-style: italic"># Labels must be -1 or 1</span>
<span style="color: #408080; font-style: italic"># Train AdaBoost</span>
ada <span style="color: #666666">=</span> AdaBoost()
ada<span style="color: #666666">.</span>fit(X, y, n_estimators<span style="color: #666666">=10</span>)
<span style="color: #408080; font-style: italic"># Predictions</span>
predictions <span style="color: #666666">=</span> ada<span style="color: #666666">.</span>predict(X)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Predictions:&quot;</span>, predictions)
</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="gradient-boosting-basics-with-steepest-descent-functional-gradient-descent">Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent </h2>
<p>Gradient boosting is again a similar technique to Adaptive boosting,
it combines so-called weak classifiers or regressors into a strong
method via a series of iterations.
</p>
<p>In order to understand the method, let us illustrate its basics by
bringing back the essential steps in linear regression, where our cost
function was the least squares function.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-squared-error-again-steepest-descent">The Squared-Error again! Steepest Descent </h2>
<p>We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize
This means that for every iteration, we need to optimize
</p>
$$
(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
<p>We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as</p>
$$
f_M(x) = \sum_{m=0}^M h_m(x).
$$
<p>In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as</p>
$$
g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}.
$$
<p>With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that
the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \).
</p>
<p>Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have</p>
$$
(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="steepest-descent-example">Steepest Descent Example </h2>
<p>Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that</p>
$$
f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i.
$$
<p>We can then proceed and compute</p>
$$
g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,
$$
<p>and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called <b>gradient boosting</b>. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="gradient-boosting-algorithm">Gradient Boosting, algorithm </h2>
<p>Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
so we do not learn a function that can generalize. However, we can modify the algorithm by
fitting a weak learner to approximate the negative gradient signal.
</p>
<p>Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function</p>
$$
C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
$$
<p>The way we proceed in an iterative fashion is to</p>
<ol>
<li> Initialize our estimate \( f_0(x) \).</li>
<li> For \( m=1:M \), we
<ol type="a"></li>
<li> compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);</li>
<li> fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);</li>
<li> update the estimate \( f_m(x) = f_{m-1}(x)+h_m(u_m,x) \);</li>
</ol>
<li> The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="gradient-boosting-examples-of-regression">Gradient Boosting, Examples of 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">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.ensemble</span> <span style="color: #008000; font-weight: bold">import</span> GradientBoostingRegressor
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scikitplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skplt</span>
<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> mean_squared_error
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
maxdegree <span style="color: #666666">=</span> <span style="color: #666666">6</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(maxdegree)
bias <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdegree)
variance <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdegree)
polydegree <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(maxdegree)
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">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,maxdegree):
model <span style="color: #666666">=</span> GradientBoostingRegressor(max_depth<span style="color: #666666">=</span>degree, n_estimators<span style="color: #666666">=100</span>, learning_rate<span style="color: #666666">=1.0</span>)
model<span style="color: #666666">.</span>fit(X_train,y_train)
y_pred <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X_test)
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>) )
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))<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) )
<span style="color: #008000">print</span>(<span style="color: #BA2121">&#39;Max depth:&#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]))
plt<span style="color: #666666">.</span>xlim(<span style="color: #666666">1</span>,maxdegree<span style="color: #666666">-1</span>)
plt<span style="color: #666666">.</span>plot(polydegree, error, label<span style="color: #666666">=</span><span style="color: #BA2121">&#39;Error&#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()
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="gradient-boosting-classification-example">Gradient Boosting, Classification Example </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">import</span> <span style="color: #0000FF; font-weight: bold">scikitplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skplt</span>
<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> GradientBoostingClassifier
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> cross_validate
<span style="color: #408080; font-style: italic"># 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">#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)
gd_clf <span style="color: #666666">=</span> GradientBoostingClassifier(max_depth<span style="color: #666666">=3</span>, n_estimators<span style="color: #666666">=100</span>, learning_rate<span style="color: #666666">=1.0</span>)
gd_clf<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
<span style="color: #408080; font-style: italic">#Cross validation</span>
accuracy <span style="color: #666666">=</span> cross_validate(gd_clf,X_test_scaled,y_test,cv<span style="color: #666666">=10</span>)[<span style="color: #BA2121">&#39;test_score&#39;</span>]
<span style="color: #008000">print</span>(accuracy)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Gradient boosting 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(gd_clf<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scikitplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skplt</span>
y_pred <span style="color: #666666">=</span> gd_clf<span style="color: #666666">.</span>predict(X_test_scaled)
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_confusion_matrix(y_test, y_pred, normalize<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
plt<span style="color: #666666">.</span>show()
y_probas <span style="color: #666666">=</span> gd_clf<span style="color: #666666">.</span>predict_proba(X_test_scaled)
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_roc(y_test, y_probas)
plt<span style="color: #666666">.</span>show()
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_cumulative_gain(y_test, y_probas)
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="xgboost-extreme-gradient-boosting">XGBoost: Extreme Gradient Boosting </h2>
<p><a href="https://github.com/dmlc/xgboost" target="_blank">XGBoost</a> or Extreme Gradient
Boosting, is an optimized distributed gradient boosting library
designed to be highly efficient, flexible and portable. It implements
machine learning algorithms under the Gradient Boosting
framework. XGBoost provides a parallel tree boosting that solve many
data science problems in a fast and accurate way. See the <a href="https://arxiv.org/abs/1603.02754" target="_blank">article by Chen and Guestrin</a>.
</p>
<p>The authors design and build a highly scalable end-to-end tree
boosting system. It has a theoretically justified weighted quantile
sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.
</p>
<p>It is now the algorithm which wins essentially all ML competitions!!!</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="xgboost-on-the-cancer-data">Xgboost on the Cancer Data </h2>
<p>As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. </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.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.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> LabelEncoder
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> cross_validate
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scikitplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skplt</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">xgboost</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">xgb</span>
<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">#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)
xg_clf <span style="color: #666666">=</span> xgb<span style="color: #666666">.</span>XGBClassifier()
xg_clf<span style="color: #666666">.</span>fit(X_train_scaled,y_train)
y_test <span style="color: #666666">=</span> xg_clf<span style="color: #666666">.</span>predict(X_test_scaled)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test set accuracy with Gradient Boosting 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(xg_clf<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scikitplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skplt</span>
y_pred <span style="color: #666666">=</span> xg_clf<span style="color: #666666">.</span>predict(X_test_scaled)
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_confusion_matrix(y_test, y_pred, normalize<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
plt<span style="color: #666666">.</span>show()
y_probas <span style="color: #666666">=</span> xg_clf<span style="color: #666666">.</span>predict_proba(X_test_scaled)
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_roc(y_test, y_probas)
plt<span style="color: #666666">.</span>show()
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_cumulative_gain(y_test, y_probas)
plt<span style="color: #666666">.</span>show()
xgb<span style="color: #666666">.</span>plot_tree(xg_clf,num_trees<span style="color: #666666">=0</span>)
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;figure.figsize&#39;</span>] <span style="color: #666666">=</span> [<span style="color: #666666">50</span>, <span style="color: #666666">10</span>]
plt<span style="color: #666666">.</span>show()
xgb<span style="color: #666666">.</span>plot_importance(xg_clf)
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;figure.figsize&#39;</span>] <span style="color: #666666">=</span> [<span style="color: #666666">5</span>, <span style="color: #666666">5</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="gradient-boosting-making-our-own-code-for-a-regression-case">Gradient boosting, making our own code for a regression case </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">class</span> <span style="color: #0000FF; font-weight: bold">DecisionTreeRegressor</span>:
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, max_depth<span style="color: #666666">=3</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>max_depth <span style="color: #666666">=</span> max_depth
<span style="color: #008000">self</span><span style="color: #666666">.</span>tree <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">fit</span>(<span style="color: #008000">self</span>, X, y):
<span style="color: #008000">self</span><span style="color: #666666">.</span>tree <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_grow_tree(X, y)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_grow_tree</span>(<span style="color: #008000">self</span>, X, y, depth<span style="color: #666666">=0</span>):
n_samples, n_features <span style="color: #666666">=</span> X<span style="color: #666666">.</span>shape
<span style="color: #008000; font-weight: bold">if</span> depth <span style="color: #666666">&lt;</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>max_depth:
best_feature, best_threshold <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_best_split(X, y)
<span style="color: #008000; font-weight: bold">if</span> best_feature <span style="color: #AA22FF; font-weight: bold">is</span> <span style="color: #AA22FF; font-weight: bold">not</span> <span style="color: #008000; font-weight: bold">None</span>:
left_indices <span style="color: #666666">=</span> X[:, best_feature] <span style="color: #666666">&lt;</span> best_threshold
right_indices <span style="color: #666666">=</span> X[:, best_feature] <span style="color: #666666">&gt;=</span> best_threshold
left_child <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_grow_tree(X[left_indices], y[left_indices], depth <span style="color: #666666">+</span> <span style="color: #666666">1</span>)
right_child <span style="color: #666666">=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_grow_tree(X[right_indices], y[right_indices], depth <span style="color: #666666">+</span> <span style="color: #666666">1</span>)
<span style="color: #008000; font-weight: bold">return</span> (best_feature, best_threshold, left_child, right_child)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>mean(y)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_best_split</span>(<span style="color: #008000">self</span>, X, y):
best_mse <span style="color: #666666">=</span> <span style="color: #008000">float</span>(<span style="color: #BA2121">&#39;inf&#39;</span>)
best_feature, best_threshold <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">None</span>, <span style="color: #008000; font-weight: bold">None</span>
n_samples, n_features <span style="color: #666666">=</span> X<span style="color: #666666">.</span>shape
<span style="color: #008000; font-weight: bold">for</span> feature <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(n_features):
thresholds <span style="color: #666666">=</span> np<span style="color: #666666">.</span>unique(X[:, feature])
<span style="color: #008000; font-weight: bold">for</span> threshold <span style="color: #AA22FF; font-weight: bold">in</span> thresholds:
left_indices <span style="color: #666666">=</span> X[:, feature] <span style="color: #666666">&lt;</span> threshold
right_indices <span style="color: #666666">=</span> X[:, feature] <span style="color: #666666">&gt;=</span> threshold
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">len</span>(y[left_indices]) <span style="color: #666666">&gt;</span> <span style="color: #666666">0</span> <span style="color: #AA22FF; font-weight: bold">and</span> <span style="color: #008000">len</span>(y[right_indices]) <span style="color: #666666">&gt;</span> <span style="color: #666666">0</span>:
left_mse <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean((y[left_indices] <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y[left_indices])) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
right_mse <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean((y[right_indices] <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y[right_indices])) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
mse <span style="color: #666666">=</span> (<span style="color: #008000">len</span>(y[left_indices]) <span style="color: #666666">*</span> left_mse <span style="color: #666666">+</span> <span style="color: #008000">len</span>(y[right_indices]) <span style="color: #666666">*</span> right_mse) <span style="color: #666666">/</span> n_samples
<span style="color: #008000; font-weight: bold">if</span> mse <span style="color: #666666">&lt;</span> best_mse:
best_mse <span style="color: #666666">=</span> mse
best_feature <span style="color: #666666">=</span> feature
best_threshold <span style="color: #666666">=</span> threshold
<span style="color: #008000; font-weight: bold">return</span> best_feature, best_threshold
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">predict</span>(<span style="color: #008000">self</span>, X):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>array([<span style="color: #008000">self</span><span style="color: #666666">.</span>_predict_sample(sample, <span style="color: #008000">self</span><span style="color: #666666">.</span>tree) <span style="color: #008000; font-weight: bold">for</span> sample <span style="color: #AA22FF; font-weight: bold">in</span> X])
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">_predict_sample</span>(<span style="color: #008000">self</span>, sample, node):
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">isinstance</span>(node, <span style="color: #008000">tuple</span>):
feature, threshold, left_child, right_child <span style="color: #666666">=</span> node
<span style="color: #008000; font-weight: bold">if</span> sample[feature] <span style="color: #666666">&lt;</span> threshold:
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_predict_sample(sample, left_child)
<span style="color: #008000; font-weight: bold">else</span>:
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>_predict_sample(sample, right_child)
<span style="color: #008000; font-weight: bold">return</span> node
<span style="color: #008000; font-weight: bold">class</span> <span style="color: #0000FF; font-weight: bold">GradientBoostingRegressor</span>:
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">__init__</span>(<span style="color: #008000">self</span>, n_estimators<span style="color: #666666">=100</span>, learning_rate<span style="color: #666666">=0.1</span>, max_depth<span style="color: #666666">=3</span>):
<span style="color: #008000">self</span><span style="color: #666666">.</span>n_estimators <span style="color: #666666">=</span> n_estimators
<span style="color: #008000">self</span><span style="color: #666666">.</span>learning_rate <span style="color: #666666">=</span> learning_rate
<span style="color: #008000">self</span><span style="color: #666666">.</span>max_depth <span style="color: #666666">=</span> max_depth
<span style="color: #008000">self</span><span style="color: #666666">.</span>models <span style="color: #666666">=</span> []
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">fit</span>(<span style="color: #008000">self</span>, X, y):
y_pred <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(y<span style="color: #666666">.</span>shape)
<span style="color: #008000; font-weight: bold">for</span> _ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #008000">self</span><span style="color: #666666">.</span>n_estimators):
residuals <span style="color: #666666">=</span> y <span style="color: #666666">-</span> y_pred
model <span style="color: #666666">=</span> DecisionTreeRegressor(max_depth<span style="color: #666666">=</span><span style="color: #008000">self</span><span style="color: #666666">.</span>max_depth)
model<span style="color: #666666">.</span>fit(X, residuals)
y_pred <span style="color: #666666">+=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>learning_rate <span style="color: #666666">*</span> model<span style="color: #666666">.</span>predict(X)
<span style="color: #008000">self</span><span style="color: #666666">.</span>models<span style="color: #666666">.</span>append(model)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">predict</span>(<span style="color: #008000">self</span>, X):
y_pred <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(X<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>])
<span style="color: #008000; font-weight: bold">for</span> model <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>models:
y_pred <span style="color: #666666">+=</span> <span style="color: #008000">self</span><span style="color: #666666">.</span>learning_rate <span style="color: #666666">*</span> model<span style="color: #666666">.</span>predict(X)
<span style="color: #008000; font-weight: bold">return</span> y_pred
<span style="color: #408080; font-style: italic"># Example usage</span>
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">&quot;__main__&quot;</span>:
<span style="color: #408080; font-style: italic"># Sample data</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([[<span style="color: #666666">1</span>], [<span style="color: #666666">2</span>], [<span style="color: #666666">3</span>], [<span style="color: #666666">4</span>], [<span style="color: #666666">5</span>]])
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">1.5</span>, <span style="color: #666666">1.7</span>, <span style="color: #666666">3.5</span>, <span style="color: #666666">3.7</span>, <span style="color: #666666">5.0</span>])
model <span style="color: #666666">=</span> GradientBoostingRegressor(n_estimators<span style="color: #666666">=100</span>, learning_rate<span style="color: #666666">=0.1</span>, max_depth<span style="color: #666666">=2</span>)
model<span style="color: #666666">.</span>fit(X, y)
predictions <span style="color: #666666">=</span> model<span style="color: #666666">.</span>predict(X)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Predictions:&quot;</span>, predictions)
</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="summary-of-course">Summary of course </h2>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="what-me-worry-no-final-exam-in-this-course">What? Me worry? No final exam in this course! </h2>
<br/><br/>
<center>
<p><img src="figures/exam1.jpeg" width="500" align="bottom"></p>
</center>
<br/><br/>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="topics-we-have-covered-this-year">Topics we have covered this year </h2>
<p>The course has two central parts</p>
<ol>
<li> Statistical analysis and optimization of data</li>
<li> Machine learning</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="statistical-analysis-and-optimization-of-data">Statistical analysis and optimization of data </h2>
<p>The following topics have been discussed:</p>
<ol>
<li> Basic concepts, expectation values, variance, covariance, correlation functions and errors;</li>
<li> Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;</li>
<li> Central elements from linear algebra, matrix inversion and SVD</li>
<li> Gradient methods for data optimization</li>
<li> Estimation of errors using cross-validation, bootstrapping and jackknife methods;</li>
<li> Practical optimization using Singular-value decomposition and least squares for parameterizing data.</li>
<li> Not discussed: Principal Component Analysis to reduce the number of features.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="machine-learning">Machine learning </h2>
<ul>
<li> Linear methods for regression and classification:
<ol type="a"></li>
<li> Ordinary Least Squares</li>
<li> Ridge regression</li>
<li> Lasso regression</li>
<li> Logistic regression</li>
</ol>
<li> Neural networks and deep learning:
<ol type="a"></li>
<li> Feed Forward Neural Networks</li>
<li> Convolutional Neural Networks</li>
<li> Recurrent Neural Networks</li>
</ol>
<li> Decisions trees and ensemble methods:
<ol type="a"></li>
<li> Decision trees</li>
<li> Bagging and voting</li>
<li> Random forests</li>
<li> Boosting and gradient boosting</li>
</ol>
<li> Not discussed this year: Support vector machines
<ol type="a"></li>
<li> Binary classification and multiclass classification</li>
<li> Kernel methods</li>
<li> Regression</li>
</ol>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="learning-outcomes-and-overarching-aims-of-this-course">Learning outcomes and overarching aims of this course </h2>
<p>The course introduces a variety of central algorithms and methods
essential for studies of data analysis and machine learning. The
course is project based and through the various projects, normally
three, you will be exposed to fundamental research problems
in these fields, with the aim to reproduce state of the art scientific
results. The students will learn to develop and structure large codes
for studying these systems, get acquainted with computing facilities
and learn to handle large scientific projects. A good scientific and
ethical conduct is emphasized throughout the course.
</p>
<ul>
<li> Understand linear methods for regression and classification;</li>
<li> Learn about neural network;</li>
<li> Learn about bagging, boosting and trees
<!-- * Support vector machines --></li>
<li> Learn about basic data analysis;</li>
<li> Be capable of extending the acquired knowledge to other systems and cases;</li>
<li> Have an understanding of central algorithms used in data analysis and machine learning;</li>
<li> Work on numerical projects to illustrate the theory. The projects play a central role.</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="perspective-on-machine-learning">Perspective on Machine Learning </h2>
<ol>
<li> Rapidly emerging application area</li>
<li> Experiment AND theory are evolving in many many fields.</li>
<li> Requires education/retraining for more widespread adoption</li>
<li> A lot of &#8220;word-of-mouth&#8221; development methods</li>
</ol>
<p>Huge amounts of data sets require automation, classical analysis tools often inadequate.
High energy physics hit this wall in the 90&#8217;s.
In 2009 single top quark production was determined via <a href="https://arxiv.org/pdf/0903.0850.pdf" target="_blank">Boosted decision trees, Bayesian
Neural Networks, etc.</a>
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="machine-learning-research">Machine Learning Research </h2>
<p>Where to find recent results:</p>
<ol>
<li> Conference proceedings, arXiv and blog posts!</li>
<li> <b>NIPS</b>: <a href="https://papers.nips.cc" target="_blank">Neural Information Processing Systems</a></li>
<li> <b>ICLR</b>: <a href="https://openreview.net/group?id=ICLR.cc/2018/Conference#accepted-oral-papers" target="_blank">International Conference on Learning Representations</a></li>
<li> <b>ICML</b>: International Conference on Machine Learning</li>
<li> <a href="http://www.jmlr.org/papers/v19/" target="_blank">Journal of Machine Learning Research</a></li>
<li> <a href="https://arxiv.org/list/cs.LG/recent" target="_blank">Follow ML on ArXiv</a></li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="starting-your-machine-learning-project">Starting your Machine Learning Project </h2>
<ol>
<li> Identify problem type: classification, regression</li>
<li> Consider your data carefully</li>
<li> Choose a simple model that fits 1 and 2</li>
<li> Consider your data carefully again! Think of data representation more carefully.</li>
<li> Based on your results, feedback loop to earliest possible point</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="choose-a-model-and-algorithm">Choose a Model and Algorithm </h2>
<ul>
<li> Supervised?</li>
<li> Start with the simplest model that fits your problem</li>
<li> Start with minimal processing of data</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="preparing-your-data">Preparing Your Data </h2>
<ul>
<li> Shuffle your data</li>
<li> Mean center your data</li>
<ul>
<li> Why?</li>
</ul>
<li> Normalize the variance</li>
<ul>
<li> Why?</li>
</ul>
<li> <b>Whitening</b></li>
<ul>
<li> Decorrelates data</li>
<li> Can be hit or miss</li>
</ul>
<li> When to do train/test split?</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="which-activation-and-weights-to-choose-in-neural-networks">Which activation and weights to choose in neural networks </h2>
<ul>
<li> RELU? ELU? GELU? etc</li>
<li> Sigmoid or Tanh?</li>
<li> Set all weights to 0? Terrible idea</li>
<li> Set all weights to random values? Small random values</li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="optimization-methods-and-hyperparameters">Optimization Methods and Hyperparameters </h2>
<ul>
<li> Stochastic gradient descent</li>
<ul>
<li> Stochastic gradient descent + momentum</li>
</ul>
<li> State-of-the-art approaches:
<ol type="a"></li>
<li> RMSProp</li>
<li> Adam</li>
<li> and more</li>
</ol>
</ul>
<p>Which regularization and hyperparameters? \( L_1 \) or \( L_2 \), soft
classifiers, depths of trees and many other. Need to explore a large
set of hyperparameters and regularization methods.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="resampling">Resampling </h2>
<p>When do we resample?</p>
<ol>
<li> <a href="https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A" target="_blank">Bootstrap</a></li>
<li> <a href="https://www.youtube.com/watch?v=fSytzGwwBVw&ab_channel=StatQuestwithJoshStarmer" target="_blank">Cross-validation</a></li>
<li> Jackknife and many other</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="other-courses-on-data-science-and-machine-learning-at-uio">Other courses on Data science and Machine Learning at UiO </h2>
<ol>
<li> <a href="https://www.uio.no/studier/emner/matnat/fys/FYS5429/index-eng.html" target="_blank">FYS5429 &#8211; Advanced machine learning and data analysis for the physical sciences</a></li>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN3050/index-eng.html" target="_blank">IN3050/IN4050 Introduction to Artificial Intelligence and Machine Learning</a>. Introductory course in machine learning and AI</li>
<li> <a href="http://www.uio.no/studier/emner/matnat/math/STK-INF3000/index-eng.html" target="_blank">STK-INF3000/4000 Selected Topics in Data Science</a>. The course provides insight into selected contemporary relevant topics within Data Science.</li>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN4080/index.html" target="_blank">IN4080 Natural Language Processing</a>. Probabilistic and machine learning techniques applied to natural language processing.</li>
<li> <a href="https://www.uio.no/studier/emner/matnat/math/STK-IN4300/index-eng.html" target="_blank">STK-IN4300 &#8211; Statistical learning methods in Data Science</a>. An advanced introduction to statistical and machine learning. For students with a good mathematics and statistics background.</li>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN-STK5000/index-eng.html" target="_blank">IN-STK5000 Responsible Data Science</a>. Methods for adaptive collection and processing of data based on machine learning techniques.</li>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN4310/index.html" target="_blank">IN4310 &#8211; Machine Learning for Image Analysis</a>. An introduction to deep learning with particular emphasis on applications within Image analysis, but useful for other application areas too.</li>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5310/index.html" target="_blank">IN5310 &#8211; Advanced Deep Learning for Image Analysis</a></li>
<li> <a href="https://www.uio.no/studier/emner/matnat/ifi/IN5490/index.html" target="_blank">IN5490 &#8211; Advanced Topics in Artificial Intelligence for Intelligent Systems</a></li>
<li> <a href="https://www.uio.no/studier/emner/matnat/its/TEK5040/" target="_blank">TEK5040 &#8211; Deep learning for autonomous systems</a>. The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="additional-courses-of-interest">Additional courses of interest </h2>
<ol>
<li> <a href="https://www.uio.no/studier/emner/matnat/math/STK4051/index-eng.html" target="_blank">STK4051 Computational Statistics</a></li>
<li> <a href="https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html" target="_blank">STK4021 Applied Bayesian Analysis and Numerical Methods</a></li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="what-s-the-future-like">What's the future like? </h2>
<p>Based on multi-layer nonlinear neural networks, deep learning can
learn directly from raw data, automatically extract and abstract
features from layer to layer, and then achieve the goal of regression,
classification, or ranking. Deep learning has made breakthroughs in
computer vision, speech processing and natural language, and reached
or even surpassed human level. The success of deep learning is mainly
due to the three factors: big data, big model, and big computing.
</p>
<p>In the past few decades, many different architectures of deep neural
networks have been proposed, such as
</p>
<ol>
<li> Convolutional neural networks, which are mostly used in image and video data processing, and have also been applied to sequential data such as text processing;</li>
<li> Recurrent neural networks, which can process sequential data of variable length and have been widely used in natural language understanding and speech processing;</li>
<li> Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning.</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="types-of-machine-learning-a-repetition">Types of Machine Learning, a repetition </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>The approaches to machine learning are many, but are often split into two main categories.
In <em>supervised learning</em> we know the answer to a problem,
and let the computer deduce the logic behind it. On the other hand, <em>unsupervised learning</em>
is a method for finding patterns and relationship in data sets without any prior knowledge of the system.
Some authours also operate with a third category, namely <em>reinforcement learning</em>. This is a paradigm
of learning inspired by behavioural psychology, where learning is achieved by trial-and-error,
solely from rewards and punishment.
</p>
<p>Another way to categorize machine learning tasks is to consider the desired output of a system.
Some of the most common tasks are:
</p>
<ul>
<li> Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.</li>
<li> Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.</li>
<li> Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.</li>
<li> Other unsupervised learning algortihms like <b>Boltzmann machines</b></li>
</ul>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="why-boltzmann-machines">Why Boltzmann machines? </h2>
<p>What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately.
One of the major reasons is that they can be stacked layer-wise to build deep neural networks that capture complicated statistics.
</p>
<p>The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images. </p>
<p>Furthermore, they have been used to solve complicated <a href="https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002" target="_blank">quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models</a>. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="boltzmann-machines">Boltzmann Machines </h2>
<p>Why use a generative model rather than the more well known discriminative deep neural networks (DNN)? </p>
<ul>
<li> Discriminitave methods have several limitations: They are mainly supervised learning methods, thus requiring labeled data. And there are tasks they cannot accomplish, like drawing new examples from an unknown probability distribution.</li>
<li> A generative model can learn to represent and sample from a probability distribution. The core idea is to learn a parametric model of the probability distribution from which the training data was drawn. As an example
<ol type="a"></li>
<li> A model for images could learn to draw new examples of cats and dogs, given a training dataset of images of cats and dogs.</li>
<li> Generate a sample of an ordered or disordered phase, having been given samples of such phases.</li>
<li> Model the trial function for <a href="https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002" target="_blank">Monte Carlo calculations</a>.</li>
</ol>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="some-similarities-and-differences-from-dnns">Some similarities and differences from DNNs </h2>
<ol>
<li> Both use gradient-descent based learning procedures for minimizing cost functions</li>
<li> Energy based models don't use backpropagation and automatic differentiation for computing gradients, instead turning to Markov Chain Monte Carlo methods.</li>
<li> DNNs often have several hidden layers. A restricted Boltzmann machine has only one hidden layer, however several RBMs can be stacked to make up Deep Belief Networks, of which they constitute the building blocks.</li>
</ol>
<p>History: The RBM was developed by amongst others <a href="https://en.wikipedia.org/wiki/Geoffrey_Hinton" target="_blank">Geoffrey Hinton</a>, called by some the "Godfather of Deep Learning", working with the University of Toronto and Google.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="boltzmann-machines-bm">Boltzmann machines (BM) </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>A BM is what we would call an undirected probabilistic graphical model
with stochastic continuous or discrete units.
</p>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>It is interpreted as a stochastic recurrent neural network where the
state of each unit(neurons/nodes) depends on the units it is connected
to. The weights in the network represent thus the strength of the
interaction between various units/nodes.
</p>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>It turns into a Hopfield network if we choose deterministic rather
than stochastic units. In contrast to a Hopfield network, a BM is a
so-called generative model. It allows us to generate new samples from
the learned distribution.
</p>
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-standard-bm-setup">A standard BM setup </h2>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>A standard BM network is divided into a set of observable and visible units \( \hat{x} \) and a set of unknown hidden units/nodes \( \hat{h} \).</p>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to \( 1 \).</p>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b></b>
<p>
<p>BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning</p>
</div>
<p>However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS.
Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-structure-of-the-rbm-network">The structure of the RBM network </h2>
<br/><br/>
<center>
<p><img src="figures/RBM.png" width="800" align="bottom"></p>
</center>
<br/><br/>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-network">The network </h2>
<b>The network layers</b>:
<ol>
<li> A function \( \mathbf{x} \) that represents the visible layer, a vector of \( M \) elements (nodes). This layer represents both what the RBM might be given as training input, and what we want it to be able to reconstruct. This might for example be given by the pixels of an image or coefficients representing speech, or the coordinates of a quantum mechanical state function.</li>
<li> The function \( \mathbf{h} \) represents the hidden, or latent, layer. A vector of \( N \) elements (nodes). Also called "feature detectors".</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="goals">Goals </h2>
<p>The goal of the hidden layer is to increase the model's expressive
power. We encode complex interactions between visible variables by
introducing additional, hidden variables that interact with visible
degrees of freedom in a simple manner, yet still reproduce the complex
correlations between visible degrees in the data once marginalized
over (integrated out).
</p>
<b>The network parameters, to be optimized/learned</b>:
<ol>
<li> \( \mathbf{a} \) represents the visible bias, a vector of same length as \( \mathbf{x} \).</li>
<li> \( \mathbf{b} \) represents the hidden bias, a vector of same lenght as \( \mathbf{h} \).</li>
<li> \( W \) represents the interaction weights, a matrix of size \( M\times N \).</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="joint-distribution">Joint distribution </h2>
<p>The restricted Boltzmann machine is described by a Boltzmann distribution</p>
$$
\begin{align}
P_{rbm}(\mathbf{x},\mathbf{h}) = \frac{1}{Z} e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})},
\label{_auto1}
\end{align}
$$
<p>where \( Z \) is the normalization constant or partition function, defined as </p>
$$
\begin{align}
Z = \int \int e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})} d\mathbf{x} d\mathbf{h}.
\label{_auto2}
\end{align}
$$
<p>It is common to ignore \( T_0 \) by setting it to one. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="network-elements-the-energy-function">Network Elements, the energy function </h2>
<p>The function \( E(\mathbf{x},\mathbf{h}) \) gives the <b>energy</b> of a
configuration (pair of vectors) \( (\mathbf{x}, \mathbf{h}) \). The lower
the energy of a configuration, the higher the probability of it. This
function also depends on the parameters \( \mathbf{a} \), \( \mathbf{b} \) and
\( W \). Thus, when we adjust them during the learning procedure, we are
adjusting the energy function to best fit our problem.
</p>
<p>An expression for the energy function is</p>
$$
E(\hat{x},\hat{h}) = -\sum_{ia}^{NA}b_i^a \alpha_i^a(x_i)-\sum_{jd}^{MD}c_j^d \beta_j^d(h_j)-\sum_{ijad}^{NAMD}b_i^a \alpha_i^a(x_i)c_j^d \beta_j^d(h_j)w_{ij}^{ad}.
$$
<p>Here \( \beta_j^d(h_j) \) and \( \alpha_i^a(x_j) \) are so-called transfer functions that map a given input value to a desired feature value. The labels \( a \) and \( d \) denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. <b>Note</b> that there is no connection between nodes in a layer.</p>
<p>The quantities \( b \) and \( c \) can be interpreted as the visible and hidden biases, respectively.</p>
<p>The connection between the nodes in the two layers is given by the weights \( w_{ij} \). </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="defining-different-types-of-rbms">Defining different types of RBMs </h2>
<p>There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function \( E(\mathbf{x},\mathbf{h}) \). </p>
<div class="alert alert-block alert-block alert-text-normal">
<b>Binary-Binary RBM:</b>
<p>
<p>RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows:</p>
$$
\begin{align}
E(\mathbf{x}, \mathbf{h}) = - \sum_i^M x_i a_i- \sum_j^N b_j h_j - \sum_{i,j}^{M,N} x_i w_{ij} h_j,
\label{_auto3}
\end{align}
$$
<p>where the binary values taken on by the nodes are most commonly 0 and 1.</p>
</div>
<div class="alert alert-block alert-block alert-text-normal">
<b>Gaussian-Binary RBM:</b>
<p>
<p>Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary:</p>
$$
\begin{align}
E(\mathbf{x}, \mathbf{h}) = \sum_i^M \frac{(x_i - a_i)^2}{2\sigma_i^2} - \sum_j^N b_j h_j - \sum_{i,j}^{M,N} \frac{x_i w_{ij} h_j}{\sigma_i^2}.
\label{_auto4}
\end{align}
$$
</div>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="more-about-rbms">More about RBMs </h2>
<ol>
<li> Useful when we model continuous data (i.e., we wish \( \mathbf{x} \) to be continuous)</li>
<li> Requires a smaller learning rate, since there's no upper bound to the value a component might take in the reconstruction</li>
</ol>
<p>Other types of units include:</p>
<ol>
<li> Softmax and multinomial units</li>
<li> Gaussian visible and hidden units</li>
<li> Binomial units</li>
<li> Rectified linear units</li>
</ol>
<p>To read more, see <a href="https://github.com/CompPhysics/ComputationalPhysics2/blob/gh-pages/doc/pub/notebook2/ipynb/notebook2.ipynb" target="_blank">Lectures on Boltzmann machines in Physics</a>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="autoencoders-overarching-view">Autoencoders: Overarching view </h2>
<p>Autoencoders are artificial neural networks capable of learning
efficient representations of the input data (these representations are called codings) without
any supervision (i.e., the training set is unlabeled). These codings
typically have a much lower dimensionality than the input data, making
autoencoders useful for dimensionality reduction.
</p>
<p>More importantly, autoencoders act as powerful feature detectors, and
they can be used for unsupervised pretraining of deep neural networks.
</p>
<p>Lastly, they are capable of randomly generating new data that looks
very similar to the training data; this is called a generative
model. For example, you could train an autoencoder on pictures of
faces, and it would then be able to generate new faces. Surprisingly,
autoencoders work by simply learning to copy their inputs to their
outputs. This may sound like a trivial task, but we will see that
constraining the network in various ways can make it rather
difficult. For example, you can limit the size of the internal
representation, or you can add noise to the inputs and train the
network to recover the original inputs. These constraints prevent the
autoencoder from trivially copying the inputs directly to the outputs,
which forces it to learn efficient ways of representing the data. In
short, the codings are byproducts of the autoencoder&#8217;s attempt to
learn the identity function under some constraints.
</p>
<a href="https://www.coursera.org/lecture/building-deep-learning-models-with-tensorflow/autoencoders-1U4L3" target="_blank">Video on autoencoders</a>
<p>See also A. Geron's textbook, chapter 15.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="bayesian-machine-learning">Bayesian Machine Learning </h2>
<p>This is an important topic if we aim at extracting a probability
distribution. This gives us also a confidence interval and error
estimates.
</p>
<p>Bayesian machine learning allows us to encode our prior beliefs about
what those models should look like, independent of what the data tells
us. This is especially useful when we don&#8217;t have a ton of data to
confidently learn our model.
</p>
<a href="https://www.youtube.com/watch?v=E1qhGw8QxqY&ab_channel=AndrewGordonWilson" target="_blank">Video on Bayesian deep learning</a>
<p>See also the <a href="https://github.com/CompPhysics/MachineLearning/blob/master/doc/Articles/lec03.pdf" target="_blank">slides here</a>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="reinforcement-learning">Reinforcement Learning </h2>
<p>Reinforcement Learning (RL) is one of the most exciting fields of
Machine Learning today, and also one of the oldest. It has been around
since the 1950s, producing many interesting applications over the
years.
</p>
<p>It studies
how agents take actions based on trial and error, so as to maximize
some notion of cumulative reward in a dynamic system or
environment. Due to its generality, the problem has also been studied
in many other disciplines, such as game theory, control theory,
operations research, information theory, multi-agent systems, swarm
intelligence, statistics, and genetic algorithms.
</p>
<p>In March 2016, AlphaGo, a computer program that plays the board game
Go, beat Lee Sedol in a five-game match. This was the first time a
computer Go program had beaten a 9-dan (highest rank) professional
without handicaps. AlphaGo is based on deep convolutional neural
networks and reinforcement learning. AlphaGo&#8217;s victory was a major
milestone in artificial intelligence and it has also made
reinforcement learning a hot research area in the field of machine
learning.
</p>
<p><a href="https://www.youtube.com/watch?v=FgzM3zpZ55o&ab_channel=stanfordonline" target="_blank">Lecture on Reinforcement Learning</a>.</p>
<p>See also A. Geron's textbook, chapter 16.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="transfer-learning">Transfer learning </h2>
<p>The goal of transfer learning is to transfer the model or knowledge
obtained from a source task to the target task, in order to resolve
the issues of insufficient training data in the target task. The
rationality of doing so lies in that usually the source and target
tasks have inter-correlations, and therefore either the features,
samples, or models in the source task might provide useful information
for us to better solve the target task. Transfer learning is a hot
research topic in recent years, with many problems still waiting to be studied.
</p>
<p><a href="https://www.ias.edu/video/machinelearning/2020/0331-SamoryKpotufe" target="_blank">Lecture on transfer learning</a>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adversarial-learning">Adversarial learning </h2>
<p>The conventional deep generative model has a potential problem: the
model tends to generate extreme instances to maximize the
probabilistic likelihood, which will hurt its performance. Adversarial
learning utilizes the adversarial behaviors (e.g., generating
adversarial instances or training an adversarial model) to enhance the
robustness of the model and improve the quality of the generated
data. In recent years, one of the most promising unsupervised learning
technologies, generative adversarial networks (GAN), has already been
successfully applied to image, speech, and text.
</p>
<p><a href="https://www.youtube.com/watch?v=CIfsB_EYsVI&ab_channel=StanfordUniversitySchoolofEngineering" target="_blank">Lecture on adversial learning</a>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="dual-learning">Dual learning </h2>
<p>Dual learning is a new learning paradigm, the basic idea of which is
to use the primal-dual structure between machine learning tasks to
obtain effective feedback/regularization, and guide and strengthen the
learning process, thus reducing the requirement of large-scale labeled
data for deep learning. The idea of dual learning has been applied to
many problems in machine learning, including machine translation,
image style conversion, question answering and generation, image
classification and generation, text classification and generation,
image-to-text, and text-to-image.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="distributed-machine-learning">Distributed machine learning </h2>
<p>Distributed computation will speed up machine learning algorithms,
significantly improve their efficiency, and thus enlarge their
application. When distributed meets machine learning, more than just
implementing the machine learning algorithms in parallel is required.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="meta-learning">Meta learning </h2>
<p>Meta learning is an emerging research direction in machine
learning. Roughly speaking, meta learning concerns learning how to
learn, and focuses on the understanding and adaptation of the learning
itself, instead of just completing a specific learning task. That is,
a meta learner needs to be able to evaluate its own learning methods
and adjust its own learning methods according to specific learning
tasks.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-challenges-facing-machine-learning">The Challenges Facing Machine Learning </h2>
<p>While there has been much progress in machine learning, there are also challenges.</p>
<p>For example, the mainstream machine learning technologies are
black-box approaches, making us concerned about their potential
risks. To tackle this challenge, we may want to make machine learning
more explainable and controllable. As another example, the
computational complexity of machine learning algorithms is usually
very high and we may want to invent lightweight algorithms or
implementations. Furthermore, in many domains such as physics,
chemistry, biology, and social sciences, people usually seek elegantly
simple equations (e.g., the Schr&#246;dinger equation) to uncover the
underlying laws behind various phenomena. In the field of machine
learning, can we reveal simple laws instead of designing more complex
models for data fitting? Although there are many challenges, we are
still very optimistic about the future of machine learning. As we look
forward to the future, here are what we think the research hotspots in
the next ten years will be.
</p>
<p>See the article on <a href="https://www.frontiersin.org/articles/10.3389/frai.2020.00025/full" target="_blank">Discovery of Physics From Data: Universal Laws and Discrepancies</a></p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="explainable-machine-learning">Explainable machine learning </h2>
<p>Machine learning, especially deep learning, evolves rapidly. The
ability gap between machine and human on many complex cognitive tasks
becomes narrower and narrower. However, we are still in the very early
stage in terms of explaining why those effective models work and how
they work.
</p>
<p><b>What is missing: the gap between correlation and causation</b>. Standard Machine Learning is based on what e have called a frequentist approach. </p>
<p>Most
machine learning techniques, especially the statistical ones, depend
highly on correlations in data sets to make predictions and analyses. In
contrast, rational humans tend to reply on clear and trustworthy
causality relations obtained via logical reasoning on real and clear
facts. It is one of the core goals of explainable machine learning to
transition from solving problems by data correlation to solving
problems by logical reasoning.
</p>
<b>Bayesian Machine Learning is one of the exciting research directions in this field</b>.
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="quantum-machine-learning">Quantum machine learning </h2>
<p>Quantum machine learning is an emerging interdisciplinary research
area at the intersection of quantum computing and machine learning.
</p>
<p>Quantum computers use effects such as quantum coherence and quantum
entanglement to process information, which is fundamentally different
from classical computers. Quantum algorithms have surpassed the best
classical algorithms in several problems (e.g., searching for an
unsorted database, inverting a sparse matrix), which we call quantum
acceleration.
</p>
<p>When quantum computing meets machine learning, it can be a mutually
beneficial and reinforcing process, as it allows us to take advantage
of quantum computing to improve the performance of classical machine
learning algorithms. In addition, we can also use the machine learning
algorithms (on classic computers) to analyze and improve quantum
computing systems.
</p>
<p><a href="https://www.youtube.com/watch?v=Xh9pUu3-WxM&ab_channel=InstituteforPure%26AppliedMathematics%28IPAM%29" target="_blank">Lecture on Quantum ML</a>.</p>
<p><a href="https://physics.aps.org/articles/v13/179?utm_campaign=weekly&utm_medium=email&utm_source=emailalert" target="_blank">Read interview with Maria Schuld on her work on Quantum Machine Learning</a>. See also <a href="https://www.springer.com/gp/book/9783319964232" target="_blank">her recent textbook</a>. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="quantum-machine-learning-algorithms-based-on-linear-algebra">Quantum machine learning algorithms based on linear algebra </h2>
<p>Many quantum machine learning algorithms are based on variants of
quantum algorithms for solving linear equations, which can efficiently
solve N-variable linear equations with complexity of O(log2 N) under
certain conditions. The quantum matrix inversion algorithm can
accelerate many machine learning methods, such as least square linear
regression, least square version of support vector machine, Gaussian
process, and more. The training of these algorithms can be simplified
to solve linear equations. The key bottleneck of this type of quantum
machine learning algorithms is data input&#8212;that is, how to initialize
the quantum system with the entire data set. Although efficient
data-input algorithms exist for certain situations, how to efficiently
input data into a quantum system is as yet unknown for most cases.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="quantum-reinforcement-learning">Quantum reinforcement learning </h2>
<p>In quantum reinforcement learning, a quantum agent interacts with the
classical environment to obtain rewards from the environment, so as to
adjust and improve its behavioral strategies. In some cases, it
achieves quantum acceleration by the quantum processing capabilities
of the agent or the possibility of exploring the environment through
quantum superposition. Such algorithms have been proposed in
superconducting circuits and systems of trapped ions.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="quantum-deep-learning">Quantum deep learning </h2>
<p>Dedicated quantum information processors, such as quantum annealers
and programmable photonic circuits, are well suited for building deep
quantum networks. The simplest deep quantum network is the Boltzmann
machine. The classical Boltzmann machine consists of bits with tunable
interactions and is trained by adjusting the interaction of these bits
so that the distribution of its expression conforms to the statistics
of the data. To quantize the Boltzmann machine, the neural network can
simply be represented as a set of interacting quantum spins that
correspond to an adjustable Ising model. Then, by initializing the
input neurons in the Boltzmann machine to a fixed state and allowing
the system to heat up, we can read out the output qubits to get the
result.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="social-machine-learning">Social machine learning </h2>
<p>Machine learning aims to imitate how humans
learn. While we have developed successful machine learning algorithms,
until now we have ignored one important fact: humans are social. Each
of us is one part of the total society and it is difficult for us to
live, learn, and improve ourselves, alone and isolated. Therefore, we
should design machines with social properties. Can we let machines
evolve by imitating human society so as to achieve more effective,
intelligent, interpretable &#8220;social machine learning&#8221;?
</p>
<p>And much more.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-last-words">The last words? </h2>
<p>Early computer scientist Alan Kay said, <b>The best way to predict the
future is to create it</b>. Therefore, all machine learning
practitioners, whether scholars or engineers, professors or students,
need to work together to advance these important research
topics. Together, we will not just predict the future, but create it.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="best-wishes-to-you-all-and-thanks-so-much-for-your-heroic-efforts-this-semester">Best wishes to you all and thanks so much for your heroic efforts this semester </h2>
<br/><br/>
<center>
<p><img src="figures/Nebbdyr2.png" width="500" align="bottom"></p>
</center>
<br/><br/>
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>