From b1af9b1fcbd717936ad83ef542fa151865eb432b Mon Sep 17 00:00:00 2001 From: mhjensen Date: Thu, 19 Nov 2020 05:35:55 +0100 Subject: [PATCH] svm update --- doc/pub/week47/html/._week47-bs000.html | 120 +++---- doc/pub/week47/html/._week47-bs001.html | 154 ++++----- doc/pub/week47/html/._week47-bs002.html | 201 ++++------- doc/pub/week47/html/._week47-bs003.html | 145 ++++---- doc/pub/week47/html/._week47-bs004.html | 166 +++++---- doc/pub/week47/html/._week47-bs005.html | 160 +++++---- doc/pub/week47/html/._week47-bs006.html | 209 ++++++++---- doc/pub/week47/html/._week47-bs007.html | 146 ++++---- doc/pub/week47/html/._week47-bs008.html | 154 +++++---- doc/pub/week47/html/._week47-bs009.html | 149 +++++---- doc/pub/week47/html/._week47-bs010.html | 140 ++++---- doc/pub/week47/html/._week47-bs011.html | 163 +++++---- doc/pub/week47/html/._week47-bs012.html | 162 ++++----- doc/pub/week47/html/._week47-bs013.html | 161 ++++----- doc/pub/week47/html/._week47-bs014.html | 161 ++++----- doc/pub/week47/html/._week47-bs015.html | 160 +++++---- doc/pub/week47/html/._week47-bs016.html | 160 +++++---- doc/pub/week47/html/._week47-bs017.html | 168 +++++----- doc/pub/week47/html/._week47-bs018.html | 161 +++++---- doc/pub/week47/html/._week47-bs019.html | 200 +++++------ doc/pub/week47/html/._week47-bs020.html | 157 ++++----- doc/pub/week47/html/._week47-bs021.html | 174 +++++----- doc/pub/week47/html/._week47-bs022.html | 190 ++++++----- doc/pub/week47/html/._week47-bs023.html | 321 ++++++------------ doc/pub/week47/html/._week47-bs024.html | 164 +++++---- doc/pub/week47/html/._week47-bs025.html | 168 ++++++---- doc/pub/week47/html/._week47-bs026.html | 202 +++++------ doc/pub/week47/html/._week47-bs027.html | 333 ++++++++++++++----- doc/pub/week47/html/week47-bs.html | 120 +++---- doc/pub/week47/html/week47-reveal.html | 132 +++++--- doc/pub/week47/html/week47-solarized.html | 188 +++++++---- doc/pub/week47/html/week47.html | 194 +++++++---- doc/pub/week47/ipynb/ipynb-week47-src.tar.gz | Bin 192 -> 190 bytes doc/pub/week47/ipynb/week47.ipynb | 51 ++- doc/src/week47/week47.do.txt | 43 ++- 35 files changed, 3038 insertions(+), 2639 deletions(-) diff --git a/doc/pub/week47/html/._week47-bs000.html b/doc/pub/week47/html/._week47-bs000.html index 98a4b1977..e96c3a089 100644 --- a/doc/pub/week47/html/._week47-bs000.html +++ b/doc/pub/week47/html/._week47-bs000.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -172,7 +180,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Sep 16, 2020

+

Nov 19, 2020


@@ -196,7 +204,7 @@ MathJax.Hub.Config({

  • 9
  • 10
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs001.html b/doc/pub/week47/html/._week47-bs001.html index 3227c5bab..91fe9b148 100644 --- a/doc/pub/week47/html/._week47-bs001.html +++ b/doc/pub/week47/html/._week47-bs001.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,35 +161,17 @@ MathJax.Hub.Config({ -

    Support Vector Machines, overarching aims

    +

    Overview of week 46

    + + + +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.

    -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. - -

    -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). - -

    -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 margin which separates classes (in case of -classification problems) of variables. It is also used for regression -problems. - -

    -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. +See overview video on Support Vector Machines. See also this video.

    @@ -200,7 +190,7 @@ unlikely that we can separate classes easily by say straight lines.

  • 10
  • 11
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs002.html b/doc/pub/week47/html/._week47-bs002.html index a548ff7ea..dfb2ca5de 100644 --- a/doc/pub/week47/html/._week47-bs002.html +++ b/doc/pub/week47/html/._week47-bs002.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,90 +161,11 @@ MathJax.Hub.Config({ -

    Hyperplanes and all that

    +

    Thursday

    -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. +We start with our final topic this semester, Support Vector Machines -

    -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. -

    - - -

    from sklearn import datasets
    -from sklearn.svm import SVC, LinearSVC
    -from sklearn.linear_model import SGDClassifier
    -from sklearn.preprocessing import StandardScaler
    -import matplotlib
    -import matplotlib.pyplot as plt
    -plt.rcParams['axes.labelsize'] = 14
    -plt.rcParams['xtick.labelsize'] = 12
    -plt.rcParams['ytick.labelsize'] = 12
    -
    -
    -iris = datasets.load_iris()
    -X = iris["data"][:, (2, 3)]  # petal length, petal width
    -y = iris["target"]
    -
    -setosa_or_versicolor = (y == 0) | (y == 1)
    -X = X[setosa_or_versicolor]
    -y = y[setosa_or_versicolor]
    -
    -
    -
    -C = 5
    -alpha = 1 / (C * len(X))
    -
    -lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
    -svm_clf = SVC(kernel="linear", C=C)
    -sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
    -                        max_iter=100000, random_state=42)
    -
    -scaler = StandardScaler()
    -X_scaled = scaler.fit_transform(X)
    -
    -lin_clf.fit(X_scaled, y)
    -svm_clf.fit(X_scaled, y)
    -sgd_clf.fit(X_scaled, y)
    -
    -print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
    -print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
    -print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
    -
    -# Compute the slope and bias of each decision boundary
    -w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
    -b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
    -w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
    -b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
    -w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
    -b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
    -
    -# Transform the decision boundary lines back to the original scale
    -line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
    -line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
    -line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
    -
    -# Plot all three decision boundaries
    -plt.figure(figsize=(11, 4))
    -plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
    -plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
    -plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
    -plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
    -plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
    -plt.xlabel("Petal length", fontsize=14)
    -plt.ylabel("Petal width", fontsize=14)
    -plt.legend(loc="upper center", fontsize=14)
    -plt.axis([0, 5.5, 0, 2])
    -
    -plt.show()
    -

    @@ -255,7 +184,7 @@ plt.show()

  • 11
  • 12
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs003.html b/doc/pub/week47/html/._week47-bs003.html index 5f506ea07..6e19a08f3 100644 --- a/doc/pub/week47/html/._week47-bs003.html +++ b/doc/pub/week47/html/._week47-bs003.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,33 +161,10 @@ MathJax.Hub.Config({ -

    What is a hyperplane?

    +

    Friday

    -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. - -

    -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. - -

    -In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as -$$ -b+w_1x_1+w_2x_2=0, -$$ - -

    -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. -$$ +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.

    @@ -200,7 +185,7 @@ $$

  • 12
  • 13
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs004.html b/doc/pub/week47/html/._week47-bs004.html index ab28ae589..b49fab415 100644 --- a/doc/pub/week47/html/._week47-bs004.html +++ b/doc/pub/week47/html/._week47-bs004.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,46 +161,22 @@ MathJax.Hub.Config({ -

    A \( p \)-dimensional space of features

    +

    Workshop plan Friday (first lecture)

    -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 -$$ -b+wx_1+w_2x_2+\dots +w_px_p=0. -$$ +Here are the various projects that will be presented during the first lecture (and possibly parts of the second lecture as well). Titles are tentative. Talks are approx 5-10 mins with roughly 5 minutes for discussions. -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. - -

    -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. -$$ - -

    -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. - -

    diff --git a/doc/pub/week47/html/._week47-bs005.html b/doc/pub/week47/html/._week47-bs005.html index e592d7f37..caac38707 100644 --- a/doc/pub/week47/html/._week47-bs005.html +++ b/doc/pub/week47/html/._week47-bs005.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -151,31 +159,37 @@ MathJax.Hub.Config({

     

     

     

    - + -

    The two-dimensional case

    +

    Support Vector Machines, overarching aims

    -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. +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.

    -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. +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.

    -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. +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 margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

    +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.

    @@ -198,7 +212,7 @@ for our data sample.

  • 14
  • 15
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs006.html b/doc/pub/week47/html/._week47-bs006.html index 279880a32..8460a426e 100644 --- a/doc/pub/week47/html/._week47-bs006.html +++ b/doc/pub/week47/html/._week47-bs006.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,25 +161,90 @@ MathJax.Hub.Config({ -

    Getting into the details

    +

    Hyperplanes and all that

    -Let us define the function -$$ -f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, -$$ - -as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. +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.

    -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 \). - +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.

    -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). -$$ + +

    from sklearn import datasets
    +from sklearn.svm import SVC, LinearSVC
    +from sklearn.linear_model import SGDClassifier
    +from sklearn.preprocessing import StandardScaler
    +import matplotlib
    +import matplotlib.pyplot as plt
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
    +
    +
    +iris = datasets.load_iris()
    +X = iris["data"][:, (2, 3)]  # petal length, petal width
    +y = iris["target"]
    +
    +setosa_or_versicolor = (y == 0) | (y == 1)
    +X = X[setosa_or_versicolor]
    +y = y[setosa_or_versicolor]
    +
    +
    +
    +C = 5
    +alpha = 1 / (C * len(X))
    +
    +lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
    +svm_clf = SVC(kernel="linear", C=C)
    +sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
    +                        max_iter=100000, random_state=42)
    +
    +scaler = StandardScaler()
    +X_scaled = scaler.fit_transform(X)
    +
    +lin_clf.fit(X_scaled, y)
    +svm_clf.fit(X_scaled, y)
    +sgd_clf.fit(X_scaled, y)
    +
    +print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
    +print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
    +print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
    +
    +# Compute the slope and bias of each decision boundary
    +w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
    +b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
    +w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
    +b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
    +w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
    +b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
    +
    +# Transform the decision boundary lines back to the original scale
    +line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
    +line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
    +line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
    +
    +# Plot all three decision boundaries
    +plt.figure(figsize=(11, 4))
    +plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
    +plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
    +plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
    +plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
    +plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
    +plt.xlabel("Petal length", fontsize=14)
    +plt.ylabel("Petal width", fontsize=14)
    +plt.legend(loc="upper center", fontsize=14)
    +plt.axis([0, 5.5, 0, 2])
    +
    +plt.show()
    +

    @@ -194,7 +267,7 @@ $$

  • 15
  • 16
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs007.html b/doc/pub/week47/html/._week47-bs007.html index 578b42b7b..c8f856dc1 100644 --- a/doc/pub/week47/html/._week47-bs007.html +++ b/doc/pub/week47/html/._week47-bs007.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,26 +161,32 @@ MathJax.Hub.Config({ -

    First attempt at a minimization approach

    +

    What is a hyperplane?

    -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 +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. +

    +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. + +

    +In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as $$ -C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +b+w_1x_1+w_2x_2=0, $$

    -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, -$$ +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 -and $$ -\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +\boldsymbol{x}^T\boldsymbol{w}+b=0. $$

    @@ -198,7 +212,7 @@ $$

  • 16
  • 17
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs008.html b/doc/pub/week47/html/._week47-bs008.html index b41b77b9d..348dc4b0c 100644 --- a/doc/pub/week47/html/._week47-bs008.html +++ b/doc/pub/week47/html/._week47-bs008.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,20 +161,44 @@ MathJax.Hub.Config({ -

    Solving the equations

    +

    A \( p \)-dimensional space of features

    -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 +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 \leftarrow b +\eta \frac{\partial C}{\partial b}, +b+wx_1+w_2x_2+\dots +w_px_p=0. $$ -and +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{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. $$ -where \( \eta \) is our by now well-known learning rate. +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. + +

    +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. +$$ + +

    +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.

    @@ -192,7 +224,7 @@ where \( \eta \) is our by now well-known learning rate.

  • 17
  • 18
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs009.html b/doc/pub/week47/html/._week47-bs009.html index ee9128291..f1c2ecb0e 100644 --- a/doc/pub/week47/html/._week47-bs009.html +++ b/doc/pub/week47/html/._week47-bs009.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -151,19 +159,32 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Code Example

    +

    The two-dimensional case

    -The equations we discussed above can be coded rather easily (the -framework is similar to what we developed for logistic -regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. -

    +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. + +

    +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. + +

    +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. - -

    
    -

    @@ -189,7 +210,7 @@ regression). We are going to set up a simple case with two classes only and we w

  • 18
  • 19
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs010.html b/doc/pub/week47/html/._week47-bs010.html index 3d3019a64..3027ccbfa 100644 --- a/doc/pub/week47/html/._week47-bs010.html +++ b/doc/pub/week47/html/._week47-bs010.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,18 +161,24 @@ MathJax.Hub.Config({ -

    Problems with the Simpler Approach

    +

    Getting into the details

    -There are however problems with this approach, although it looks -pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. +Let us define the function +$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ + +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here.

    -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. +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 \). + +

    +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). +$$

    @@ -192,7 +206,7 @@ at all.

  • 19
  • 20
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs011.html b/doc/pub/week47/html/._week47-bs011.html index 2838d27e8..a8da297a2 100644 --- a/doc/pub/week47/html/._week47-bs011.html +++ b/doc/pub/week47/html/._week47-bs011.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,44 +161,27 @@ MathJax.Hub.Config({ -

    A better approach

    +

    First attempt at a minimization approach

    -A better approach is rather to try to define a large margin between -the two classes (if they are well separated from the beginning). - -

    -Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to -\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition +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 $$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_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. - -

    -We seek thus the largest value \( M \) defined by -$$ -\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, -$$ - -or just -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_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. +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). $$

    -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. +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. +$$

    @@ -218,7 +209,7 @@ about Lagrangian multipliers.

  • 20
  • 21
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs012.html b/doc/pub/week47/html/._week47-bs012.html index 60f17ed0b..5efebf7b3 100644 --- a/doc/pub/week47/html/._week47-bs012.html +++ b/doc/pub/week47/html/._week47-bs012.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,52 +161,20 @@ MathJax.Hub.Config({ -

    A quick Reminder on Lagrangian Multipliers

    +

    Solving the equations

    -Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an -extreme we have +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 $$ -df=0. +b \leftarrow b +\eta \frac{\partial C}{\partial b}, $$ -A necessary and sufficient condition is +and $$ -\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, $$ -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. - -

    -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. +where \( \eta \) is our by now well-known learning rate.

    @@ -226,7 +202,7 @@ Then \( dz \) is no longer arbitrary.

  • 21
  • 22
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs013.html b/doc/pub/week47/html/._week47-bs013.html index 2e5306ac0..f4f20dafc 100644 --- a/doc/pub/week47/html/._week47-bs013.html +++ b/doc/pub/week47/html/._week47-bs013.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,46 +161,17 @@ MathJax.Hub.Config({ -

    Adding the Multiplier

    +

    Code Example

    -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. -$$ - +The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way.

    -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. -$$ + +

    
    +

    @@ -219,7 +198,7 @@ $$

  • 22
  • 23
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs014.html b/doc/pub/week47/html/._week47-bs014.html index 83f59fcb3..5ae161f80 100644 --- a/doc/pub/week47/html/._week47-bs014.html +++ b/doc/pub/week47/html/._week47-bs014.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,43 +161,18 @@ MathJax.Hub.Config({ -

    Setting up the Problem

    -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 \). +

    Problems with the Simpler Approach

    -Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain -$$ -\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, -$$ +There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. -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 Karush-Kuhn-Tucker (KKT) condition -$$ -\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. -$$ - - -

      -
    1. 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.
    2. -
    3. 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 \).
    4. -
    - -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 \). +

    +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.

    @@ -217,7 +200,7 @@ When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support

  • 23
  • 24
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs015.html b/doc/pub/week47/html/._week47-bs015.html index 9ef26d30d..884dee6de 100644 --- a/doc/pub/week47/html/._week47-bs015.html +++ b/doc/pub/week47/html/._week47-bs015.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,26 +161,44 @@ MathJax.Hub.Config({ -

    The problem to solve

    +

    A better approach

    -We can rewrite +A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

    +Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + $$ -{\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, +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. $$ -and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +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. + +

    +We seek thus the largest value \( M \) defined by $$ -\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}, +\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, $$ -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] \). +or just +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_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. +$$ + +

    +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.

    @@ -200,7 +226,7 @@ subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vec

  • 24
  • 25
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs016.html b/doc/pub/week47/html/._week47-bs016.html index 349e5ba87..08c0a0ca8 100644 --- a/doc/pub/week47/html/._week47-bs016.html +++ b/doc/pub/week47/html/._week47-bs016.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,36 +161,52 @@ MathJax.Hub.Config({ -

    The last steps

    +

    A quick Reminder on Lagrangian Multipliers

    -Solving the above problem, yields the values of \( \lambda_i \). -To find the coefficients of your hyperplane we need simply to compute +Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have $$ -\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +df=0. $$ -With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +A necessary and sufficient condition is $$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, $$ -resulting in +due to $$ -b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. $$ -or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +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. + +

    +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 \) $$ -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). +\phi(x,y,z) = 0, $$ -With our hyperplane coefficients we can use our classifier to assign any observation by simply using + resulting in $$ -y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. $$ -Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. +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.

    @@ -210,7 +234,7 @@ Below we discuss how to find the optimal values of \( \lambda_i \). Before we pr

  • 25
  • 26
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs017.html b/doc/pub/week47/html/._week47-bs017.html index e4ac520da..93c641fba 100644 --- a/doc/pub/week47/html/._week47-bs017.html +++ b/doc/pub/week47/html/._week47-bs017.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,37 +161,45 @@ MathJax.Hub.Config({ -

    A soft classifier

    +

    Adding the Multiplier

    -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. +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. +$$

    -Suppose now that classes overlap in feature space, as shown in the -figure here. One way to deal with this problem before we define the -so-called kernel approach, is to allow a kind of slack in the sense -that we allow some points to be on the wrong side of the margin. - -

    -We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and -modify our previous equation +We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have $$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, $$ -to +and $$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. $$ -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. - -

    -Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of -misclassifications. +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. +$$

    @@ -211,7 +227,7 @@ misclassifications.

  • 26
  • 27
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs018.html b/doc/pub/week47/html/._week47-bs018.html index 950a843c5..f6fd45b55 100644 --- a/doc/pub/week47/html/._week47-bs018.html +++ b/doc/pub/week47/html/._week47-bs018.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,20 +161,13 @@ MathJax.Hub.Config({ -

    Soft optmization problem

    - -

    -This has in turn the consequences that we change our optmization problem to finding the minimum of +

    Setting up the Problem

    +In order to solve the above problem, we define the following Lagrangian function to be minimized $$ -{\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, +{\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], $$ -subject to -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, -$$ - -with the requirement \( \xi_i\geq 0 \). +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \).

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain @@ -176,33 +177,27 @@ $$ and $$ -\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +\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 +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, $$ -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 +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition $$ -\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. $$ -$$ -\gamma_i\xi_i = 0, -$$ -and -$$ -y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. -$$ +

      +
    1. 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.
    2. +
    3. 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 \).
    4. +
    + +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 \).

    @@ -229,6 +224,8 @@ $$

  • 26
  • 27
  • 28
  • +
  • ...
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs019.html b/doc/pub/week47/html/._week47-bs019.html index 5466386e7..43a03c61f 100644 --- a/doc/pub/week47/html/._week47-bs019.html +++ b/doc/pub/week47/html/._week47-bs019.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,76 +161,27 @@ MathJax.Hub.Config({ -

    Kernels and non-linearity

    +

    The problem to solve

    -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. +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, +$$ -

    -If our feature space is not easy to separate, as shown in the figure -here, we can achieve a better separation by introducing more complex -basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to -obtain a separation between the classes which is almost linear. +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}, +$$ -

    -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. +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] \). -

    - - -

    import numpy as np
    -import os
    -
    -np.random.seed(42)
    -
    -# To plot pretty figures
    -import matplotlib
    -import matplotlib.pyplot as plt
    -plt.rcParams['axes.labelsize'] = 14
    -plt.rcParams['xtick.labelsize'] = 12
    -plt.rcParams['ytick.labelsize'] = 12
    -
    -
    -from sklearn.svm import SVC
    -from sklearn import datasets
    -
    -
    -
    -X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
    -X2D = np.c_[X1D, X1D**2]
    -y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
    -
    -plt.figure(figsize=(11, 4))
    -
    -plt.subplot(121)
    -plt.grid(True, which='both')
    -plt.axhline(y=0, color='k')
    -plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
    -plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
    -plt.gca().get_yaxis().set_ticks([])
    -plt.xlabel(r"$x_1$", fontsize=20)
    -plt.axis([-4.5, 4.5, -0.2, 0.2])
    -
    -plt.subplot(122)
    -plt.grid(True, which='both')
    -plt.axhline(y=0, color='k')
    -plt.axvline(x=0, color='k')
    -plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
    -plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
    -plt.xlabel(r"$x_1$", fontsize=20)
    -plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
    -plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
    -plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
    -plt.axis([-4.5, 4.5, -1, 17])
    -plt.subplots_adjust(right=1)
    -plt.show()
    -

    @@ -247,6 +206,9 @@ plt.show()

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • ...
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs020.html b/doc/pub/week47/html/._week47-bs020.html index d569f9c6e..6ec6015e8 100644 --- a/doc/pub/week47/html/._week47-bs020.html +++ b/doc/pub/week47/html/._week47-bs020.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,47 +161,36 @@ MathJax.Hub.Config({ -

    The equations

    +

    The last steps

    -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) +Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute $$ -z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. $$ -

    -With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via $$ -{\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, +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, $$ -subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +resulting in $$ -y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, $$ -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 +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have $$ -K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +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). $$ -For the above example, the kernel reads +With our hyperplane coefficients we can use our classifier to assign any observation by simply using $$ -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. +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). $$ -

    -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 \). - -

    -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. +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier.

    @@ -218,6 +215,10 @@ the trouble of performing the transformation

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • ...
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs021.html b/doc/pub/week47/html/._week47-bs021.html index 3740fcf70..a7de379d9 100644 --- a/doc/pub/week47/html/._week47-bs021.html +++ b/doc/pub/week47/html/._week47-bs021.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,38 +161,37 @@ MathJax.Hub.Config({ -

    The problem to solve

    -Using our definition of the kernel We can rewrite again the Lagrangian -$$ -{\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, -$$ - -subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem -$$ -\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}, -$$ - -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 \). +

    A soft classifier

    -We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +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. + +

    +Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

    +We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation $$ -\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*} +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, $$ -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} \). +to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+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{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. + +

    +Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications.

    @@ -208,6 +215,11 @@ Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up.

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • ...
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs022.html b/doc/pub/week47/html/._week47-bs022.html index c94f39f0d..e22e4cf7a 100644 --- a/doc/pub/week47/html/._week47-bs022.html +++ b/doc/pub/week47/html/._week47-bs022.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,40 +161,56 @@ MathJax.Hub.Config({ -

    Different kernels and Mercer's theorem

    +

    Soft optmization problem

    -There are several popular kernels being used. These are - -

      -
    1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
    2. -
    3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
    4. -
    5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
    6. -
    7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
    8. -
    - -and many other ones. - -

    -An important theorem for us is Mercer's -theorem. 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 - +This has in turn the consequences that we change our optmization problem to finding the minimum of $$ -K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +{\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, $$ -

    -So you can use \( K \) as a kernel since you know \( \phi \) exists, even if -you don’t know what \( \phi \) is. +subject to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ + +with the requirement \( \xi_i\geq 0 \).

    -Note that some frequently used kernels (such as the Sigmoid kernel) -don’t respect all of Mercer’s conditions, yet they generally work well -in practice. +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{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ + +$$ +\gamma_i\xi_i = 0, +$$ + +and +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$

    @@ -209,6 +233,10 @@ in practice.

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs023.html b/doc/pub/week47/html/._week47-bs023.html index a13f59672..67433da6e 100644 --- a/doc/pub/week47/html/._week47-bs023.html +++ b/doc/pub/week47/html/._week47-bs023.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,15 +161,35 @@ MathJax.Hub.Config({ -

    The moons example

    +

    Kernels and non-linearity

    + +

    +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. + +

    +If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

    +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. +

    -

    from __future__ import division, print_function, unicode_literals
    +
    import numpy as np
    +import os
     
    -import numpy as np
     np.random.seed(42)
     
    +# To plot pretty figures
     import matplotlib
     import matplotlib.pyplot as plt
     plt.rcParams['axes.labelsize'] = 14
    @@ -174,176 +202,33 @@ plt.rcParams[&#
     
     
     
    -from sklearn.pipeline import Pipeline
    -from sklearn.preprocessing import StandardScaler
    -from sklearn.svm import LinearSVC
    -
    -
    -from sklearn.datasets import make_moons
    -X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
    -
    -def plot_dataset(X, y, axes):
    -    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
    -    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
    -    plt.axis(axes)
    -    plt.grid(True, which='both')
    -    plt.xlabel(r"$x_1$", fontsize=20)
    -    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
    -
    -plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    -plt.show()
    -
    -from sklearn.datasets import make_moons
    -from sklearn.pipeline import Pipeline
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -polynomial_svm_clf = Pipeline([
    -        ("poly_features", PolynomialFeatures(degree=3)),
    -        ("scaler", StandardScaler()),
    -        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
    -    ])
    -
    -polynomial_svm_clf.fit(X, y)
    -
    -def plot_predictions(clf, axes):
    -    x0s = np.linspace(axes[0], axes[1], 100)
    -    x1s = np.linspace(axes[2], axes[3], 100)
    -    x0, x1 = np.meshgrid(x0s, x1s)
    -    X = np.c_[x0.ravel(), x1.ravel()]
    -    y_pred = clf.predict(X).reshape(x0.shape)
    -    y_decision = clf.decision_function(X).reshape(x0.shape)
    -    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
    -    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
    -
    -plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
    -plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    -
    -plt.show()
    -
    -
    -from sklearn.svm import SVC
    -
    -poly_kernel_svm_clf = Pipeline([
    -        ("scaler", StandardScaler()),
    -        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
    -    ])
    -poly_kernel_svm_clf.fit(X, y)
    -
    -poly100_kernel_svm_clf = Pipeline([
    -        ("scaler", StandardScaler()),
    -        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
    -    ])
    -poly100_kernel_svm_clf.fit(X, y)
    +X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
    +X2D = np.c_[X1D, X1D**2]
    +y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
     
     plt.figure(figsize=(11, 4))
     
     plt.subplot(121)
    -plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
    -plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    -plt.title(r"$d=3, r=1, C=5$", fontsize=18)
    -
    -plt.subplot(122)
    -plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
    -plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    -plt.title(r"$d=10, r=100, C=5$", fontsize=18)
    -
    -plt.show()
    -
    -def gaussian_rbf(x, landmark, gamma):
    -    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
    -
    -gamma = 0.3
    -
    -x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
    -x2s = gaussian_rbf(x1s, -2, gamma)
    -x3s = gaussian_rbf(x1s, 1, gamma)
    -
    -XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
    -yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
    -
    -plt.figure(figsize=(11, 4))
    -
    -plt.subplot(121)
    -plt.grid(True, which='both')
    +plt.grid(True, which='both')
     plt.axhline(y=0, color='k')
    -plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
    -plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
    -plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
    -plt.plot(x1s, x2s, "g--")
    -plt.plot(x1s, x3s, "b:")
    -plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
    +plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
    +plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
    +plt.gca().get_yaxis().set_ticks([])
     plt.xlabel(r"$x_1$", fontsize=20)
    -plt.ylabel(r"Similarity", fontsize=14)
    -plt.annotate(r'$\mathbf{x}$',
    -             xy=(X1D[3, 0], 0),
    -             xytext=(-0.5, 0.20),
    -             ha="center",
    -             arrowprops=dict(facecolor='black', shrink=0.1),
    -             fontsize=18,
    -            )
    -plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
    -plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
    -plt.axis([-4.5, 4.5, -0.1, 1.1])
    +plt.axis([-4.5, 4.5, -0.2, 0.2])
     
     plt.subplot(122)
    -plt.grid(True, which='both')
    +plt.grid(True, which='both')
     plt.axhline(y=0, color='k')
     plt.axvline(x=0, color='k')
    -plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
    -plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
    -plt.xlabel(r"$x_2$", fontsize=20)
    -plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
    -plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
    -             xy=(XK[3, 0], XK[3, 1]),
    -             xytext=(0.65, 0.50),
    -             ha="center",
    -             arrowprops=dict(facecolor='black', shrink=0.1),
    -             fontsize=18,
    -            )
    -plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
    -plt.axis([-0.1, 1.1, -0.1, 1.1])
    -    
    +plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
    +plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
    +plt.xlabel(r"$x_1$", fontsize=20)
    +plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
    +plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
    +plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
    +plt.axis([-4.5, 4.5, -1, 17])
     plt.subplots_adjust(right=1)
    -
    -plt.show()
    -
    -
    -x1_example = X1D[3, 0]
    -for landmark in (-2, 1):
    -    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
    -    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
    -
    -rbf_kernel_svm_clf = Pipeline([
    -        ("scaler", StandardScaler()),
    -        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
    -    ])
    -rbf_kernel_svm_clf.fit(X, y)
    -
    -
    -from sklearn.svm import SVC
    -
    -gamma1, gamma2 = 0.1, 5
    -C1, C2 = 0.001, 1000
    -hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
    -
    -svm_clfs = []
    -for gamma, C in hyperparams:
    -    rbf_kernel_svm_clf = Pipeline([
    -            ("scaler", StandardScaler()),
    -            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
    -        ])
    -    rbf_kernel_svm_clf.fit(X, y)
    -    svm_clfs.append(rbf_kernel_svm_clf)
    -
    -plt.figure(figsize=(11, 7))
    -
    -for i, svm_clf in enumerate(svm_clfs):
    -    plt.subplot(221 + i)
    -    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
    -    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    -    gamma, C = hyperparams[i]
    -    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
    -
     plt.show()
     

    @@ -366,6 +251,10 @@ plt.show()

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs024.html b/doc/pub/week47/html/._week47-bs024.html index 250925cbc..b33a5f4b5 100644 --- a/doc/pub/week47/html/._week47-bs024.html +++ b/doc/pub/week47/html/._week47-bs024.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,27 +161,47 @@ MathJax.Hub.Config({ -

    Mathematical optimization of convex functions

    +

    The equations

    -A mathematical (quadratic) optimization problem, or just optimization problem, has the form +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) $$ -\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*} +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). $$ -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. +

    +With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +$$ +{\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, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ + +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 +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +For the above example, the kernel reads +$$ +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. +$$

    -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. +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 \).

    -Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. +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.

    @@ -194,6 +222,10 @@ Convex optimization problems play a central role in applied mathematics and we r

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs025.html b/doc/pub/week47/html/._week47-bs025.html index f36eae7cd..b109dfad6 100644 --- a/doc/pub/week47/html/._week47-bs025.html +++ b/doc/pub/week47/html/._week47-bs025.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,28 +161,38 @@ MathJax.Hub.Config({ -

    How do we solve these problems?

    +

    The problem to solve

    +Using our definition of the kernel We can rewrite again the Lagrangian +$$ +{\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, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +$$ +\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}, +$$ + +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 \).

    -If we use Python as programming language and wish to venture beyond -scikit-learn, tensorflow 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. +We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +$$ +\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*} +$$ -

    -The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as - -

    - - -

    import numpy
    -import cvxopt
    -
    -

    -This will make our life much easier. You don't need t write your own optimizer. +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} \).

    @@ -194,6 +212,10 @@ This will make our life much easier. You don't need t write your own optimizer.

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs026.html b/doc/pub/week47/html/._week47-bs026.html index 937c97777..43a5e09c6 100644 --- a/doc/pub/week47/html/._week47-bs026.html +++ b/doc/pub/week47/html/._week47-bs026.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,71 +161,41 @@ MathJax.Hub.Config({ -

    A simple example

    +

    Different kernels and Mercer's theorem

    -We remind ourselves about the general problem we want to solve +There are several popular kernels being used. These are + +

      +
    1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
    2. +
    3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
    4. +
    5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
    6. +
    7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
    8. +
    + +and many other ones. + +

    +An important theorem for us is Mercer's +theorem. 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 + $$ -\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*} +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). $$

    -Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem -$$ -\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*} -$$ - -The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) -$$ -\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}. -$$ - -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 -$$ -\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}. -$$ - -We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix -$$ -\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} -$$ - -is clearly positive semi-definite (all eigenvalues larger or equal zero). -Finally, the vector \( \boldsymbol{h} \) is defined as -$$ -\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. -$$ +So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is.

    -Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero -The following code solves the equations for us -

    +Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. - -

    # Import the necessary packages
    -import numpy
    -from cvxopt import matrix
    -from cvxopt import solvers
    -P = matrix(numpy.diag([1,0]), tc=’d’)
    -q = matrix(numpy.array([3,4]), tc=’d’)
    -G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)
    -h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)
    -# Construct the QP, invoke solver
    -sol = solvers.qp(P,q,G,h)
    -# Extract optimal value and solution
    -sol[’x’] 
    -sol[’primal objective’]
    -

    @@ -235,6 +213,10 @@ sol[’primal objective’]

  • 26
  • 27
  • 28
  • +
  • 29
  • +
  • 30
  • +
  • 31
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/._week47-bs027.html b/doc/pub/week47/html/._week47-bs027.html index f92cb624d..4891a99d3 100644 --- a/doc/pub/week47/html/._week47-bs027.html +++ b/doc/pub/week47/html/._week47-bs027.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -153,28 +161,200 @@ MathJax.Hub.Config({ -

    Back to the more realistic cases

    - -

    -We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have -$$ -\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_2K(\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{I}\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] \). -With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). - -

    -code will be added - +

    The moons example

    + +

    from __future__ import division, print_function, unicode_literals
    +
    +import numpy as np
    +np.random.seed(42)
    +
    +import matplotlib
    +import matplotlib.pyplot as plt
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
    +
    +
    +from sklearn.svm import SVC
    +from sklearn import datasets
    +
    +
    +
    +from sklearn.pipeline import Pipeline
    +from sklearn.preprocessing import StandardScaler
    +from sklearn.svm import LinearSVC
    +
    +
    +from sklearn.datasets import make_moons
    +X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
    +
    +def plot_dataset(X, y, axes):
    +    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
    +    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
    +    plt.axis(axes)
    +    plt.grid(True, which='both')
    +    plt.xlabel(r"$x_1$", fontsize=20)
    +    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
    +
    +plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    +plt.show()
    +
    +from sklearn.datasets import make_moons
    +from sklearn.pipeline import Pipeline
    +from sklearn.preprocessing import PolynomialFeatures
    +
    +polynomial_svm_clf = Pipeline([
    +        ("poly_features", PolynomialFeatures(degree=3)),
    +        ("scaler", StandardScaler()),
    +        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
    +    ])
    +
    +polynomial_svm_clf.fit(X, y)
    +
    +def plot_predictions(clf, axes):
    +    x0s = np.linspace(axes[0], axes[1], 100)
    +    x1s = np.linspace(axes[2], axes[3], 100)
    +    x0, x1 = np.meshgrid(x0s, x1s)
    +    X = np.c_[x0.ravel(), x1.ravel()]
    +    y_pred = clf.predict(X).reshape(x0.shape)
    +    y_decision = clf.decision_function(X).reshape(x0.shape)
    +    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
    +    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
    +
    +plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
    +plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    +
    +plt.show()
    +
    +
    +from sklearn.svm import SVC
    +
    +poly_kernel_svm_clf = Pipeline([
    +        ("scaler", StandardScaler()),
    +        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
    +    ])
    +poly_kernel_svm_clf.fit(X, y)
    +
    +poly100_kernel_svm_clf = Pipeline([
    +        ("scaler", StandardScaler()),
    +        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
    +    ])
    +poly100_kernel_svm_clf.fit(X, y)
    +
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
    +plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    +plt.title(r"$d=3, r=1, C=5$", fontsize=18)
    +
    +plt.subplot(122)
    +plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
    +plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    +plt.title(r"$d=10, r=100, C=5$", fontsize=18)
    +
    +plt.show()
    +
    +def gaussian_rbf(x, landmark, gamma):
    +    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
    +
    +gamma = 0.3
    +
    +x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
    +x2s = gaussian_rbf(x1s, -2, gamma)
    +x3s = gaussian_rbf(x1s, 1, gamma)
    +
    +XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
    +yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
    +
    +plt.figure(figsize=(11, 4))
    +
    +plt.subplot(121)
    +plt.grid(True, which='both')
    +plt.axhline(y=0, color='k')
    +plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
    +plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
    +plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
    +plt.plot(x1s, x2s, "g--")
    +plt.plot(x1s, x3s, "b:")
    +plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
    +plt.xlabel(r"$x_1$", fontsize=20)
    +plt.ylabel(r"Similarity", fontsize=14)
    +plt.annotate(r'$\mathbf{x}$',
    +             xy=(X1D[3, 0], 0),
    +             xytext=(-0.5, 0.20),
    +             ha="center",
    +             arrowprops=dict(facecolor='black', shrink=0.1),
    +             fontsize=18,
    +            )
    +plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
    +plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
    +plt.axis([-4.5, 4.5, -0.1, 1.1])
    +
    +plt.subplot(122)
    +plt.grid(True, which='both')
    +plt.axhline(y=0, color='k')
    +plt.axvline(x=0, color='k')
    +plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
    +plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
    +plt.xlabel(r"$x_2$", fontsize=20)
    +plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
    +plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
    +             xy=(XK[3, 0], XK[3, 1]),
    +             xytext=(0.65, 0.50),
    +             ha="center",
    +             arrowprops=dict(facecolor='black', shrink=0.1),
    +             fontsize=18,
    +            )
    +plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
    +plt.axis([-0.1, 1.1, -0.1, 1.1])
    +    
    +plt.subplots_adjust(right=1)
    +
    +plt.show()
    +
    +
    +x1_example = X1D[3, 0]
    +for landmark in (-2, 1):
    +    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
    +    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
    +
    +rbf_kernel_svm_clf = Pipeline([
    +        ("scaler", StandardScaler()),
    +        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
    +    ])
    +rbf_kernel_svm_clf.fit(X, y)
    +
    +
    +from sklearn.svm import SVC
    +
    +gamma1, gamma2 = 0.1, 5
    +C1, C2 = 0.001, 1000
    +hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
    +
    +svm_clfs = []
    +for gamma, C in hyperparams:
    +    rbf_kernel_svm_clf = Pipeline([
    +            ("scaler", StandardScaler()),
    +            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
    +        ])
    +    rbf_kernel_svm_clf.fit(X, y)
    +    svm_clfs.append(rbf_kernel_svm_clf)
    +
    +plt.figure(figsize=(11, 7))
    +
    +for i, svm_clf in enumerate(svm_clfs):
    +    plt.subplot(221 + i)
    +    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
    +    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    +    gamma, C = hyperparams[i]
    +    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
    +
    +plt.show()
    +
    +

      @@ -190,6 +370,11 @@ With the slack constants this leads to the additional constraint \( 0\leq \lamb
    • 26
    • 27
    • 28
    • +
    • 29
    • +
    • 30
    • +
    • 31
    • +
    • 32
    • +
    • »
    diff --git a/doc/pub/week47/html/week47-bs.html b/doc/pub/week47/html/week47-bs.html index 98a4b1977..e96c3a089 100644 --- a/doc/pub/week47/html/week47-bs.html +++ b/doc/pub/week47/html/week47-bs.html @@ -41,39 +41,43 @@ Automatically generated HTML file from DocOnce source @@ -111,33 +115,37 @@ MathJax.Hub.Config({ @@ -172,7 +180,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Sep 16, 2020

    +

    Nov 19, 2020


    @@ -196,7 +204,7 @@ MathJax.Hub.Config({

  • 9
  • 10
  • ...
  • -
  • 28
  • +
  • 32
  • »
  • diff --git a/doc/pub/week47/html/week47-reveal.html b/doc/pub/week47/html/week47-reveal.html index c13cb8752..b29673c88 100644 --- a/doc/pub/week47/html/week47-reveal.html +++ b/doc/pub/week47/html/week47-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

     
    -

    Sep 16, 2020

    +

    Nov 19, 2020


    @@ -159,7 +159,58 @@ MathJax.Hub.Config({

    -

    Support Vector Machines, overarching aims

    +

    Overview of week 46

    + +
      +

    • Thursday: Support Vector Machines, classification and regression.
    • +

    • Friday: Workshop on project 3 (first lecture), Support Vector Machines (second Lecture)
    • +
    +

    + +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. + +

    +See overview video on Support Vector Machines. See also this video. +

    + + +
    +

    Thursday

    + +

    +We start with our final topic this semester, Support Vector Machines +

    + + +
    +

    Friday

    + +

    +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. +

    + + +
    +

    Workshop plan Friday (first lecture)

    + +

    +Here are the various projects that will be presented during the first lecture (and possibly parts of the second lecture as well). Titles are tentative. Talks are approx 5-10 mins with roughly 5 minutes for discussions. + +

      +

    • Maria Emine Nylund: Lego Bricks Classifier
    • +

    • Fabio Rodrigues Pereira: Financial Machine Learning
    • +

    • Markus Borud Pettersen: Machine Learning and Brain Grid Cells
    • +

    • _Jing Sun and Endrias Getachew Asgedom: Machine learning-based approaches to denoising microseismic data
    • +

    • Felicia Jacobsen: Analysis of Breast Cancer Data
    • +

    • Simon Elias Schrader: Predicting atomization energies of molecules
    • +

    • Varvara Bazilova and Sergio Andres Diaz Mesa: Glacier Mapping and Machine Learning
    • +

    • Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: Gamma ray signals stemming from dark matter in the galactic center
    • +
    +
    + + +
    +

    Support Vector Machines, overarching aims

    A Support Vector Machine (SVM) is a very powerful and versatile @@ -173,7 +224,7 @@ medium-sized datasets.

    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). +the two classes.

    The basic mathematics behind the SVM is however less familiar to most of us. @@ -192,7 +243,7 @@ unlikely that we can separate classes easily by say straight lines.

    -

    Hyperplanes and all that

    +

    Hyperplanes and all that

    The theory behind support vector machines (SVM hereafter) is based on @@ -245,9 +296,9 @@ lin_clf.fit(X_scaled, y) svm_clf.fit(X_scaled, y) sgd_clf.fit(X_scaled, y) -print("LinearSVC: ", lin_clf.intercept_, lin_clf.coef_) -print("SVC: ", svm_clf.intercept_, svm_clf.coef_) -print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_) +print("LinearSVC: ", lin_clf.intercept_, lin_clf.coef_) +print("SVC: ", svm_clf.intercept_, svm_clf.coef_) +print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_) # Compute the slope and bias of each decision boundary w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1] @@ -280,7 +331,7 @@ plt.show()

    -

    What is a hyperplane?

    +

    What is a hyperplane?

    The aim of the SVM algorithm is to find a hyperplane in a @@ -315,11 +366,11 @@ $$

    -

    A \( p \)-dimensional space of features

    +

    A \( p \)-dimensional space of features

    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 +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. @@ -367,7 +418,7 @@ When we try to separate hyperplanes, if it exists, we can use it to construct a

    -

    The two-dimensional case

    +

    The two-dimensional case

    Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional @@ -394,7 +445,7 @@ for our data sample.

    -

    Getting into the details

    +

    Getting into the details

    Let us define the function @@ -420,7 +471,7 @@ $$

    -

    First attempt at a minimization approach

    +

    First attempt at a minimization approach

    How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could @@ -451,7 +502,7 @@ $$

    -

    Solving the equations

    +

    Solving the equations

    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 @@ -473,7 +524,7 @@ where \( \eta \) is our by now well-known learning rate.

    -

    Code Example

    +

    Code Example

    The equations we discussed above can be coded rather easily (the @@ -488,7 +539,7 @@ regression). We are going to set up a simple case with two classes only and we w

    -

    Problems with the Simpler Approach

    +

    Problems with the Simpler Approach

    There are however problems with this approach, although it looks @@ -504,7 +555,7 @@ at all.

    -

    A better approach

    +

    A better approach

    A better approach is rather to try to define a large margin between @@ -554,7 +605,7 @@ about Lagrangian multipliers.

    -

    A quick Reminder on Lagrangian Multipliers

    +

    A quick Reminder on Lagrangian Multipliers

    Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an @@ -616,7 +667,7 @@ Then \( dz \) is no longer arbitrary.

    -

    Adding the Multiplier

    +

    Adding the Multiplier

    However, we can add to @@ -671,7 +722,7 @@ $$

    -

    Setting up the Problem

    +

    Setting up the Problem

    In order to solve the above problem, we define the following Lagrangian function to be minimized

     
    $$ @@ -723,7 +774,7 @@ When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support

    -

    The problem to solve

    +

    The problem to solve

    We can rewrite @@ -751,7 +802,7 @@ subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vec

    -

    The last steps

    +

    The last steps

    Solving the above problem, yields the values of \( \lambda_i \). @@ -795,7 +846,7 @@ Below we discuss how to find the optimal values of \( \lambda_i \). Before we pr

    -

    A soft classifier

    +

    A soft classifier

    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. @@ -834,7 +885,7 @@ misclassifications.

    -

    Soft optmization problem

    +

    Soft optmization problem

    This has in turn the consequences that we change our optmization problem to finding the minimum of @@ -906,7 +957,7 @@ $$

    -

    Kernels and non-linearity

    +

    Kernels and non-linearity

    The cases we have studied till now, were all characterized by two classes @@ -954,7 +1005,7 @@ y = np.array([0, 11, 4)) plt.subplot(121) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs") plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^") @@ -963,7 +1014,7 @@ plt.xlabel(r"$x_1$", fontsize=4.5, 4.5, -0.2, 0.2]) plt.subplot(122) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs") @@ -980,7 +1031,7 @@ plt.show()

    -

    The equations

    +

    The equations

    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) @@ -1035,7 +1086,7 @@ the trouble of performing the transformation

    -

    The problem to solve

    +

    The problem to solve

    Using our definition of the kernel We can rewrite again the Lagrangian

     
    $$ @@ -1077,7 +1128,7 @@ Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up.

    -

    Different kernels and Mercer's theorem

    +

    Different kernels and Mercer's theorem

    There are several popular kernels being used. These are @@ -1118,7 +1169,7 @@ in practice.

    -

    The moons example

    +

    The moons example

    @@ -1151,7 +1202,7 @@ X, y = make_moons(n_samples=100, noise=0][y==0], X[:, 1][y==0], "bs") plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^") plt.axis(axes) - plt.grid(True, which='both') + plt.grid(True, which='both') plt.xlabel(r"$x_1$", fontsize=20) plt.ylabel(r"$x_2$", fontsize=20, rotation=0) @@ -1229,7 +1280,7 @@ yk = np.array([0, 11, 4)) plt.subplot(121) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red") plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs") @@ -1251,7 +1302,7 @@ plt.text(1, 0.9 plt.axis([-4.5, 4.5, -0.1, 1.1]) plt.subplot(122) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs") @@ -1276,7 +1327,7 @@ plt.show() x1_example = X1D[3, 0] for landmark in (-2, 1): k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma) - print("Phi({}, {}) = {}".format(x1_example, landmark, k)) + print("Phi({}, {}) = {}".format(x1_example, landmark, k)) rbf_kernel_svm_clf = Pipeline([ ("scaler", StandardScaler()), @@ -1315,7 +1366,7 @@ plt.show()

    -

    Mathematical optimization of convex functions

    +

    Mathematical optimization of convex functions

    A mathematical (quadratic) optimization problem, or just optimization problem, has the form @@ -1342,7 +1393,7 @@ Convex optimization problems play a central role in applied mathematics and we r

    -

    How do we solve these problems?

    +

    How do we solve these problems?

    If we use Python as programming language and wish to venture beyond @@ -1368,7 +1419,7 @@ This will make our life much easier. You don't need t write your own optimizer.

    -

    A simple example

    +

    A simple example

    We remind ourselves about the general problem we want to solve @@ -1449,7 +1500,7 @@ sol[primal obj

    -

    Back to the more realistic cases

    +

    Back to the more realistic cases

    We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have @@ -1467,9 +1518,6 @@ $$ 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] \). With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). - -

    -code will be added

    diff --git a/doc/pub/week47/html/week47-solarized.html b/doc/pub/week47/html/week47-solarized.html index f75482c1e..d63bf6582 100644 --- a/doc/pub/week47/html/week47-solarized.html +++ b/doc/pub/week47/html/week47-solarized.html @@ -35,39 +35,43 @@ div { text-align: justify; text-justify: inter-word; } @@ -109,12 +113,61 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Sep 16, 2020

    +

    Nov 19, 2020












    -

    Support Vector Machines, overarching aims

    +

    Overview of week 46

    + +
      +
    • Thursday: Support Vector Machines, classification and regression.
    • +
    • Friday: Workshop on project 3 (first lecture), Support Vector Machines (second Lecture)
    • +
    + +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. + +

    +See overview video on Support Vector Machines. See also this video. + +

    +









    + +

    Thursday

    + +

    +We start with our final topic this semester, Support Vector Machines + +

    +









    + +

    Friday

    + +

    +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. + +

    +









    + +

    Workshop plan Friday (first lecture)

    + +

    +Here are the various projects that will be presented during the first lecture (and possibly parts of the second lecture as well). Titles are tentative. Talks are approx 5-10 mins with roughly 5 minutes for discussions. + +

      +
    • Maria Emine Nylund: Lego Bricks Classifier
    • +
    • Fabio Rodrigues Pereira: Financial Machine Learning
    • +
    • Markus Borud Pettersen: Machine Learning and Brain Grid Cells
    • +
    • _Jing Sun and Endrias Getachew Asgedom: Machine learning-based approaches to denoising microseismic data
    • +
    • Felicia Jacobsen: Analysis of Breast Cancer Data
    • +
    • Simon Elias Schrader: Predicting atomization energies of molecules
    • +
    • Varvara Bazilova and Sergio Andres Diaz Mesa: Glacier Mapping and Machine Learning
    • +
    • Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: Gamma ray signals stemming from dark matter in the galactic center
    • +
    + +









    + +

    Support Vector Machines, overarching aims

    A Support Vector Machine (SVM) is a very powerful and versatile @@ -128,7 +181,7 @@ medium-sized datasets.

    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). +the two classes.

    The basic mathematics behind the SVM is however less familiar to most of us. @@ -147,7 +200,7 @@ unlikely that we can separate classes easily by say straight lines.











    -

    Hyperplanes and all that

    +

    Hyperplanes and all that

    The theory behind support vector machines (SVM hereafter) is based on @@ -200,9 +253,9 @@ lin_clf.fit(X_scaled, y) svm_clf.fit(X_scaled, y) sgd_clf.fit(X_scaled, y) -print("LinearSVC: ", lin_clf.intercept_, lin_clf.coef_) -print("SVC: ", svm_clf.intercept_, svm_clf.coef_) -print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_) +print("LinearSVC: ", lin_clf.intercept_, lin_clf.coef_) +print("SVC: ", svm_clf.intercept_, svm_clf.coef_) +print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_) # Compute the slope and bias of each decision boundary w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1] @@ -234,7 +287,7 @@ plt.show()











    -

    What is a hyperplane?

    +

    What is a hyperplane?

    The aim of the SVM algorithm is to find a hyperplane in a @@ -265,11 +318,11 @@ $$











    -

    A \( p \)-dimensional space of features

    +

    A \( p \)-dimensional space of features

    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 +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. $$ @@ -307,7 +360,7 @@ When we try to separate hyperplanes, if it exists, we can use it to construct a

    -

    The two-dimensional case

    +

    The two-dimensional case

    Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional @@ -334,7 +387,7 @@ for our data sample.











    -

    Getting into the details

    +

    Getting into the details

    Let us define the function @@ -356,7 +409,7 @@ $$











    -

    First attempt at a minimization approach

    +

    First attempt at a minimization approach

    How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could @@ -381,7 +434,7 @@ $$











    -

    Solving the equations

    +

    Solving the equations

    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 @@ -399,7 +452,7 @@ where \( \eta \) is our by now well-known learning rate.











    -

    Code Example

    +

    Code Example

    The equations we discussed above can be coded rather easily (the @@ -413,7 +466,7 @@ regression). We are going to set up a simple case with two classes only and we w











    -

    Problems with the Simpler Approach

    +

    Problems with the Simpler Approach

    There are however problems with this approach, although it looks @@ -429,7 +482,7 @@ at all.











    -

    A better approach

    +

    A better approach

    A better approach is rather to try to define a large margin between @@ -471,7 +524,7 @@ about Lagrangian multipliers.











    -

    A quick Reminder on Lagrangian Multipliers

    +

    A quick Reminder on Lagrangian Multipliers

    Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an @@ -521,7 +574,7 @@ Then \( dz \) is no longer arbitrary.











    -

    Adding the Multiplier

    +

    Adding the Multiplier

    However, we can add to @@ -564,7 +617,7 @@ $$











    -

    Setting up the Problem

    +

    Setting up the Problem

    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], @@ -605,7 +658,7 @@ When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support











    -

    The problem to solve

    +

    The problem to solve

    We can rewrite @@ -629,7 +682,7 @@ subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vec











    -

    The last steps

    +

    The last steps

    Solving the above problem, yields the values of \( \lambda_i \). @@ -663,7 +716,7 @@ Below we discuss how to find the optimal values of \( \lambda_i \). Before we pr











    -

    A soft classifier

    +

    A soft classifier

    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. @@ -698,7 +751,7 @@ misclassifications.











    -

    Soft optmization problem

    +

    Soft optmization problem

    This has in turn the consequences that we change our optmization problem to finding the minimum of @@ -752,7 +805,7 @@ $$











    -

    Kernels and non-linearity

    +

    Kernels and non-linearity

    The cases we have studied till now, were all characterized by two classes @@ -800,7 +853,7 @@ y = np.array([0, 11, 4)) plt.subplot(121) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs") plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^") @@ -809,7 +862,7 @@ plt.xlabel(r"$x_1$", fontsize=4.5, 4.5, -0.2, 0.2]) plt.subplot(122) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs") @@ -825,7 +878,7 @@ plt.show()











    -

    The equations

    +

    The equations

    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) @@ -870,7 +923,7 @@ the trouble of performing the transformation











    -

    The problem to solve

    +

    The problem to solve

    Using our definition of the kernel We can rewrite again the Lagrangian $$ {\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, @@ -906,7 +959,7 @@ Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up.











    -

    Different kernels and Mercer's theorem

    +

    Different kernels and Mercer's theorem

    There are several popular kernels being used. These are @@ -944,7 +997,7 @@ in practice.











    -

    The moons example

    +

    The moons example

    @@ -977,7 +1030,7 @@ X, y = make_moons(n_samples=100, noise=0][y==0], X[:, 1][y==0], "bs") plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^") plt.axis(axes) - plt.grid(True, which='both') + plt.grid(True, which='both') plt.xlabel(r"$x_1$", fontsize=20) plt.ylabel(r"$x_2$", fontsize=20, rotation=0) @@ -1055,7 +1108,7 @@ yk = np.array([0, 11, 4)) plt.subplot(121) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red") plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs") @@ -1077,7 +1130,7 @@ plt.text(1, 0.9 plt.axis([-4.5, 4.5, -0.1, 1.1]) plt.subplot(122) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs") @@ -1102,7 +1155,7 @@ plt.show() x1_example = X1D[3, 0] for landmark in (-2, 1): k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma) - print("Phi({}, {}) = {}".format(x1_example, landmark, k)) + print("Phi({}, {}) = {}".format(x1_example, landmark, k)) rbf_kernel_svm_clf = Pipeline([ ("scaler", StandardScaler()), @@ -1140,7 +1193,7 @@ plt.show()











    -

    Mathematical optimization of convex functions

    +

    Mathematical optimization of convex functions

    A mathematical (quadratic) optimization problem, or just optimization problem, has the form @@ -1165,7 +1218,7 @@ Convex optimization problems play a central role in applied mathematics and we r











    -

    How do we solve these problems?

    +

    How do we solve these problems?

    If we use Python as programming language and wish to venture beyond @@ -1191,7 +1244,7 @@ This will make our life much easier. You don't need t write your own optimizer.











    -

    A simple example

    +

    A simple example

    We remind ourselves about the general problem we want to solve @@ -1259,7 +1312,7 @@ sol[primal obj











    -

    Back to the more realistic cases

    +

    Back to the more realistic cases

    We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have @@ -1276,9 +1329,6 @@ subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vec \( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). -

    -code will be added -

    diff --git a/doc/pub/week47/html/week47.html b/doc/pub/week47/html/week47.html index a08ae3053..922be221c 100644 --- a/doc/pub/week47/html/week47.html +++ b/doc/pub/week47/html/week47.html @@ -40,39 +40,43 @@ div { text-align: justify; text-justify: inter-word; } @@ -114,12 +118,61 @@ MathJax.Hub.Config({

    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Sep 16, 2020

    +

    Nov 19, 2020












    -

    Support Vector Machines, overarching aims

    +

    Overview of week 46

    + +
      +
    • Thursday: Support Vector Machines, classification and regression.
    • +
    • Friday: Workshop on project 3 (first lecture), Support Vector Machines (second Lecture)
    • +
    + +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. + +

    +See overview video on Support Vector Machines. See also this video. + +

    +









    + +

    Thursday

    + +

    +We start with our final topic this semester, Support Vector Machines + +

    +









    + +

    Friday

    + +

    +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. + +

    +









    + +

    Workshop plan Friday (first lecture)

    + +

    +Here are the various projects that will be presented during the first lecture (and possibly parts of the second lecture as well). Titles are tentative. Talks are approx 5-10 mins with roughly 5 minutes for discussions. + +

      +
    • Maria Emine Nylund: Lego Bricks Classifier
    • +
    • Fabio Rodrigues Pereira: Financial Machine Learning
    • +
    • Markus Borud Pettersen: Machine Learning and Brain Grid Cells
    • +
    • _Jing Sun and Endrias Getachew Asgedom: Machine learning-based approaches to denoising microseismic data
    • +
    • Felicia Jacobsen: Analysis of Breast Cancer Data
    • +
    • Simon Elias Schrader: Predicting atomization energies of molecules
    • +
    • Varvara Bazilova and Sergio Andres Diaz Mesa: Glacier Mapping and Machine Learning
    • +
    • Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: Gamma ray signals stemming from dark matter in the galactic center
    • +
    + +









    + +

    Support Vector Machines, overarching aims

    A Support Vector Machine (SVM) is a very powerful and versatile @@ -133,7 +186,7 @@ medium-sized datasets.

    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). +the two classes.

    The basic mathematics behind the SVM is however less familiar to most of us. @@ -152,7 +205,7 @@ unlikely that we can separate classes easily by say straight lines.











    -

    Hyperplanes and all that

    +

    Hyperplanes and all that

    The theory behind support vector machines (SVM hereafter) is based on @@ -205,9 +258,9 @@ lin_clf.fit(X_scaled, y) svm_clf.fit(X_scaled, y) sgd_clf.fit(X_scaled, y) -print("LinearSVC: ", lin_clf.intercept_, lin_clf.coef_) -print("SVC: ", svm_clf.intercept_, svm_clf.coef_) -print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_) +print("LinearSVC: ", lin_clf.intercept_, lin_clf.coef_) +print("SVC: ", svm_clf.intercept_, svm_clf.coef_) +print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_) # Compute the slope and bias of each decision boundary w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1] @@ -239,7 +292,7 @@ plt.show()











    -

    What is a hyperplane?

    +

    What is a hyperplane?

    The aim of the SVM algorithm is to find a hyperplane in a @@ -270,11 +323,11 @@ $$











    -

    A \( p \)-dimensional space of features

    +

    A \( p \)-dimensional space of features

    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 +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. $$ @@ -312,7 +365,7 @@ When we try to separate hyperplanes, if it exists, we can use it to construct a

    -

    The two-dimensional case

    +

    The two-dimensional case

    Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional @@ -339,7 +392,7 @@ for our data sample.











    -

    Getting into the details

    +

    Getting into the details

    Let us define the function @@ -361,7 +414,7 @@ $$











    -

    First attempt at a minimization approach

    +

    First attempt at a minimization approach

    How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could @@ -386,7 +439,7 @@ $$











    -

    Solving the equations

    +

    Solving the equations

    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 @@ -404,7 +457,7 @@ where \( \eta \) is our by now well-known learning rate.











    -

    Code Example

    +

    Code Example

    The equations we discussed above can be coded rather easily (the @@ -418,7 +471,7 @@ regression). We are going to set up a simple case with two classes only and we w











    -

    Problems with the Simpler Approach

    +

    Problems with the Simpler Approach

    There are however problems with this approach, although it looks @@ -434,7 +487,7 @@ at all.











    -

    A better approach

    +

    A better approach

    A better approach is rather to try to define a large margin between @@ -476,7 +529,7 @@ about Lagrangian multipliers.











    -

    A quick Reminder on Lagrangian Multipliers

    +

    A quick Reminder on Lagrangian Multipliers

    Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an @@ -526,7 +579,7 @@ Then \( dz \) is no longer arbitrary.











    -

    Adding the Multiplier

    +

    Adding the Multiplier

    However, we can add to @@ -569,7 +622,7 @@ $$











    -

    Setting up the Problem

    +

    Setting up the Problem

    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], @@ -610,7 +663,7 @@ When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support











    -

    The problem to solve

    +

    The problem to solve

    We can rewrite @@ -634,7 +687,7 @@ subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vec











    -

    The last steps

    +

    The last steps

    Solving the above problem, yields the values of \( \lambda_i \). @@ -668,7 +721,7 @@ Below we discuss how to find the optimal values of \( \lambda_i \). Before we pr











    -

    A soft classifier

    +

    A soft classifier

    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. @@ -703,7 +756,7 @@ misclassifications.











    -

    Soft optmization problem

    +

    Soft optmization problem

    This has in turn the consequences that we change our optmization problem to finding the minimum of @@ -757,7 +810,7 @@ $$











    -

    Kernels and non-linearity

    +

    Kernels and non-linearity

    The cases we have studied till now, were all characterized by two classes @@ -805,7 +858,7 @@ y = np.a plt.figure(figsize=(11, 4)) plt.subplot(121) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs") plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^") @@ -814,7 +867,7 @@ plt.xlabel(r&qu plt.axis([-4.5, 4.5, -0.2, 0.2]) plt.subplot(122) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs") @@ -830,7 +883,7 @@ plt.show()











    -

    The equations

    +

    The equations

    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) @@ -875,7 +928,7 @@ the trouble of performing the transformation











    -

    The problem to solve

    +

    The problem to solve

    Using our definition of the kernel We can rewrite again the Lagrangian $$ {\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, @@ -911,7 +964,7 @@ Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up.











    -

    Different kernels and Mercer's theorem

    +

    Different kernels and Mercer's theorem

    There are several popular kernels being used. These are @@ -949,7 +1002,7 @@ in practice.











    -

    The moons example

    +

    The moons example

    @@ -982,7 +1035,7 @@ X, y = make_moons(n_samples.plot(X[:, 0][y==0], X[:, 1][y==0], "bs") plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^") plt.axis(axes) - plt.grid(True, which='both') + plt.grid(True, which='both') plt.xlabel(r"$x_1$", fontsize=20) plt.ylabel(r"$x_2$", fontsize=20, rotation=0) @@ -1060,7 +1113,7 @@ yk = np. plt.figure(figsize=(11, 4)) plt.subplot(121) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red") plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs") @@ -1070,7 +1123,7 @@ plt.plot(x1s, x3s, .gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1]) plt.xlabel(r"$x_1$", fontsize=20) plt.ylabel(r"Similarity", fontsize=14) -plt.annotate(r'$\mathbf{x}$', +plt.annotate(r'$\mathbf{x}$', xy=(X1D[3, 0], 0), xytext=(-0.5, 0.20), ha="center", @@ -1082,14 +1135,14 @@ plt.text(1.axis([-4.5, 4.5, -0.1, 1.1]) plt.subplot(122) -plt.grid(True, which='both') +plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs") plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^") plt.xlabel(r"$x_2$", fontsize=20) plt.ylabel(r"$x_3$ ", fontsize=20, rotation=0) -plt.annotate(r'$\phi\left(\mathbf{x}\right)$', +plt.annotate(r'$\phi\left(\mathbf{x}\right)$', xy=(XK[3, 0], XK[3, 1]), xytext=(0.65, 0.50), ha="center", @@ -1107,7 +1160,7 @@ plt.show() x1_example = X1D[3, 0] for landmark in (-2, 1): k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma) - print("Phi({}, {}) = {}".format(x1_example, landmark, k)) + print("Phi({}, {}) = {}".format(x1_example, landmark, k)) rbf_kernel_svm_clf = Pipeline([ ("scaler", StandardScaler()), @@ -1138,14 +1191,14 @@ plt.figure(figsize-1.5, 2.5, -1, 1.5]) plot_dataset(X, y, [-1.5, 2.5, -1, 1.5]) gamma, C = hyperparams[i] - plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16) + plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16) plt.show()











    -

    Mathematical optimization of convex functions

    +

    Mathematical optimization of convex functions

    A mathematical (quadratic) optimization problem, or just optimization problem, has the form @@ -1170,7 +1223,7 @@ Convex optimization problems play a central role in applied mathematics and we r











    -

    How do we solve these problems?

    +

    How do we solve these problems?

    If we use Python as programming language and wish to venture beyond @@ -1196,7 +1249,7 @@ This will make our life much easier. You don't need t write your own optimizer.











    -

    A simple example

    +

    A simple example

    We remind ourselves about the general problem we want to solve @@ -1264,7 +1317,7 @@ sol[’primal objective’]











    -

    Back to the more realistic cases

    +

    Back to the more realistic cases

    We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have @@ -1281,9 +1334,6 @@ subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vec \( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). -

    -code will be added -

    diff --git a/doc/pub/week47/ipynb/ipynb-week47-src.tar.gz b/doc/pub/week47/ipynb/ipynb-week47-src.tar.gz index 8b2c4fca12a72ec2c1ae80247494a37b84224bd5..1dc28a641f4a4dde144c10efc5d873ce0ddbf9e5 100644 GIT binary patch literal 190 zcmV;v073sBiwFP<_O)LC1MSaC3c@fD2H>uHia9|^Ow+6dUAPcLyg*8)Hdd3Gq-bw% zAD}D6O%Wj<3_l^mFtcATSKD>s?>?FhAtXyv7*b?>OtP5XBT6|?COBt;5z3%1#(4x} zzLj2D=cVmesZOXJ>bHG;TUmaXGo1p@{1b;tIoRwvUl|SBc+8Ed;f7eJB2i7Jb0`eD s;R`HYTV)ZX?m!lW^2%s=jvH%^R$g2Z|N5992!h~i4>otJApi&f041(ZVgLXD literal 192 zcmb2|=3t0-N{VM-etUi+AETp4>%+CSM{AqT@|?aV#MSC@guCZW3uoH3HyppeO>1)t zQF`=$R`8tQJGFT_;;LkCSM;l*74ts(y-r-l{?tLV^_@}huJya4t~~dv zvM@dAGVzT-(x!i3-^Ko492R~3M9#%!xgQ=mZ+b0IRMziODX$kL?p{q6G%$l!qdPA2aABF7js7#IMjEn3_F diff --git a/doc/pub/week47/ipynb/week47.ipynb b/doc/pub/week47/ipynb/week47.ipynb index 9ae4852e3..7760a5e3c 100644 --- a/doc/pub/week47/ipynb/week47.ipynb +++ b/doc/pub/week47/ipynb/week47.ipynb @@ -10,12 +10,51 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Sep 16, 2020**\n", + "Date: **Nov 19, 2020**\n", "\n", "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", "\n", "\n", + "## Overview of week 46\n", + "\n", + "* **Thursday**: Support Vector Machines, classification and regression. \n", + "\n", + "* **Friday**: Workshop on project 3 (first lecture), Support Vector Machines (second Lecture)\n", + "\n", + "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.\n", + "\n", + "[See overview video on Support Vector Machines](https://www.youtube.com/watch?v=efR1C6CvhmE&ab_channel=StatQuestwithJoshStarmer). See also [this video](https://www.youtube.com/watch?v=N1vOgolbjSc&ab_channel=AliceZhao).\n", + "\n", + "\n", + "## Thursday\n", + "\n", + "We start with our final topic this semester, Support Vector Machines\n", + "\n", + "## Friday\n", + "\n", + "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.\n", + "\n", + "## Workshop plan Friday (first lecture)\n", + "\n", + "Here are the various projects that will be presented during the first lecture (and possibly parts of the second lecture as well). *Titles are tentative*. Talks are approx 5-10 mins with roughly 5 minutes for discussions.\n", + "\n", + "* Maria Emine Nylund: **Lego Bricks Classifier**\n", + "\n", + "* Fabio Rodrigues Pereira: **Financial Machine Learning**\n", + "\n", + "* Markus Borud Pettersen: **Machine Learning and Brain Grid Cells**\n", + "\n", + "* _Jing Sun and Endrias Getachew Asgedom: **Machine learning-based approaches to denoising microseismic data**\n", + "\n", + "* Felicia Jacobsen: **Analysis of Breast Cancer Data**\n", + "\n", + "* Simon Elias Schrader: **Predicting atomization energies of molecules**\n", + "\n", + "* Varvara Bazilova and Sergio Andres Diaz Mesa: **Glacier Mapping and Machine Learning**\n", + "\n", + "* Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: **Gamma ray signals stemming from dark matter in the galactic center**\n", + "\n", "## Support Vector Machines, overarching aims\n", "\n", "A Support Vector Machine (SVM) is a very powerful and versatile\n", @@ -28,7 +67,7 @@ "\n", "The case with two well-separated classes only can be understood in an\n", "intuitive way in terms of lines in a two-dimensional space separating\n", - "the two classes (see figure below).\n", + "the two classes.\n", "\n", "The basic mathematics behind the SVM is however less familiar to most of us. \n", "It relies on the definition of hyperplanes and the\n", @@ -186,7 +225,7 @@ "## A $p$-dimensional space of features\n", "\n", "We limit ourselves to two classes of outputs $y_i$ and assign these classes the values $y_i = \\pm 1$. \n", - "In a $p$-dimensional space of say $p$ features we have a hyperplane defines as" + "In a $p$-dimensional space of say $p$ features we have a hyperplane defined as" ] }, { @@ -1882,13 +1921,11 @@ "source": [ "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", - "With the slack constants this leads to the additional constraint $0\\leq \\lambda_i \\leq C$.\n", - "\n", - "**code will be added**" + "With the slack constants this leads to the additional constraint $0\\leq \\lambda_i \\leq C$." ] } ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/doc/src/week47/week47.do.txt b/doc/src/week47/week47.do.txt index 26c8aa497..af70b14bd 100644 --- a/doc/src/week47/week47.do.txt +++ b/doc/src/week47/week47.do.txt @@ -2,6 +2,42 @@ TITLE: Week 47: Support Vector Machines AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University DATE: today +!split +===== Overview of week 46 ===== + +* _Thursday_: Support Vector Machines, classification and regression. +* _Friday_: Workshop on project 3 (first lecture), Support Vector Machines (second Lecture) + + +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. + +"See overview video on Support Vector Machines":"https://www.youtube.com/watch?v=efR1C6CvhmE&ab_channel=StatQuestwithJoshStarmer". See also "this video":"https://www.youtube.com/watch?v=N1vOgolbjSc&ab_channel=AliceZhao". + + +!split +===== Thursday ===== + +We start with our final topic this semester, Support Vector Machines + +!split +===== Friday ===== + +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. + +!split +===== Workshop plan Friday (first lecture) ===== + +Here are the various projects that will be presented during the first lecture (and possibly parts of the second lecture as well). *Titles are tentative*. Talks are approx 5-10 mins with roughly 5 minutes for discussions. + +* Maria Emine Nylund: _Lego Bricks Classifier_ +* Fabio Rodrigues Pereira: _Financial Machine Learning_ +* Markus Borud Pettersen: _Machine Learning and Brain Grid Cells_ +* _Jing Sun and Endrias Getachew Asgedom: _Machine learning-based approaches to denoising microseismic data_ +* Felicia Jacobsen: _Analysis of Breast Cancer Data_ +* Simon Elias Schrader: _Predicting atomization energies of molecules_ +* Varvara Bazilova and Sergio Andres Diaz Mesa: _Glacier Mapping and Machine Learning_ +* Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: _Gamma ray signals stemming from dark matter in the galactic center_ + !split ===== Support Vector Machines, overarching aims ===== @@ -15,7 +51,7 @@ medium-sized datasets. 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). +the two classes. The basic mathematics behind the SVM is however less familiar to most of us. It relies on the definition of hyperplanes and the @@ -150,7 +186,7 @@ We can then rewrite the above equation as ===== A $p$-dimensional space of features ===== 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 +In a $p$-dimensional space of say $p$ features we have a hyperplane defined as !bt \[ b+wx_1+w_2x_2+\dots +w_px_p=0. @@ -1138,6 +1174,7 @@ subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} = $\bm{y}=[y_1,y_2,\dots,y_n]$. With the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$. -_code will be added_ + +