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

2435 lines
136 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week47.do.txt --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=week47 --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 47: Support Vector Machines and Summary of Course">
<title>Week 47: Support Vector Machines 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 47', 2, None, 'overview-of-week-47'),
('Support Vector Machines, overarching aims',
2,
None,
'support-vector-machines-overarching-aims'),
('Hyperplanes and all that', 2, None, 'hyperplanes-and-all-that'),
('What is a hyperplane?', 2, None, 'what-is-a-hyperplane'),
('A $p$-dimensional space of features',
2,
None,
'a-p-dimensional-space-of-features'),
('The two-dimensional case', 2, None, 'the-two-dimensional-case'),
('Getting into the details', 2, None, 'getting-into-the-details'),
('First attempt at a minimization approach',
2,
None,
'first-attempt-at-a-minimization-approach'),
('Solving the equations', 2, None, 'solving-the-equations'),
('Problems with the Simpler Approach',
2,
None,
'problems-with-the-simpler-approach'),
('A better approach', 2, None, 'a-better-approach'),
('A quick Reminder on Lagrangian Multipliers',
2,
None,
'a-quick-reminder-on-lagrangian-multipliers'),
('Adding the Multiplier', 2, None, 'adding-the-multiplier'),
('Setting up the Problem', 2, None, 'setting-up-the-problem'),
('The problem to solve', 2, None, 'the-problem-to-solve'),
('The last steps', 2, None, 'the-last-steps'),
('A soft classifier', 2, None, 'a-soft-classifier'),
('Soft optmization problem', 2, None, 'soft-optmization-problem'),
('Kernels and non-linearity',
2,
None,
'kernels-and-non-linearity'),
('The equations', 2, None, 'the-equations'),
('The problem to solve', 2, None, 'the-problem-to-solve'),
("Different kernels and Mercer's theorem",
2,
None,
'different-kernels-and-mercer-s-theorem'),
('The moons example', 2, None, 'the-moons-example'),
('Mathematical optimization of convex functions',
2,
None,
'mathematical-optimization-of-convex-functions'),
('How do we solve these problems?',
2,
None,
'how-do-we-solve-these-problems'),
('A simple example', 2, None, 'a-simple-example'),
('Support Vector Machines and Regression',
2,
None,
'support-vector-machines-and-regression'),
('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'),
('What is the link between Artificial Intelligence and Machine '
'Learning and some general Remarks',
2,
None,
'what-is-the-link-between-artificial-intelligence-and-machine-learning-and-some-general-remarks'),
('Going back to the beginning of the semester',
2,
None,
'going-back-to-the-beginning-of-the-semester'),
('Not so sharp distinctions',
2,
None,
'not-so-sharp-distinctions'),
('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 47: Support Vector Machines and Summary of Course</h1>
</center> <!-- document title -->
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<!-- institution(s) -->
<center>
[1] <b>Department of Physics, University of Oslo</b>
</center>
<center>
[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b>
</center>
<br>
<center>
<h4>Aug 23, 2022</h4>
</center> <!-- date -->
<br>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="overview-of-week-47">Overview of week 47 </h2>
<ul>
<li> <b>Thursday</b>: Support Vector Machines, classification and regression.</li>
<li> <b>Friday</b>: Support Vector Machines and Summary of Course</li>
</ul>
<p>_Reading recommendations:</p>
<ol>
<li> Geron's chapter 5.</li>
<li> Hastie et al Chapter 12 (sections 12.1-12.3 are the most relevant ones)</li>
<li> Bishop chapter 7, with sections 7.1 and 7.2 as the essential ones</li>
</ol>
<p><a href="https://www.youtube.com/watch?v=efR1C6CvhmE&ab_channel=StatQuestwithJoshStarmer" target="_blank">See overview video on Support Vector Machines</a>. See also <a href="https://www.youtube.com/watch?v=N1vOgolbjSc&ab_channel=AliceZhao" target="_blank">this video</a>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="support-vector-machines-overarching-aims">Support Vector Machines, overarching aims </h2>
<p>A Support Vector Machine (SVM) is a very powerful and versatile
Machine Learning method, capable of performing linear or nonlinear
classification, regression, and even outlier detection. It is one of
the most popular models in Machine Learning, and anyone interested in
Machine Learning should have it in their toolbox. SVMs are
particularly well suited for classification of complex but small-sized or
medium-sized datasets.
</p>
<p>The case with two well-separated classes only can be understood in an
intuitive way in terms of lines in a two-dimensional space separating
the two classes (see figure below).
</p>
<p>The basic mathematics behind the SVM is however less familiar to most of us.
It relies on the definition of hyperplanes and the
definition of a <b>margin</b> which separates classes (in case of
classification problems) of variables. It is also used for regression
problems.
</p>
<p>With SVMs we distinguish between hard margin and soft margins. The
latter introduces a so-called softening parameter to be discussed
below. We distinguish also between linear and non-linear
approaches. The latter are the most frequent ones since it is rather
unlikely that we can separate classes easily by say straight lines.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="hyperplanes-and-all-that">Hyperplanes and all that </h2>
<p>The theory behind support vector machines (SVM hereafter) is based on
the mathematical description of so-called hyperplanes. Let us start
with a two-dimensional case. This will also allow us to introduce our
first SVM examples. These will be tailored to the case of two specific
classes, as displayed in the figure here based on the usage of the petal data.
</p>
<p>We assume here that our data set can be well separated into two
domains, where a straight line does the job in the separating the two
classes. Here the two classes are represented by either squares or
circles.
</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</span> <span style="color: #008000; font-weight: bold">import</span> datasets
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC, LinearSVC
<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> SGDClassifier
<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
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;axes.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">14</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;xtick.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;ytick.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
iris <span style="color: #666666">=</span> datasets<span style="color: #666666">.</span>load_iris()
X <span style="color: #666666">=</span> iris[<span style="color: #BA2121">&quot;data&quot;</span>][:, (<span style="color: #666666">2</span>, <span style="color: #666666">3</span>)] <span style="color: #408080; font-style: italic"># petal length, petal width</span>
y <span style="color: #666666">=</span> iris[<span style="color: #BA2121">&quot;target&quot;</span>]
setosa_or_versicolor <span style="color: #666666">=</span> (y <span style="color: #666666">==</span> <span style="color: #666666">0</span>) <span style="color: #666666">|</span> (y <span style="color: #666666">==</span> <span style="color: #666666">1</span>)
X <span style="color: #666666">=</span> X[setosa_or_versicolor]
y <span style="color: #666666">=</span> y[setosa_or_versicolor]
C <span style="color: #666666">=</span> <span style="color: #666666">5</span>
alpha <span style="color: #666666">=</span> <span style="color: #666666">1</span> <span style="color: #666666">/</span> (C <span style="color: #666666">*</span> <span style="color: #008000">len</span>(X))
lin_clf <span style="color: #666666">=</span> LinearSVC(loss<span style="color: #666666">=</span><span style="color: #BA2121">&quot;hinge&quot;</span>, C<span style="color: #666666">=</span>C, random_state<span style="color: #666666">=42</span>)
svm_clf <span style="color: #666666">=</span> SVC(kernel<span style="color: #666666">=</span><span style="color: #BA2121">&quot;linear&quot;</span>, C<span style="color: #666666">=</span>C)
sgd_clf <span style="color: #666666">=</span> SGDClassifier(loss<span style="color: #666666">=</span><span style="color: #BA2121">&quot;hinge&quot;</span>, learning_rate<span style="color: #666666">=</span><span style="color: #BA2121">&quot;constant&quot;</span>, eta0<span style="color: #666666">=0.001</span>, alpha<span style="color: #666666">=</span>alpha,
max_iter<span style="color: #666666">=100000</span>, random_state<span style="color: #666666">=42</span>)
scaler <span style="color: #666666">=</span> StandardScaler()
X_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>fit_transform(X)
lin_clf<span style="color: #666666">.</span>fit(X_scaled, y)
svm_clf<span style="color: #666666">.</span>fit(X_scaled, y)
sgd_clf<span style="color: #666666">.</span>fit(X_scaled, y)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;LinearSVC: &quot;</span>, lin_clf<span style="color: #666666">.</span>intercept_, lin_clf<span style="color: #666666">.</span>coef_)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;SVC: &quot;</span>, svm_clf<span style="color: #666666">.</span>intercept_, svm_clf<span style="color: #666666">.</span>coef_)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;SGDClassifier(alpha=</span><span style="color: #BB6688; font-weight: bold">{:.5f}</span><span style="color: #BA2121">):&quot;</span><span style="color: #666666">.</span>format(sgd_clf<span style="color: #666666">.</span>alpha), sgd_clf<span style="color: #666666">.</span>intercept_, sgd_clf<span style="color: #666666">.</span>coef_)
<span style="color: #408080; font-style: italic"># Compute the slope and bias of each decision boundary</span>
w1 <span style="color: #666666">=</span> <span style="color: #666666">-</span>lin_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">0</span>]<span style="color: #666666">/</span>lin_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">1</span>]
b1 <span style="color: #666666">=</span> <span style="color: #666666">-</span>lin_clf<span style="color: #666666">.</span>intercept_[<span style="color: #666666">0</span>]<span style="color: #666666">/</span>lin_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">1</span>]
w2 <span style="color: #666666">=</span> <span style="color: #666666">-</span>svm_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">0</span>]<span style="color: #666666">/</span>svm_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">1</span>]
b2 <span style="color: #666666">=</span> <span style="color: #666666">-</span>svm_clf<span style="color: #666666">.</span>intercept_[<span style="color: #666666">0</span>]<span style="color: #666666">/</span>svm_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">1</span>]
w3 <span style="color: #666666">=</span> <span style="color: #666666">-</span>sgd_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">0</span>]<span style="color: #666666">/</span>sgd_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">1</span>]
b3 <span style="color: #666666">=</span> <span style="color: #666666">-</span>sgd_clf<span style="color: #666666">.</span>intercept_[<span style="color: #666666">0</span>]<span style="color: #666666">/</span>sgd_clf<span style="color: #666666">.</span>coef_[<span style="color: #666666">0</span>, <span style="color: #666666">1</span>]
<span style="color: #408080; font-style: italic"># Transform the decision boundary lines back to the original scale</span>
line1 <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>inverse_transform([[<span style="color: #666666">-10</span>, <span style="color: #666666">-10</span> <span style="color: #666666">*</span> w1 <span style="color: #666666">+</span> b1], [<span style="color: #666666">10</span>, <span style="color: #666666">10</span> <span style="color: #666666">*</span> w1 <span style="color: #666666">+</span> b1]])
line2 <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>inverse_transform([[<span style="color: #666666">-10</span>, <span style="color: #666666">-10</span> <span style="color: #666666">*</span> w2 <span style="color: #666666">+</span> b2], [<span style="color: #666666">10</span>, <span style="color: #666666">10</span> <span style="color: #666666">*</span> w2 <span style="color: #666666">+</span> b2]])
line3 <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>inverse_transform([[<span style="color: #666666">-10</span>, <span style="color: #666666">-10</span> <span style="color: #666666">*</span> w3 <span style="color: #666666">+</span> b3], [<span style="color: #666666">10</span>, <span style="color: #666666">10</span> <span style="color: #666666">*</span> w3 <span style="color: #666666">+</span> b3]])
<span style="color: #408080; font-style: italic"># Plot all three decision boundaries</span>
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>plot(line1[:, <span style="color: #666666">0</span>], line1[:, <span style="color: #666666">1</span>], <span style="color: #BA2121">&quot;k:&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;LinearSVC&quot;</span>)
plt<span style="color: #666666">.</span>plot(line2[:, <span style="color: #666666">0</span>], line2[:, <span style="color: #666666">1</span>], <span style="color: #BA2121">&quot;b--&quot;</span>, linewidth<span style="color: #666666">=2</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;SVC&quot;</span>)
plt<span style="color: #666666">.</span>plot(line3[:, <span style="color: #666666">0</span>], line3[:, <span style="color: #666666">1</span>], <span style="color: #BA2121">&quot;r-&quot;</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">&quot;SGDClassifier&quot;</span>)
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==1</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==1</span>], <span style="color: #BA2121">&quot;bs&quot;</span>) <span style="color: #408080; font-style: italic"># label=&quot;Iris-Versicolor&quot;</span>
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==0</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==0</span>], <span style="color: #BA2121">&quot;yo&quot;</span>) <span style="color: #408080; font-style: italic"># label=&quot;Iris-Setosa&quot;</span>
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&quot;Petal length&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&quot;Petal width&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">&quot;upper center&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>, <span style="color: #666666">5.5</span>, <span style="color: #666666">0</span>, <span style="color: #666666">2</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="what-is-a-hyperplane">What is a hyperplane? </h2>
<p>The aim of the SVM algorithm is to find a hyperplane in a
\( p \)-dimensional space, where \( p \) is the number of features that
distinctly classifies the data points.
</p>
<p>In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \).
As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is
a two-dimensional subspace, or stated simply, a plane.
</p>
<p>In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as</p>
$$
b+w_1x_1+w_2x_2=0,
$$
<p>where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line
\( b+w_1x_1+w_2x_2=0 \).
In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \).
We can then rewrite the above equation as
</p>
$$
\boldsymbol{x}^T\boldsymbol{w}+b=0.
$$
<p>For figures, see <a href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/HandWrittenNotes/2021" target="_blank">handwritten notes</a> for Thursday November 25.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-p-dimensional-space-of-features">A \( p \)-dimensional space of features </h2>
<p>We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \).
In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as
</p>
$$
b+wx_1+w_2x_2+\dots +w_px_p=0.
$$
<p>If we define a
matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \)
of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \),
</p>
$$
\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}.
$$
<p>If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have </p>
$$
b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0,
$$
<p>if our output \( y_i=1 \).
In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if
</p>
$$
b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0,
$$
<p>for the class of observations \( y_i=-1 \),
then \( \boldsymbol{x}_i \) lies on the other side.
</p>
<p>Equivalently, for the two classes of observations we have </p>
$$
y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0.
$$
<p>When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.</p>
<!-- !split -->
<h2 id="the-two-dimensional-case">The two-dimensional case </h2>
<p>Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional
plane. To separate the two classes of data points, there are many
possible lines (hyperplanes if you prefer a more strict naming)
that could be chosen. Our objective is to find a
plane that has the maximum margin, i.e the maximum distance between
data points of both classes. Maximizing the margin distance provides
some reinforcement so that future data points can be classified with
more confidence.
</p>
<p>What a linear classifier attempts to accomplish is to split the
feature space into two half spaces by placing a hyperplane between the
data points. This hyperplane will be our decision boundary. All
points on one side of the plane will belong to class one and all points
on the other side of the plane will belong to the second class two.
</p>
<p>Unfortunately there are many ways in which we can place a hyperplane
to divide the data. Below is an example of two candidate hyperplanes
for our data sample.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="getting-into-the-details">Getting into the details </h2>
<p>Let us define the function</p>
$$
f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0,
$$
<p>as the function that determines the line \( L \) that separates two classes (our two features), see the figures in the <a href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/HandWrittenNotes/2021" target="_blank">handwritten notes</a> for Thursday November 25.
.
</p>
<p>Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). </p>
<p>The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then</p>
$$
\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b).
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="first-attempt-at-a-minimization-approach">First attempt at a minimization approach </h2>
<p>How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could
do is to define a cost function which now contains the set of all
misclassified points \( M \) and attempt to minimize this function
</p>
$$
C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b).
$$
<p>We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us</p>
$$
\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i,
$$
<p>and </p>
$$
\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="solving-the-equations">Solving the equations </h2>
<p>We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations</p>
$$
b \leftarrow b +\eta \frac{\partial C}{\partial b},
$$
<p>and</p>
$$
\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}},
$$
<p>where \( \eta \) is our by now well-known learning rate. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="problems-with-the-simpler-approach">Problems with the Simpler Approach </h2>
<p>The equations we discussed above can be coded rather easily (the
framework is similar to what we developed for logistic
regression).
</p>
<p>There are however problems with this approach, although it looks
pretty straightforward to implement. When running such a calculation, we can easily end up with many diffeent lines which separate the two classes.
</p>
<p>For small
gaps between the entries, we may also end up needing many iterations
before the solutions converge and if the data cannot be separated
properly into two distinct classes, we may not experience a converge
at all.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-better-approach">A better approach </h2>
<p>A better approach is rather to try to define a large margin between
the two classes (if they are well separated from the beginning).
</p>
<p>Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to
\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition
</p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n.
$$
<p>All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. </p>
<p>We seek thus the largest value \( M \) defined by</p>
$$
\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n,
$$
<p>or just </p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i=1,2,\dots,n.
$$
<p>If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of
\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert_2^2 \) (the norm) subject to the condition
</p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i=1,2,\dots,n.
$$
<p>We have thus defined our margin as the invers of the norm of
\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as
possible margin \( M \). Before we proceed, we need to remind ourselves
about Lagrangian multipliers.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-quick-reminder-on-lagrangian-multipliers">A quick Reminder on Lagrangian Multipliers </h2>
<p>Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an
extreme we have
</p>
$$
df=0.
$$
<p>A necessary and sufficient condition is</p>
$$
\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0,
$$
<p>due to</p>
$$
df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz.
$$
<p>In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin)
so that they are no longer all independent. It is possible at least in principle to use each
constraint to eliminate one variable
and to proceed with a new and smaller set of independent varables.
</p>
<p>The use of so-called Lagrangian multipliers is an alternative technique when the elimination
of variables is incovenient or undesirable. Assume that we have an equation of constraint on
the variables \( x,y,z \)
</p>
$$
\phi(x,y,z) = 0,
$$
<p> resulting in</p>
$$
d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0.
$$
<p>Now we cannot set anymore</p>
$$
\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0,
$$
<p>if \( df=0 \) is wanted
because there are now only two independent variables! Assume \( x \) and \( y \) are the independent
variables.
Then \( dz \) is no longer arbitrary.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="adding-the-multiplier">Adding the Multiplier </h2>
<p>However, we can add to</p>
$$
df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz,
$$
<p>a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in</p>
$$
df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda
\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+
(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0.
$$
<p>Our multiplier is chosen so that</p>
$$
\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0.
$$
<p>We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have</p>
$$
\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0,
$$
<p>and</p>
$$
\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0.
$$
<p>When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and
\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined,
it is therefore often called
Lagrange's undetermined multiplier.
If we have a set of constraints \( \phi_k \) we have the equations
</p>
$$
\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="setting-up-the-problem">Setting up the Problem </h2>
<p>In order to solve the above problem, we define the following Lagrangian function to be minimized </p>
$$
{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right],
$$
<p>where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \).</p>
<p>Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain </p>
$$
\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0,
$$
<p>and </p>
$$
\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i.
$$
<p>Inserting these constraints into the equation for \( {\cal L} \) we obtain</p>
$$
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j,
$$
<p>subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \).
We must in addition satisfy the <a href="https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions" target="_blank">Karush-Kuhn-Tucker</a> (KKT) condition
</p>
$$
\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i.
$$
<ol>
<li> If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.</li>
<li> If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).</li>
</ol>
<p>When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-problem-to-solve">The problem to solve </h2>
<p>We can rewrite </p>
$$
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j,
$$
<p>and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem</p>
$$
\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\
y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\
\dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots \\
y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\
\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda},
$$
<p>subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda}^T =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and
\( \boldsymbol{y}^T=[y_1,y_2,\dots,y_n] \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-last-steps">The last steps </h2>
<p>Solving the above problem, yields the values of \( \lambda_i \).
To find the coefficients of your hyperplane we need simply to compute
</p>
$$
\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i.
$$
<p>With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via </p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1,
$$
<p>resulting in</p>
$$
b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i,
$$
<p>or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have</p>
$$
b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right).
$$
<p>With our hyperplane coefficients we can use our classifier to assign any observation by simply using </p>
$$
y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b).
$$
<p>Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. </p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-soft-classifier">A soft classifier </h2>
<p>Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.</p>
<p>Suppose now that classes overlap in feature space, as shown in the
figure in the <a href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/HandWrittenNotes/2021" target="_blank">handwritten notes</a> for Thursday November 25.
</p>
<p>One way to deal with this problem before we define the
so-called <b>kernel approach</b>, is to allow a kind of slack in the sense
that we allow some points to be on the wrong side of the margin.
</p>
<p>We introduce thus the so-called <b>slack</b> variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and
modify our previous equation
</p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1,
$$
<p>to </p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i,
$$
<p>with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \).
The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction
\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \),
we bound the total amount by which predictions fall on the wrong side of their margins.
</p>
<p>Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of
misclassifications.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="soft-optmization-problem">Soft optmization problem </h2>
<p>This has in turn the consequences that we change our optmization problem to finding the minimum of </p>
$$
{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i,
$$
<p>subject to </p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i,
$$
<p>with the requirement \( \xi_i\geq 0 \).</p>
<p>Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain </p>
$$
\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0,
$$
<p>and </p>
$$
\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i,
$$
<p>and</p>
$$
\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i.
$$
<p>Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before</p>
$$
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j,
$$
<p>but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \).
We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads
</p>
$$
\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i,
$$
$$
\gamma_i\xi_i = 0,
$$
<p>and </p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i.
$$
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="kernels-and-non-linearity">Kernels and non-linearity </h2>
<p>The cases we have studied till now, were all characterized by two classes
with a close to linear separability. The classifiers we have described
so far find linear boundaries in our input feature space. It is
possible to make our procedure more flexible by exploring the feature
space using other basis expansions such as higher-order polynomials,
wavelets, splines etc.
</p>
<p>If our feature space is not easy to separate, as shown in the figure
in the <a href="https://github.com/CompPhysics/MachineLearning/tree/master/doc/HandWrittenNotes/2021" target="_blank">handwritten notes</a> for Thursday November 25.
, we can achieve a better separation by introducing more complex
basis functions. The ideal would be to, via a specific transformation to
obtain a separation between the classes which is almost linear.
</p>
<p>The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that
we need to introduce for example a polynomial transformation to a two-dimensional training set.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">42</span>)
<span style="color: #408080; font-style: italic"># To plot pretty figures</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;axes.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">14</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;xtick.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;ytick.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets
X1D <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-4</span>, <span style="color: #666666">4</span>, <span style="color: #666666">9</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
X2D <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[X1D, X1D<span style="color: #666666">**2</span>]
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">0</span>, <span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0</span>, <span style="color: #666666">0</span>])
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
plt<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>, which<span style="color: #666666">=</span><span style="color: #BA2121">&#39;both&#39;</span>)
plt<span style="color: #666666">.</span>axhline(y<span style="color: #666666">=0</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;k&#39;</span>)
plt<span style="color: #666666">.</span>plot(X1D[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==0</span>], np<span style="color: #666666">.</span>zeros(<span style="color: #666666">4</span>), <span style="color: #BA2121">&quot;bs&quot;</span>)
plt<span style="color: #666666">.</span>plot(X1D[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==1</span>], np<span style="color: #666666">.</span>zeros(<span style="color: #666666">5</span>), <span style="color: #BA2121">&quot;g^&quot;</span>)
plt<span style="color: #666666">.</span>gca()<span style="color: #666666">.</span>get_yaxis()<span style="color: #666666">.</span>set_ticks([])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=20</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">-4.5</span>, <span style="color: #666666">4.5</span>, <span style="color: #666666">-0.2</span>, <span style="color: #666666">0.2</span>])
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
plt<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>, which<span style="color: #666666">=</span><span style="color: #BA2121">&#39;both&#39;</span>)
plt<span style="color: #666666">.</span>axhline(y<span style="color: #666666">=0</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;k&#39;</span>)
plt<span style="color: #666666">.</span>axvline(x<span style="color: #666666">=0</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;k&#39;</span>)
plt<span style="color: #666666">.</span>plot(X2D[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==0</span>], X2D[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==0</span>], <span style="color: #BA2121">&quot;bs&quot;</span>)
plt<span style="color: #666666">.</span>plot(X2D[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==1</span>], X2D[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==1</span>], <span style="color: #BA2121">&quot;g^&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=20</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&quot;$x_2$&quot;</span>, fontsize<span style="color: #666666">=20</span>, rotation<span style="color: #666666">=0</span>)
plt<span style="color: #666666">.</span>gca()<span style="color: #666666">.</span>get_yaxis()<span style="color: #666666">.</span>set_ticks([<span style="color: #666666">0</span>, <span style="color: #666666">4</span>, <span style="color: #666666">8</span>, <span style="color: #666666">12</span>, <span style="color: #666666">16</span>])
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">-4.5</span>, <span style="color: #666666">4.5</span>], [<span style="color: #666666">6.5</span>, <span style="color: #666666">6.5</span>], <span style="color: #BA2121">&quot;r--&quot;</span>, linewidth<span style="color: #666666">=3</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">-4.5</span>, <span style="color: #666666">4.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">17</span>])
plt<span style="color: #666666">.</span>subplots_adjust(right<span style="color: #666666">=1</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="the-equations">The equations </h2>
<p>Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables)</p>
$$
z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right).
$$
<p>With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)</p>
$$
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j,
$$
<p>subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors</p>
$$
y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i,
$$
<p>from which we also find \( b \).
To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as
</p>
$$
K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j).
$$
<p>For the above example, the kernel reads</p>
$$
K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2.
$$
<p>We note that this is nothing but the dot product of the two original
vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the
product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute
the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \).
</p>
<p>This leads to the so-called
kernel trick and the result leads to the same as if we went through
the trouble of performing the transformation
\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-problem-to-solve">The problem to solve </h2>
<p>Using our definition of the kernel We can rewrite again the Lagrangian</p>
$$
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j,
$$
<p>subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem</p>
$$
\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\
y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\
\dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots \\
y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\
\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda},
$$
<p>subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and
\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \).
If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \).
</p>
<p>We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type</p>
$$
\begin{align*}
&\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber
&\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f.
\end{align*}
$$
<p>Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \).
Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into
\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \).
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="different-kernels-and-mercer-s-theorem">Different kernels and Mercer's theorem </h2>
<p>There are several popular kernels being used. These are</p>
<ol>
<li> Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),</li>
<li> Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),</li>
<li> Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),</li>
<li> Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),</li>
</ol>
<p>and many other ones.</p>
<p>An important theorem for us is <a href="https://en.wikipedia.org/wiki/Mercer%27s_theorem" target="_blank">Mercer's
theorem</a>. The
theorem states that if a kernel function \( K \) is symmetric, continuous
and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there
exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into
another space (possibly with much higher dimensions) such that
</p>
$$
K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j).
$$
<p>So you can use \( K \) as a kernel since you know \( \phi \) exists, even if
you don&#8217;t know what \( \phi \) is.
</p>
<p>Note that some frequently used kernels (such as the Sigmoid kernel)
don&#8217;t respect all of Mercer&#8217;s conditions, yet they generally work well
in practice.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="the-moons-example">The moons 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">from</span> <span style="color: #0000FF; font-weight: bold">__future__</span> <span style="color: #008000; font-weight: bold">import</span> division, print_function, unicode_literals
<span style="color: #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>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">42</span>)
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;axes.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">14</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;xtick.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
plt<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">&#39;ytick.labelsize&#39;</span>] <span style="color: #666666">=</span> <span style="color: #666666">12</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.svm</span> <span style="color: #008000; font-weight: bold">import</span> SVC
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn</span> <span style="color: #008000; font-weight: bold">import</span> datasets
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.pipeline</span> <span style="color: #008000; font-weight: bold">import</span> Pipeline
<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
<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> LinearSVC
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
X, y <span style="color: #666666">=</span> make_moons(n_samples<span style="color: #666666">=100</span>, noise<span style="color: #666666">=0.15</span>, random_state<span style="color: #666666">=42</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plot_dataset</span>(X, y, axes):
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==0</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==0</span>], <span style="color: #BA2121">&quot;bs&quot;</span>)
plt<span style="color: #666666">.</span>plot(X[:, <span style="color: #666666">0</span>][y<span style="color: #666666">==1</span>], X[:, <span style="color: #666666">1</span>][y<span style="color: #666666">==1</span>], <span style="color: #BA2121">&quot;g^&quot;</span>)
plt<span style="color: #666666">.</span>axis(axes)
plt<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>, which<span style="color: #666666">=</span><span style="color: #BA2121">&#39;both&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=20</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&quot;$x_2$&quot;</span>, fontsize<span style="color: #666666">=20</span>, rotation<span style="color: #666666">=0</span>)
plot_dataset(X, y, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
plt<span style="color: #666666">.</span>show()
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> make_moons
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.pipeline</span> <span style="color: #008000; font-weight: bold">import</span> Pipeline
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> PolynomialFeatures
polynomial_svm_clf <span style="color: #666666">=</span> Pipeline([
(<span style="color: #BA2121">&quot;poly_features&quot;</span>, PolynomialFeatures(degree<span style="color: #666666">=3</span>)),
(<span style="color: #BA2121">&quot;scaler&quot;</span>, StandardScaler()),
(<span style="color: #BA2121">&quot;svm_clf&quot;</span>, LinearSVC(C<span style="color: #666666">=10</span>, loss<span style="color: #666666">=</span><span style="color: #BA2121">&quot;hinge&quot;</span>, random_state<span style="color: #666666">=42</span>))
])
polynomial_svm_clf<span style="color: #666666">.</span>fit(X, y)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">plot_predictions</span>(clf, axes):
x0s <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(axes[<span style="color: #666666">0</span>], axes[<span style="color: #666666">1</span>], <span style="color: #666666">100</span>)
x1s <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(axes[<span style="color: #666666">2</span>], axes[<span style="color: #666666">3</span>], <span style="color: #666666">100</span>)
x0, x1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x0s, x1s)
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[x0<span style="color: #666666">.</span>ravel(), x1<span style="color: #666666">.</span>ravel()]
y_pred <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>predict(X)<span style="color: #666666">.</span>reshape(x0<span style="color: #666666">.</span>shape)
y_decision <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>decision_function(X)<span style="color: #666666">.</span>reshape(x0<span style="color: #666666">.</span>shape)
plt<span style="color: #666666">.</span>contourf(x0, x1, y_pred, cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>brg, alpha<span style="color: #666666">=0.2</span>)
plt<span style="color: #666666">.</span>contourf(x0, x1, y_decision, cmap<span style="color: #666666">=</span>plt<span style="color: #666666">.</span>cm<span style="color: #666666">.</span>brg, alpha<span style="color: #666666">=0.1</span>)
plot_predictions(polynomial_svm_clf, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
plot_dataset(X, y, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
plt<span style="color: #666666">.</span>show()
<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
poly_kernel_svm_clf <span style="color: #666666">=</span> Pipeline([
(<span style="color: #BA2121">&quot;scaler&quot;</span>, StandardScaler()),
(<span style="color: #BA2121">&quot;svm_clf&quot;</span>, SVC(kernel<span style="color: #666666">=</span><span style="color: #BA2121">&quot;poly&quot;</span>, degree<span style="color: #666666">=3</span>, coef0<span style="color: #666666">=1</span>, C<span style="color: #666666">=5</span>))
])
poly_kernel_svm_clf<span style="color: #666666">.</span>fit(X, y)
poly100_kernel_svm_clf <span style="color: #666666">=</span> Pipeline([
(<span style="color: #BA2121">&quot;scaler&quot;</span>, StandardScaler()),
(<span style="color: #BA2121">&quot;svm_clf&quot;</span>, SVC(kernel<span style="color: #666666">=</span><span style="color: #BA2121">&quot;poly&quot;</span>, degree<span style="color: #666666">=10</span>, coef0<span style="color: #666666">=100</span>, C<span style="color: #666666">=5</span>))
])
poly100_kernel_svm_clf<span style="color: #666666">.</span>fit(X, y)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
plot_predictions(poly_kernel_svm_clf, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
plot_dataset(X, y, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&quot;$d=3, r=1, C=5$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
plot_predictions(poly100_kernel_svm_clf, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
plot_dataset(X, y, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&quot;$d=10, r=100, C=5$&quot;</span>, fontsize<span style="color: #666666">=18</span>)
plt<span style="color: #666666">.</span>show()
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">gaussian_rbf</span>(x, landmark, gamma):
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>gamma <span style="color: #666666">*</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>norm(x <span style="color: #666666">-</span> landmark, axis<span style="color: #666666">=1</span>)<span style="color: #666666">**2</span>)
gamma <span style="color: #666666">=</span> <span style="color: #666666">0.3</span>
x1s <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-4.5</span>, <span style="color: #666666">4.5</span>, <span style="color: #666666">200</span>)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
x2s <span style="color: #666666">=</span> gaussian_rbf(x1s, <span style="color: #666666">-2</span>, gamma)
x3s <span style="color: #666666">=</span> gaussian_rbf(x1s, <span style="color: #666666">1</span>, gamma)
XK <span style="color: #666666">=</span> np<span style="color: #666666">.</span>c_[gaussian_rbf(X1D, <span style="color: #666666">-2</span>, gamma), gaussian_rbf(X1D, <span style="color: #666666">1</span>, gamma)]
yk <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">0</span>, <span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">1</span>, <span style="color: #666666">0</span>, <span style="color: #666666">0</span>])
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">4</span>))
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">121</span>)
plt<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>, which<span style="color: #666666">=</span><span style="color: #BA2121">&#39;both&#39;</span>)
plt<span style="color: #666666">.</span>axhline(y<span style="color: #666666">=0</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;k&#39;</span>)
plt<span style="color: #666666">.</span>scatter(x<span style="color: #666666">=</span>[<span style="color: #666666">-2</span>, <span style="color: #666666">1</span>], y<span style="color: #666666">=</span>[<span style="color: #666666">0</span>, <span style="color: #666666">0</span>], s<span style="color: #666666">=150</span>, alpha<span style="color: #666666">=0.5</span>, c<span style="color: #666666">=</span><span style="color: #BA2121">&quot;red&quot;</span>)
plt<span style="color: #666666">.</span>plot(X1D[:, <span style="color: #666666">0</span>][yk<span style="color: #666666">==0</span>], np<span style="color: #666666">.</span>zeros(<span style="color: #666666">4</span>), <span style="color: #BA2121">&quot;bs&quot;</span>)
plt<span style="color: #666666">.</span>plot(X1D[:, <span style="color: #666666">0</span>][yk<span style="color: #666666">==1</span>], np<span style="color: #666666">.</span>zeros(<span style="color: #666666">5</span>), <span style="color: #BA2121">&quot;g^&quot;</span>)
plt<span style="color: #666666">.</span>plot(x1s, x2s, <span style="color: #BA2121">&quot;g--&quot;</span>)
plt<span style="color: #666666">.</span>plot(x1s, x3s, <span style="color: #BA2121">&quot;b:&quot;</span>)
plt<span style="color: #666666">.</span>gca()<span style="color: #666666">.</span>get_yaxis()<span style="color: #666666">.</span>set_ticks([<span style="color: #666666">0</span>, <span style="color: #666666">0.25</span>, <span style="color: #666666">0.5</span>, <span style="color: #666666">0.75</span>, <span style="color: #666666">1</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&quot;$x_1$&quot;</span>, fontsize<span style="color: #666666">=20</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&quot;Similarity&quot;</span>, fontsize<span style="color: #666666">=14</span>)
plt<span style="color: #666666">.</span>annotate(<span style="color: #BA2121">r&#39;$\mathbf</span><span style="color: #BB6688; font-weight: bold">{x}</span><span style="color: #BA2121">$&#39;</span>,
xy<span style="color: #666666">=</span>(X1D[<span style="color: #666666">3</span>, <span style="color: #666666">0</span>], <span style="color: #666666">0</span>),
xytext<span style="color: #666666">=</span>(<span style="color: #666666">-0.5</span>, <span style="color: #666666">0.20</span>),
ha<span style="color: #666666">=</span><span style="color: #BA2121">&quot;center&quot;</span>,
arrowprops<span style="color: #666666">=</span><span style="color: #008000">dict</span>(facecolor<span style="color: #666666">=</span><span style="color: #BA2121">&#39;black&#39;</span>, shrink<span style="color: #666666">=0.1</span>),
fontsize<span style="color: #666666">=18</span>,
)
plt<span style="color: #666666">.</span>text(<span style="color: #666666">-2</span>, <span style="color: #666666">0.9</span>, <span style="color: #BA2121">&quot;$x_2$&quot;</span>, ha<span style="color: #666666">=</span><span style="color: #BA2121">&quot;center&quot;</span>, fontsize<span style="color: #666666">=20</span>)
plt<span style="color: #666666">.</span>text(<span style="color: #666666">1</span>, <span style="color: #666666">0.9</span>, <span style="color: #BA2121">&quot;$x_3$&quot;</span>, ha<span style="color: #666666">=</span><span style="color: #BA2121">&quot;center&quot;</span>, fontsize<span style="color: #666666">=20</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">-4.5</span>, <span style="color: #666666">4.5</span>, <span style="color: #666666">-0.1</span>, <span style="color: #666666">1.1</span>])
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">122</span>)
plt<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>, which<span style="color: #666666">=</span><span style="color: #BA2121">&#39;both&#39;</span>)
plt<span style="color: #666666">.</span>axhline(y<span style="color: #666666">=0</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;k&#39;</span>)
plt<span style="color: #666666">.</span>axvline(x<span style="color: #666666">=0</span>, color<span style="color: #666666">=</span><span style="color: #BA2121">&#39;k&#39;</span>)
plt<span style="color: #666666">.</span>plot(XK[:, <span style="color: #666666">0</span>][yk<span style="color: #666666">==0</span>], XK[:, <span style="color: #666666">1</span>][yk<span style="color: #666666">==0</span>], <span style="color: #BA2121">&quot;bs&quot;</span>)
plt<span style="color: #666666">.</span>plot(XK[:, <span style="color: #666666">0</span>][yk<span style="color: #666666">==1</span>], XK[:, <span style="color: #666666">1</span>][yk<span style="color: #666666">==1</span>], <span style="color: #BA2121">&quot;g^&quot;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r&quot;$x_2$&quot;</span>, fontsize<span style="color: #666666">=20</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r&quot;$x_3$ &quot;</span>, fontsize<span style="color: #666666">=20</span>, rotation<span style="color: #666666">=0</span>)
plt<span style="color: #666666">.</span>annotate(<span style="color: #BA2121">r&#39;$\phi\left(\mathbf</span><span style="color: #BB6688; font-weight: bold">{x}</span><span style="color: #BA2121">\right)$&#39;</span>,
xy<span style="color: #666666">=</span>(XK[<span style="color: #666666">3</span>, <span style="color: #666666">0</span>], XK[<span style="color: #666666">3</span>, <span style="color: #666666">1</span>]),
xytext<span style="color: #666666">=</span>(<span style="color: #666666">0.65</span>, <span style="color: #666666">0.50</span>),
ha<span style="color: #666666">=</span><span style="color: #BA2121">&quot;center&quot;</span>,
arrowprops<span style="color: #666666">=</span><span style="color: #008000">dict</span>(facecolor<span style="color: #666666">=</span><span style="color: #BA2121">&#39;black&#39;</span>, shrink<span style="color: #666666">=0.1</span>),
fontsize<span style="color: #666666">=18</span>,
)
plt<span style="color: #666666">.</span>plot([<span style="color: #666666">-0.1</span>, <span style="color: #666666">1.1</span>], [<span style="color: #666666">0.57</span>, <span style="color: #666666">-0.1</span>], <span style="color: #BA2121">&quot;r--&quot;</span>, linewidth<span style="color: #666666">=3</span>)
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">-0.1</span>, <span style="color: #666666">1.1</span>, <span style="color: #666666">-0.1</span>, <span style="color: #666666">1.1</span>])
plt<span style="color: #666666">.</span>subplots_adjust(right<span style="color: #666666">=1</span>)
plt<span style="color: #666666">.</span>show()
x1_example <span style="color: #666666">=</span> X1D[<span style="color: #666666">3</span>, <span style="color: #666666">0</span>]
<span style="color: #008000; font-weight: bold">for</span> landmark <span style="color: #AA22FF; font-weight: bold">in</span> (<span style="color: #666666">-2</span>, <span style="color: #666666">1</span>):
k <span style="color: #666666">=</span> gaussian_rbf(np<span style="color: #666666">.</span>array([[x1_example]]), np<span style="color: #666666">.</span>array([[landmark]]), gamma)
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Phi(</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">&quot;</span><span style="color: #666666">.</span>format(x1_example, landmark, k))
rbf_kernel_svm_clf <span style="color: #666666">=</span> Pipeline([
(<span style="color: #BA2121">&quot;scaler&quot;</span>, StandardScaler()),
(<span style="color: #BA2121">&quot;svm_clf&quot;</span>, SVC(kernel<span style="color: #666666">=</span><span style="color: #BA2121">&quot;rbf&quot;</span>, gamma<span style="color: #666666">=5</span>, C<span style="color: #666666">=0.001</span>))
])
rbf_kernel_svm_clf<span style="color: #666666">.</span>fit(X, y)
<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
gamma1, gamma2 <span style="color: #666666">=</span> <span style="color: #666666">0.1</span>, <span style="color: #666666">5</span>
C1, C2 <span style="color: #666666">=</span> <span style="color: #666666">0.001</span>, <span style="color: #666666">1000</span>
hyperparams <span style="color: #666666">=</span> (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
svm_clfs <span style="color: #666666">=</span> []
<span style="color: #008000; font-weight: bold">for</span> gamma, C <span style="color: #AA22FF; font-weight: bold">in</span> hyperparams:
rbf_kernel_svm_clf <span style="color: #666666">=</span> Pipeline([
(<span style="color: #BA2121">&quot;scaler&quot;</span>, StandardScaler()),
(<span style="color: #BA2121">&quot;svm_clf&quot;</span>, SVC(kernel<span style="color: #666666">=</span><span style="color: #BA2121">&quot;rbf&quot;</span>, gamma<span style="color: #666666">=</span>gamma, C<span style="color: #666666">=</span>C))
])
rbf_kernel_svm_clf<span style="color: #666666">.</span>fit(X, y)
svm_clfs<span style="color: #666666">.</span>append(rbf_kernel_svm_clf)
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">11</span>, <span style="color: #666666">7</span>))
<span style="color: #008000; font-weight: bold">for</span> i, svm_clf <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(svm_clfs):
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">221</span> <span style="color: #666666">+</span> i)
plot_predictions(svm_clf, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
plot_dataset(X, y, [<span style="color: #666666">-1.5</span>, <span style="color: #666666">2.5</span>, <span style="color: #666666">-1</span>, <span style="color: #666666">1.5</span>])
gamma, C <span style="color: #666666">=</span> hyperparams[i]
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r&quot;$\gamma = </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">, C = </span><span style="color: #BB6688; font-weight: bold">{}</span><span style="color: #BA2121">$&quot;</span><span style="color: #666666">.</span>format(gamma, C), fontsize<span style="color: #666666">=16</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="mathematical-optimization-of-convex-functions">Mathematical optimization of convex functions </h2>
<p>A mathematical (quadratic) optimization problem, or just optimization problem, has the form</p>
$$
\begin{align*}
&\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber
&\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f.
\end{align*}
$$
<p>subject to some constraints for say a selected set \( i=1,2,\dots, n \).
In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the
vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with.
</p>
<p>In our case we are particularly interested in a class of optimization problems called convex optmization problems.
In our discussion on gradient descent methods we discussed at length the definition of a convex function.
</p>
<p>Convex optimization problems play a central role in applied mathematics and we recommend strongly <a href="http://web.stanford.edu/~boyd/cvxbook/" target="_blank">Boyd and Vandenberghe's text on the topics</a>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="how-do-we-solve-these-problems">How do we solve these problems? </h2>
<p>If we use Python as programming language and wish to venture beyond
<b>scikit-learn</b>, <b>tensorflow</b> and similar software which makes our
lives so much easier, we need to dive into the wonderful world of
quadratic programming. We can, if we wish, solve the minimization
problem using say standard gradient methods or conjugate gradient
methods. However, these methods tend to exhibit a rather slow
converge. So, welcome to the promised land of quadratic programming.
</p>
<p>The functions we need are contained in the quadratic programming package <b>CVXOPT</b> and we need to import it together with <b>numpy</b> as</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">numpy</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">cvxopt</span>
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>This will make our life much easier. You don't need t write your own optimizer.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="a-simple-example">A simple example </h2>
<p>We remind ourselves about the general problem we want to solve</p>
$$
\begin{align*}
&\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber
&\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f.
\end{align*}
$$
<p>Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem</p>
$$
\begin{align*}
&\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber
&\mathrm{subject to} \\ \nonumber
&x, y \geq 0 \\ \nonumber
&x+3y \geq 15 \\ \nonumber
&2x+5y \leq 100 \\ \nonumber
&3x+4y \leq 80. \\ \nonumber
\end{align*}
$$
<p>The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns)</p>
$$
\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}.
$$
<p>Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation</p>
$$
\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
$$
<p>We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix </p>
$$
\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix}
$$
<p>is clearly positive semi-definite (all eigenvalues larger or equal zero).
Finally, the vector \( \boldsymbol{h} \) is defined as
</p>
$$
\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
$$
<p>Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero
The following code solves the equations for us
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># Import the necessary packages</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">from</span> <span style="color: #0000FF; font-weight: bold">cvxopt</span> <span style="color: #008000; font-weight: bold">import</span> matrix
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">cvxopt</span> <span style="color: #008000; font-weight: bold">import</span> solvers
P <span style="color: #666666">=</span> matrix(numpy<span style="color: #666666">.</span>diag([<span style="color: #666666">1</span>,<span style="color: #666666">0</span>]), tc<span style="color: #666666">=</span>d)
q <span style="color: #666666">=</span> matrix(numpy<span style="color: #666666">.</span>array([<span style="color: #666666">3</span>,<span style="color: #666666">4</span>]), tc<span style="color: #666666">=</span>d)
G <span style="color: #666666">=</span> matrix(numpy<span style="color: #666666">.</span>array([[<span style="color: #666666">-1</span>,<span style="color: #666666">0</span>],[<span style="color: #666666">0</span>,<span style="color: #666666">-1</span>],[<span style="color: #666666">-1</span>,<span style="color: #666666">-3</span>],[<span style="color: #666666">2</span>,<span style="color: #666666">5</span>],[<span style="color: #666666">3</span>,<span style="color: #666666">4</span>]]), tc<span style="color: #666666">=</span>d)
h <span style="color: #666666">=</span> matrix(numpy<span style="color: #666666">.</span>array([<span style="color: #666666">0</span>,<span style="color: #666666">0</span>,<span style="color: #666666">-15</span>,<span style="color: #666666">100</span>,<span style="color: #666666">80</span>]), tc<span style="color: #666666">=</span>d)
<span style="color: #408080; font-style: italic"># Construct the QP, invoke solver</span>
sol <span style="color: #666666">=</span> solvers<span style="color: #666666">.</span>qp(P,q,G,h)
<span style="color: #408080; font-style: italic"># Extract optimal value and solution</span>
sol[x]
sol[primal objective]
</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="support-vector-machines-and-regression">Support Vector Machines and Regression </h2>
<p>Material may be added if of interest. See Bishop chapter 7.1 for a discussion.</p>
<!-- !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="what-is-the-link-between-artificial-intelligence-and-machine-learning-and-some-general-remarks">What is the link between Artificial Intelligence and Machine Learning and some general Remarks </h2>
<p>Artificial intelligence is built upon integrated machine learning
algorithms as discussed in this course, which in turn are fundamentally rooted in optimization and
statistical learning.
</p>
<p>Can we have Artificial Intelligence without Machine Learning? See <a href="https://www.linkedin.com/pulse/what-artificial-intelligence-without-machine-learning-claudia-pohlink" target="_blank">this post for inspiration</a>.</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="going-back-to-the-beginning-of-the-semester">Going back to the beginning of the semester </h2>
<p>Traditionally the field of machine learning has had its main focus on
predictions and correlations. These concepts outline in some sense
the difference between machine learning and what is normally called
Bayesian statistics or Bayesian inference.
</p>
<p>In machine learning and prediction based tasks, we are often
interested in developing algorithms that are capable of learning
patterns from given data in an automated fashion, and then using these
learned patterns to make predictions or assessments of newly given
data. In many cases, our primary concern is the quality of the
predictions or assessments, and we are less concerned with the
underlying patterns that were learned in order to make these
predictions. This leads to what normally has been labeled as a
frequentist approach.
</p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="not-so-sharp-distinctions">Not so sharp distinctions </h2>
<p>You should keep in mind that the division between a traditional
frequentist approach with focus on predictions and correlations only
and a Bayesian approach with an emphasis on estimations and
causations, is not that sharp. Machine learning can be frequentist
with ensemble methods (EMB) as examples and Bayesian with Gaussian
Processes as examples.
</p>
<p>If one views ML from a statistical learning
perspective, one is then equally interested in estimating errors as
one is in finding correlations and making predictions. It is important
to keep in mind that the frequentist and Bayesian approaches differ
mainly in their interpretations of probability. In the frequentist
world, we can only assign probabilities to repeated random
phenomena. From the observations of these phenomena, we can infer the
probability of occurrence of a specific event. In Bayesian
statistics, we assign probabilities to specific events and the
probability represents the measure of belief/confidence for that
event. The belief can be updated in the light of new evidence.
</p>
<!-- !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> 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>
<p>The following topics will be covered</p>
<ol>
<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> Support vector machines
<ol type="a"></li>
<li> Binary classification and multiclass classification</li>
<li> Kernel methods</li>
<li> Regression</li>
</ol>
</ol>
<!-- !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</li>
<li> 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 and you are expected to know modern programming languages like Python or C++.</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. Still many low-hanging fruits.</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>. Similarly, the search for Higgs was a statistical learning tour de force. See this link on <a href="https://www.kaggle.com/c/higgs-boson" target="_blank">Kaggle.com</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>
<ol>
<li> Supervised?</li>
<li> Start with the simplest model that fits your problem</li>
<li> Start with minimal processing of data</li>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="preparing-your-data">Preparing Your Data </h2>
<ol>
<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> <a href="https://multivariatestatsjl.readthedocs.io/en/latest/whiten.html" target="_blank">Whitening</a></li>
<ul>
<li> Decorrelates data</li>
<li> Can be hit or miss</li>
</ul>
<li> When to do train/test split?</li>
</ol>
<p>Whitening is a decorrelation transformation that transforms a set of
random variables into a set of new random variables with identity
covariance (uncorrelated with unit variances).
</p>
<!-- !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>
<ol>
<li> RELU? ELU?</li>
<li> Sigmoid or Tanh?</li>
<li> Set all weights to 0?</li>
<ul>
<li> Terrible idea</li>
</ul>
<li> Set all weights to random values?</li>
<ul>
<li> Small random values</li>
</ul>
</ol>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="optimization-methods-and-hyperparameters">Optimization Methods and Hyperparameters </h2>
<ol>
<li> Stochastic gradient descent
<ol type="a"></li>
<li> Stochastic gradient descent + momentum</li>
</ol>
<li> State-of-the-art approaches:</li>
<ul>
<li> RMSProp</li>
<li> Adam</li>
<li> and more</li>
</ul>
</ol>
<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>
<p>The link here <a href="https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/" target="_blank"><tt>https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/</tt></a> gives an excellent overview of courses on Machine learning at UiO.</p>
<ol>
<li> <a href="http://www.uio.no/studier/emner/matnat/math/STK2100/index-eng.html" target="_blank">STK2100 Machine learning and statistical methods for prediction and classification</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 with an algorithmic approach.</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 Adaptive Methods for Data-Based Decision Making</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/IN5400/" target="_blank">IN5400/INF5860 &#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/its/TEK5040/" target="_blank">TEK5040 &#8211; Dyp l&#230;ring for autonome systemer</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-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>