Files
FYS-STK4155/doc/pub/week47/html/week47.html
T
2020-11-26 05:33:45 +01:00

810 lines
37 KiB
HTML

<!--
Automatically generated HTML file from DocOnce source
(https://github.com/hplgit/doconce/)
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Week 47: Support Vector Machines">
<title>Week 47: Support Vector Machines</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 { color: #8A0808; }
a { color: #8A0808; text-decoration:none; }
tt { font-family: "Courier New", Courier; }
/* pre style removed because it will interfer with pygments */
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 { text-align: justify; text-justify: inter-word; }
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Overview of week 47', 2, None, '___sec0'),
('Thursday', 2, None, '___sec1'),
('Friday', 2, None, '___sec2'),
('Workshop plan Friday (first lecture)', 2, None, '___sec3'),
('Support Vector Machines, overarching aims', 2, None, '___sec4'),
('Hyperplanes and all that', 2, None, '___sec5'),
('What is a hyperplane?', 2, None, '___sec6'),
('A $p$-dimensional space of features', 2, None, '___sec7'),
('The two-dimensional case', 2, None, '___sec8'),
('Getting into the details', 2, None, '___sec9'),
('First attempt at a minimization approach', 2, None, '___sec10'),
('Solving the equations', 2, None, '___sec11'),
('Can we code this?', 2, None, '___sec12'),
('A better approach', 2, None, '___sec13'),
('A quick Reminder on Lagrangian Multipliers',
2,
None,
'___sec14'),
('Adding the Multiplier', 2, None, '___sec15'),
('Setting up the Problem', 2, None, '___sec16'),
('The problem to solve', 2, None, '___sec17'),
('The last steps', 2, None, '___sec18'),
('A soft classifier', 2, None, '___sec19'),
('Soft optmization problem', 2, None, '___sec20')]}
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</h1></center> <!-- document title -->
<p>
<!-- author(s): Morten Hjorth-Jensen -->
<center>
<b>Morten Hjorth-Jensen</b> [1, 2]
</center>
<p>
<!-- 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>
<p>
<center><h4>Nov 26, 2020</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec0">Overview of week 47 </h2>
<ul>
<li> <b>Thursday</b>: Support Vector Machines, classification and regression. <a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember19.mp4?vrtx=view-as-webpage" target="_blank">Video of Lecture</a></li>
<li> <b>Friday</b>: Workshop on project 3. <a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember20.mp4?vrtx=view-as-webpage" target="_blank">Video of Lecture</a></li>
</ul>
Geron's chapter 5. Chapter 12 (sections 12.1-12.3 are the most relevant ones) of Hastie et al contains also a good discussion.
<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="___sec1">Thursday </h2>
<p>
We start with our final topic this semester, Support Vector Machines
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec2">Friday </h2>
<p>
Friday's lecture is split in two parts. The first lecture is deveoted to a presentation of possible data sets and projects for project 3. The second lecture continues with support vector machines. It may happen that we will need parts of the second lecture as well for the project ideas.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec3">Workshop plan Friday (first lecture) </h2>
<p>
Here are the various projects that will be presented during the first lecture (and possibly parts of the second lecture as well). <em>Titles are tentative</em>. Talks are approx 5-10 mins with roughly 5 minutes for discussions.
<ul>
<li> Maria Emine Nylund: <b>Lego Bricks Classifier</b></li>
<li> Fabio Rodrigues Pereira: <b>Financial Machine Learning</b></li>
<li> Markus Borud Pettersen: <b>Machine Learning and Brain Grid Cells</b></li>
<li> Jing Sun and Endrias Getachew Asgedom: <b>Machine learning-based approaches to denoising microseismic data</b></li>
<li> Felicia Jacobsen: <b>Analysis of Breast Cancer Data</b></li>
<li> Simon Elias Schrader: <b>Predicting atomization energies of molecules</b></li>
<li> Varvara Bazilova and Sergio Andres Diaz Mesa: <b>Glacier Mapping and Machine Learning</b></li>
<li> Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: <b>Gamma ray signals stemming from dark matter in the galactic center</b></li>
</ul>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec4">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>
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.
<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>
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="___sec5">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>
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="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><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>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec6">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>
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>
In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as
$$
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
$$
\boldsymbol{x}^T\boldsymbol{w}+b=0.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec7">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 defined as
$$
b+wx_1+w_2x_2+\dots +w_px_p=0.
$$
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} \),
$$
\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}.
$$
If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have
$$
b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0,
$$
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
$$
b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0,
$$
for the class of observations \( y_i=-1 \),
then \( \boldsymbol{x}_i \) lies on the other side.
<p>
Equivalently, for the two classes of observations we have
$$
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="___sec8">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. Figure 12.1 of Hastie et al is a good illustration.
<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>
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="___sec9">Getting into the details </h2>
<p>
Let us define the function
$$
f(x) = \boldsymbol{x}^T\boldsymbol{w}+b = 0,
$$
as the function that determines the line \( L \) that separates two classes (our two features), see Figure 12.1 of <a href="https://www.springer.com/gp/book/9780387848570" target="_blank">Hastie et al</a>.
<p>
Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{x}^T(\boldsymbol{w}_1-\boldsymbol{x}_2)=0 \).
<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
$$
\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b).
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec10">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
$$
C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{x}^T\boldsymbol{w}_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
$$
\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i,
$$
and
$$
\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec11">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
$$
b \leftarrow b +\eta \frac{\partial C}{\partial b},
$$
and
$$
\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}},
$$
where \( \eta \) is our by now well-known learning rate.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec12">Can we code this? </h2>
<p>
The equations we discussed above can be coded rather easily (the
framework is similar to what we developed for logistic regression). We
can set up a simple case with two classes only and we want to find a
line which separates them the best possible way.
<p>
There are however problems with this approach, although it looks
pretty straightforward to implement. When running a code for such a
case we can easily end up with many diffeent lines which separate the
two classes.
<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="___sec13">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>
Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to
\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition
$$
y_i(\boldsymbol{x}^T\boldsymbol{w}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, 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>
We seek thus the largest value \( M \) defined by
$$
\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{x}^T\boldsymbol{w}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n,
$$
or just
$$
y_i(\boldsymbol{x}^T\boldsymbol{w}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i.
$$
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 \) (the norm) subject to the condition
$$
y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i.
$$
<p>
We have thus defined our margin as the inverse 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 and optimzation problems.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec14">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
$$
df=0.
$$
A necessary and sufficient condition is
$$
\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0,
$$
due to
$$
df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz.
$$
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>
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 \)
$$
\phi(x,y,z) = 0,
$$
resulting in
$$
d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0.
$$
Now we cannot set anymore
$$
\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0,
$$
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="___sec15">Adding the Multiplier </h2>
<p>
However, we can add to
$$
df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz,
$$
a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in
$$
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.
$$
Our multiplier is chosen so that
$$
\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
$$
\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0,
$$
and
$$
\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0.
$$
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
$$
\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0.
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec16">Setting up the Problem </h2>
In order to solve the above problem, we define the following Lagrangian function to be minimized
$$
{\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],
$$
where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \).
<p>
Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain
$$
\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0,
$$
and
$$
\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i.
$$
Inserting these constraints into the equation for \( {\cal L} \) we obtain
$$
{\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,
$$
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
$$
\lambda_i\left[y_i(\boldsymbol{x}^T\boldsymbol{w}_i+b) -1\right] \hspace{0.1cm}\forall i.
$$
<ol>
<li> If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{x}^T\boldsymbol{w}_i+b)=1 \) and we say that \( x_i \) is on the boundary.</li>
<li> If \( y_i(\boldsymbol{x}^T\boldsymbol{w}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).</li>
</ol>
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>
The support vectors (the points that define the margin \( M \)) are the quantities we keep in order to make predictions.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec17">The problem to solve </h2>
<p>
We can rewrite
$$
{\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,
$$
and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem
$$
\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},
$$
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] \).
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec18">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
$$
\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i.
$$
With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via
$$
y_i(\boldsymbol{x}^T\boldsymbol{w}_i+b)=1,
$$
resulting in
$$
b = \frac{1}{y_i}-\boldsymbol{x}_1^T\boldsymbol{w},
$$
or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have
$$
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).
$$
With our hyperplane coefficients we can use our classifier to assign any observation by simply using
$$
y_i = \mathrm{sign}(\boldsymbol{x}_i^T\boldsymbol{w}+b).
$$
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="___sec19">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>
Suppose now that the two classes overlap in feature space, as shown in Figure 12.1 of
<a href="https://www.springer.com/gp/book/9780387848570" target="_blank">Hastie et al</a>.
<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>
We introduce thus the so-called <b>slack</b> variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and
modify our previous equation
$$
y_i(\boldsymbol{x}_i^T\boldsymbol{w}+b)=1,
$$
to
$$
y_i(\boldsymbol{x}_1^T\boldsymbol{w}+b)=1-\xi_i,
$$
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{x}_i^T\boldsymbol{w}+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>
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="___sec20">Soft optmization problem </h2>
<p>
This has in turn the consequences that we change our optmization problem to finding the minimum of
$$
{\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,
$$
subject to
$$
y_i(\boldsymbol{x}_1^T\boldsymbol{w}+b)=1-\xi_i \hspace{0.1cm}\forall i,
$$
with the requirement \( \xi_i\geq 0 \).
<p>
Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain
$$
\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0,
$$
and
$$
\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i,
$$
and
$$
\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i.
$$
Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before
$$
{\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,
$$
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
$$
\lambda_i\left[y_i(\boldsymbol{x}_1^T\boldsymbol{w}+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i,
$$
$$
\gamma_i\xi_i = 0,
$$
and
$$
y_i(\boldsymbol{x}_i^T\boldsymbol{w}+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i.
$$
<!-- ------------------- end of main content --------------- -->
<center style="font-size:80%">
<!-- copyright --> &copy; 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
</center>
</body>
</html>