## SVM algorithm improvements

In the previous post I talked about an SVM implementation in Matlab. I consider that post and implementation really interesting since it is not easy to find a simple SVM implementation. Instead, I found tons of files which may implement a very interesting algorithm but they are insanely difficult to examine in order to learn about how it works. This is the main reason why I put so much effort on this implementation I developed thanks to the algorithm [1].

## First improvement

After I implemented that algorithm everything seemed to work:

#### Example 1:

 Data points coordinates and target: Distance to the border from each point:

Very acceptable results, right? However, when I added more points I experienced an odd behavior.

#### Example 2:

It clearly fails at finding the optimum boundary, however, the funny thing here is that the distance between the second and third point and the boundary are the same. This means that the rest of the samples were ignored and the algorithm focused only on those two. Actually, and were the only nonzero values.

After debugging the code everything seemed to be right according to the algorithm I followed [1] but after many trials I saw what definitely brought me to discover the error. In my trial the first two elements belong to class -1 whereas the rest of them belong to the other one. As you can see in the following examples, when I changed the order of the elements in the second class I got that the boundary was different depending only on the first element of the second class, ergo, the third sample.

#### Example 4:

In this last trial we get the best solution because in this case the algorithm has to focus on the third sample which is the closest one to the other class. However, this is not always true, so I had the need of fixing it. The fix is very simple but was not easy to find (at least quickly).

When I was debugging the code, I realized that in the first loop (iterating over ) it never reached the samples 4th and 5th. The reason was easy to understand: after calculating the temporal boundary (even if it is not the best, that is why it is called “temporal”), there were no errors because the algorithm classified it correctly, so it never entered that loops which needed to pass the “if” which takes care of the tolerance. In other words, if there is no error, it does not try to fix it because it is able to classify it correctly (and this actually makes sense).

If the samples were not encountered on the loop on purpose, then they should be encountered on the other loop. Surprisingly, the algorithm did not encountered any of them in the inner loop. After I checked that I wrote the code accordingly to the algorithm [1], I thought that there had to be a mistake in the algorithm itself. And the mistake was the “Continue to “. Because of that line, it ignored the rest of ‘s, so it should be “Continue to “.

Thus, the fix in the Matlab code was pretty simple: changing from “break” to “continue“. Break allows to stop iterating over the loop and therefore it continues in the outer loop whereas continue makes the current loop stop and start iterating over the next value in that loop.

## Second improvement

After the first improvement was implemented, it seemed that it worked for many trials, but when I tried more complex examples, it failed again.

The original algorithm [1] uses the variable to see whether alpha changed. If no alphas are changed during the iterations for times, the algorithm will stop. I think the idea of iterating various times over the main algorithm is correct, but the algorithm must focus on those samples that will help building the boundary. After I implemented the modification, the algorithm iterated less times than the original algorithm. Additionally, the original algorithm implementation seemed to fail in many cases whereas my implementation works.

When the algorithm iterates once, alphas are updated such that nonzero alphas correspond to the samples that will help building the boundary. In this example, after the first iteration, alpha values correspond to this:

Therefore, in the next iteration it will update the samples to focus only in sample #3 and sample #6. After this implementation was done, all the trials I tried worked perfectly. This is the result of the same problem:

## Algorithm

This is the algorithm [1] after both improvements:

Initialize
Initialize

Initialize input and

Calculate using (2)

Calculate using (2)
Save old ‘s:
Compute and by (10) and (11)

Continue to
Compute by (14)

Continue to
Compute and clip new value for using (12) and (15)
(*A*)
Continue to
Determine value for using (16)
Compute and using (17) and (18) respectively
Compute by (19)

(*B*)

#### Algorithm Legend

(*A*): If the difference between the new and is negligible, it makes no sense to update the rest of variables.
(*B*): Useful data are those samples whose had a nonzero value during the previous algorithm iteration.
(2):
(10):
(11):
(12):
(14):
(15):
(16):
(17):
(18):
(19):

The code is provided in the Source code section.

## References

1. The Simplified SMO Algorithm http://cs229.stanford.edu/materials/smo.pdf

## [SVM Matlab code implementation] SMO (Sequential Minimal Optimization) and Quadratic Programming explained

This post is the second and last part of a double entry about how SVMs work (theoretical, in practice, and implemented). You can check the first part, SVM – Support Vector Machine explained with examples.

Index

## Introduction

Since the algorithm uses Lagrange to optimize a function subject to certain constrains, we need a computer-oriented algorithm to implement SVMs. This algorithm called Sequential Minimal Optimization (SMO from now on) was developed by John Platt in 1998. Since it is based on Quadratic Programming (QP from now on) I decided to learn and write about it. I think it is not strictly necessary to read it, but if you want to fully understand SMO, it is recommended to understand QP, which is very easy given the example I will briefly describe.

QP is a special type of mathematical optimization problem. It describes the problem of optimizing (min or max) a quadratic function of several variables subject to linear constraints on these variables. Convex functions are used for optimization since they only have one optima which is the global optima.
Optimality conditions:

If it is a positive definite, we have a unique global minimizer. If it is a positive indefinite (or negative), then we do not have a unique minimizer.

#### Example

Minimize

Initial point (where we start iterating)
Initial active set (we will only take into account these constraints).

Since a quadratic function looks like:

We have to configure the variables as:

This picture represents how the problem looks like. The function we want to minimize is the red circumference whereas the green lines represent the constraints. Finally, the blue mark shows where the center and the minima are located.

Iteration 1

Solve EQP defined by , so we have to deal with the first two constraints. KKT method is used since it calculates the Lagrangian multipliers.

indicates the next point the algorithm will iterate.
Now it is necessary to check whether this solution is feasible:

It is clear that this point was going to be feasible because the point (0,0) is where we started.
Now, we remove a constraint with negative and move to the next value .

Graphically, we started on (0,0) and we have to move to the same point (0,0). The removal of the constraint indicates to which axis and direction we are going to move: up or right. Since we took the first constraint out, we will move to the right. Now we need to minimize constrained to the second constraint.

Iteration 2

Solve EQP defined with

Check whether this is feasible: ?

Iteration 3

Solve EQP defined with

Check whether this is feasible:

It is not feasible. 3rd constrained is violated (that is why the third element is 0). As it is not feasible, we have to maximize

So,

Finally we add the constraint that was violated.

Iteration 4

Solve EQP defined with

Check whether this is feasible:

Iterations and steps are drawn on the plane below. It is graphically easy to see that the 4th step was illegal since it was out of the boundaries.

## Sequential Minimal Optimization (SMO) algorithm

SMO is an algorithm for solving the QP problem that arises during the SVM training. The algorithm works as follows: it finds a Lagrange multiplier that violates the KKT conditions for the optimization problem. It picks a second multiplier and it optimizes the pair , and repeat this until convergence. The algorithm iterates over all pairs twice to make it easier to understand, but it can be improved when choosing and .

Because we have that for a pair of . This confines optimization to be as the following lines show:

Let (assuming that )

We want to optimize:

If we pull out and we have:

Let and:

It represents the original formula without the first and second

Let . This means that is the output of under old parameters.

Now we substitute in our original formula with and pulled out using new variables: .

Note that here we assume that

Now we substitute using

The first is a constant so it will be added to the value.

Constant terms are grouped and is applied:

Let . Now, the formula is reduced to . Let us focus on the second part (the coefficient ““). Remember that

Since : (mathematical convenience)

Therefore, the objective function is:

First derivative:

Second derivative:

Note that . Proof: Let . Then
This is important to understand because when we want to use other kernels this has to be true.

Therefore, this is the formula to get a maximum:

While performing the algorithm, after calculating (or ) it is necessary to clip its value since it is constrained by . This constraint comes from the KKT algorithm.

So we have that:
If , then
If , then
If , then
If , then
If , then
If , then

In other words: (L = lower bound, H = higher bound)

Why do we need to clip our value?
We can understand it using a very simple example.
Remember that if , then remains always constant. If , then so they can change as much as they want if they remain equal. In the first case, the numbers are balanced, so if , as they sum 0.7, they can change maintaining that constraint true, so they may end up being .

If :

1) As explained before, and taking into account that , can only increase 0.3 because can only decrease 0.3 keeping this true: . Likewise, can only decrease 0.4 because can only increase that amount.

2) If they are different, can grow up to 1 because similarly, will grow up to 1 (which is the value of C and hence, the upper boundary). can only decrease till 0.1 because if it decreases till 0, would be -0.1 and the constraint would be violated.

Remember that the reason why has to be is because of the KKT algorithm.

 s L H 0 1 -1 1 1
If , it means that we cannot balance or proportionally increase/decrease at all between and . In this case, we skip this combination and try a new one.

After updating and we still need to update b.
(the increment of a variable is given by the increment of all variables which are part of it).

The change in the threshold can be computed by forcing

So we have:

## Algorithm

The code I provide in the Source code section was developed by me, but I followed the algorithm shown in [1]. I will copy the algorithm here since it made my life really easier and avoided me many headaches for sure. All the credit definitely goes to the writer.

Algorithm: Simplified SMO
Note: if you check [1] you will see that this algorithm differs from the original one written on that paper. The reason is because the original one had mistakes that I wanted to fix and improve. I talk about that in this post.

Input:
C: regularization parameter
tol: numerical tolerance
max_passes: max # of times to iterate over ‘s without changing
: training data

Output:
: Lagrange for multipliers for solution
: threshold for solution

Algorithm:
Initialize
Initialize

Initialize input and

Calculate using (2)

Calculate using (2)
Save old ‘s:
Compute and by (10) and (11)

Continue to
Compute by (14)

Continue to
Compute and clip new value for using (12) and (15)
(*A*)
Continue to
Determine value for using (16)
Compute and using (17) and (18) respectively
Compute by (19)

(*B*)

#### Algorithm Legend

(*A*): If the difference between the new and is negligible, it makes no sense to update the rest of variables.
(*B*): Useful data are those samples whose had a nonzero value during the previous algorithm iteration.
(2):
(10):
(11):
(12):
(14):
(15):
(16):
(17):
(18):
(19):

#### Source Code Legend

(*1*): This error function arises when we try to see the difference between our output and the target: and as we get that
(*2*): This line has 4 parts: if ((a && b) || (c && d)). A and C parts control that you will not enter if the error is lower than the tolerance. And honestly, I don’t get parts B and D. Actually I tried to run this code with several problems and the result is always the same with and without those parts. I know that alpha is constrained to be within that range, but I don’t see the relationship between A and B parts, and C and D parts separately, because that double constraint (be greater than 0 and lower than C) should be always checked.

## Results

Given a 3D space we have two samples from each class. The last column indicates the class:

Solution:

The code is provided in the Source code section.

## References

1. The Simplified SMO Algorithm http://cs229.stanford.edu/materials/smo.pdf
2. Sequential Minimal Optimization for SVM http://www.cs.iastate.edu/~honavar/smo-svm.pdf

## [Supervised Learning] SVM – Support Vector Machine explained with examples

This post is the first part of a double post about SVMs. This part tries to help to clarify how SVMs work in theory (with 2 full developed examples). The second part (not published yet) will explain the algorithm to solve this problem using a computer: Quadratic Programming and SMO.

Index

## Basic definition

Support vector machines (SVMs from now on) are supervised learning models used for classification and regression. The basic idea of SVMs in binary classification is to find the farthest boundary from each class.

Therefore, solving a basic mathematical function given the coordinates (features) of each sample will tell whether the sample belongs to one region (class) or other. Input features determine the dimension of the problem. To keep it simple, the explanation will include examples in 2 dimensions.

## Mathematical explanation

 The vector is a perpendicular vector to the boundary, but since boundary’s coefficients are unknown, vector’s coefficients are unknown as well. What we want to do is to calculate the boundary’s coefficients with respect to because we have its coordinates (sample’s coordinates).

 If both vectors are multiplied, the result will be the purple vector.

Let us say that:

Where is a positive sample (class A) and is a negative sample (class B).
A new variable is now introduced:

Multiply each of them by the previous equations:

The result is the same equation. Therefore, we only need the previous formula:

 Finally, we add an additional constrain so that the values that fulfill this, fall in between the two regions as depicted (green zone).

 The next step is to maximize the projection of on (the black perpendicular vector to the boundary) to keep samples from each class as far as possible. I assume that you know about scalar projection, but if you don’t, you can check out the Appendix A. The length of the projection is given by the following formula:

From the previous formula now let us substitute both positive and negative samples and so that:

Therefore:

The goal is to maximize which is the same as minimizing or, to make it more mathematically convenient,

Thus, we have a function to minimize with a constraint (), so Lagrange is applied. In case you want to know more about Lagrange multipliers, you can check Appendix B.

First we have the function we want to minimize, and later the constraints.

Plug these two functions to .

Hence, we aim to minimize
The optimization depends on

## Kernel trick

One of the most interesting properties of SVMs is that we can transform problems from a certain number of dimensions to another dimensional space. This flexibility, as known as kernel trick, allows SVMs to classify nonlinear problems.

The following example shows how to graphically solve the XOR problem using 3 dimensions.

Now it is not difficult to imagine a plane that can separate between blue and red samples.

## Example 1: 2 points in a plane

Points and class (coordinate x (x1), coordinate y (x2), class/output (y)):

Point 1:

Coordinates:
Class (output):

Point 2:

Coordinates:
Class (output):

We want to minimize:
We know that:
and

Let us calculate the second part of the function we want to minimize first to keep it simple:

Ergo:

Now let us calculate :

Now we have to figure out the bias

Solution =

## Example 2: 3 points in a plane

Points and class (coordinate x (x1), coordinate y (x2), class/output (y)):

Point 1:

Coordinates:
Class (output):

Point 2:

Coordinates:
Class (output):

Point 3:

Coordinates:
Class (output):

First let us calculate the second part of the function we want to minimize. You can see both alphas being multiplied by two numbers. The first number is the product of and . The second number is the dot product between the two coordinates .

Result:

## Appendix A: Scalar Projection of Vectors

We have two points and its vector:

And we want to calculate the length of the vector’s projection (purple) on the orange vector (which by the way, is the perpendicular of both green lines). The result is the blue vector which is over the orange one within the green region.

For this, we have to solve the formula:

Now with the length and the angle, we can calculate the coordinates using sine and cosine functions.

B was in [9,7], so the point on the other side of the projection is

## Appendix B: Lagrange Multipliers

Lagrange is a strategy to find local maxima and minima of a function subject to equality constraints, i.e. max of subject to . and need to have continuous first partial derivatives.

If is a maximum of for the original constrained problem, then there exists such that is a stationary point for Lagrange function (so is 0).

 In mathematics, a stationary point of a differentiable function of one variable is a point of the function domain where the derivative is zero. For a function of several variables, the stationary point is an input whose all partial derivatives are zero (gradient zero). They correspond to local maxima or minima.

 To make it clear, let us say that we have a surface whose gradient is and it is perpendicular to the whole surface. We try to find its maxima whose gradient should theoretically be perpendicular as well. Let us not forget the relationship between the first derivative and the gradient. Hence we can say that the gradient of and the gradient of are pointing in the same direction so: (proportional). is called Lagrange multiplier.

#### Example 1: 1 constraint, 2 dimensions

Maximize on unit circle

Now we plug these results into the original equation.

Therefore we have two points:

#### Example 2: 1 constraint, 2 dimensions

Find the rectangle of maximal perimeter that can be inscribed in the ellipse . We want to maximize the perimeter which is subject to

Now plug it into the original equation.

(we take the positive because it is a maximum),

Then,
So the maximum permieter is:

#### Example 3: 2 constraints, 3 dimensions

Now plug it into and :

Since this is a parabola in 3 dimensions, this has no maximum, so it is a minimum.