## [Hough Transform] Ellipse detection and space reduction

This is the last entry regarding Hough Transform. I previously wrote about Line Detection and Circle Detection including some Source Code, but in this case I will just write about it. The reason why I did not write any code is because it can be found in [1] and because it is very similar to the Circle Detector.

## Brief Introduction

Ellipse detection is another useful tool that may have various applications in the field of recognition. Let us not forget that sometimes due to the movement when a picture is taken, in some images circles cannot be represented correctly, so ellipses appear instead. Ellipses are also a very simple shape that can be interesting to recognize since we live surrounded by objects with that shape. As an example, self-driving cars are intended to recognize traffic signs. In particular, rounded traffic signs may look elliptical when they are seen from a specific point of view.

## Simple way (5 dimensions)

This approach is very similar to the Circle Detector. Circumferences have 3 characteristics needed to be defined: radius and center coordinates. Likewise, it can be said that in case of ellipses we need 5 characteristics: the center (2), the size along both axes (2) and its rotation (1).

Implementing a 5 dimensional matrix will lead us to fall over the curse of dimensionality. This approach can be reasonable when the algorithm faces a known environment and therefore some characteristics can be drastically reduced. For instance, if a fixed camera aims to capture the movement of the moon, the size of its radius will not change very much, and as the movement can also be predicted, one can simply modify a few parameters to adapt the algorithm and focus on a certain region.

The implementation, as stated above, is similar to the circle detector: using the trigonometric characteristics of the ellipse one can establish relationships between them and iterate over each parameter to try all combinations along the whole image. There is a Matlab code written in [1] (page 209).

## Space Reduction

Space reduction is applied in a very similar way to the Circle Detector. Nonetheless, as ellipses are figures a bit more complex than circumferences, it can be more problematic to achieve the solution. Let us recall that for circumferences, it is only necessary to take the center point in the chord between two prospective points that might belong to the circumference, and draw a perpendicular line to the chord passing through the center point. This is possible due to the orthogonality between these two lines, but this is not the case when analyzing ellipses. The equivalent to that perpendicular line in the circumference must be found in other way, for instance, using the tangential lines of those two chosen points, as we can see below.

 Circle detection Ellipse detection

The algorithm shown in the book [1] is similar to the Circle detector: it iterates over the whole picture trying to find a black pixel. When it is detected, it looks in the neighborhood for another one to draw a chord and therefore, the pixel in the center of the chord. The proposed way to find the coordinates of the pixel out of the ellipse is by the intersection of the tangent of those two chosen points. The author proposed that these tangents can be obtained before the process of Non-Maximum Suppression. In this case, during the use of Sobel filter the angles to generate those tangents can be obtained when Canny Edge detector is used.

Finally, we just need to obtain the maxima of the accumulator, and draw the consequent ellipse.

## References

1. M. Nixon and A. Aguado. 2008. “First order edge detection operators”, Feature Extraction & Image Processing.

## Brief Introduction

Hough Transform was already used for Line detection and it showed how powerful it can be. This time, the main goal will be detecting circles. Detecting this basic shape may be interesting in the field of recognition since many objects subject to be classified have a circular shape such as the iris of the eyes, coins or even cells under a microscope.

## Simple way (3 dimensional matrix)

This first method is easier to understand but very inefficient compared to the next (after space reduction is applied). A circle needs three parameters: x,y values for the center location and the radius of the circumference. Thus the accumulator matrix will have 3 dimensions, one for each parameter, covering all possibilities.

Given a certain radius, when a pixel is detected, the algorithm will increment the accumulator elements corresponding to the circumference that can be drawn using that pixel and radius as characteristics of the circle.

The first two parameters of the 3-D accumulator are x,y values corresponding to the coordinates of the whole picture. The third parameter is the radius. In the following picture, we are using a fixed radius to make everything easier to understand, and the accumulator is incremented in those coordinates in which a red pixel is located.

As you can see, the red pixels almost do not coincide in any point when iterating over the same coordinate. During the algorithm execution, many circles will be drawn and there will be a peak in the center of the real circle we want to detect, as depicted below. They all meet in the center of the circumference (green points).

When the algorithm finishes the iteration over all pixels and radius, we only need to find where is that maxima located to get the characteristics of the circumference. Finally, we can draw it.

The most problematic characteristic of this algorithm is that it needs to iterate over all radius, so it will lose a considerable amount of time on this task. For this reason, in the algorithm I developed I establish a min and max radius, to avoid checking radius extremely short and radius too large. This is how it looks depending on the described situation.

 a) b) c)

a) When the circumference has a larger radius than expected.
b) When it finds more figures.
c) When it only finds an ellipse.

The algorithm is this:
Iterate over columns (x)
Iterate over rows (y)
If an edge is detected
Iterate over all radius (r)
For angles between 0 and 360 (m)
Calculate pixel for the generated circumference (y,x,r)
If that pixel is not out of bounds, increase accumulator

## Space Reduction

Space reduction in this case consist in removing the problematic radius parameter.

When iterating over the picture and a pixel is detected, it will try to look for more pixels in a enclosed neighborhood. When a pixel in the neighborhood is detected, we will have an arc of the circumference. Given these two pixels, we will have a slope and a middle point (blue). We need to find the perpendicular line passing through that middle point (red) which represents the increment in the accumulator.

As the algorithm iterates, it will increase more and more the accumulator, and a peak in the center of the real circumference will be generated.

 After some iterations Accumulator plotted

There is another method to obtain the center explained in [1], but the algorithm written in the book is an implementation of the already explained method. However, the author of the books does not give a hint about getting the radius once we got the center.

I used a 1 dimensional array (or vector) as an accumulator of the distances of each pixel in the image to the center. The peak will be generated when the distances of all the pixels belonging to the circumference are summed in the accumulator. This results in the radius of that circumference. It may be improved by starting in the neighborhood of the center and stop counting at some point.

The execution time differs from the improved algorithm and from the non-improved algorithm. For the same picture, the non-improved algorithm takes around 0.39 seconds whereas the improved version takes around 0.019 seconds.

The code is provided in the Source code section.

## References

1. M. Nixon and A. Aguado. 2008. “First order edge detection operators”, Feature Extraction & Image Processing.

## [High and low pass filters] The Einstein-Monroe picture

There is an Einstein-Monroe picture wandering around the Internet that I recently saw. It can be a nice example of how human vision works as well as building a high and low pass filter from scratch in order to extract both images.

This picture includes a low frequency picture of Monroe and a high frequency picture of Einstein blended together. Human vision notices details of its environment when objects are close (high frequency). That means that when we are close enough (a normal distance) to this picture, we should be able to see Einstein’s face, otherwise you should check your sight. If you take 3 steps back and see the same picture, you should be seeing Monroe’s face because your vision is not able anymore to get the small details of the picture. Instead, it will get a general idea of the picture (a bit blurry).

Since this is about high and low frequency pictures, we can build high and low pass filters to extract the frequency of the image we want. Thus each original image is theoretically possible to be extracted.

First of all, we can see how the Fast Fourier transform looks like. In order to achieve it, we have to perform the 2-D Fast Fourier, shift it, and scale it.

The low frequency data of the image is in the center of the previous image. Thus a simply low-pass filter can be built by keeping the center and removing the rest, as this picture shows. If we want to extract the opposite, we can invert it.

 Low-pass filter High-pass filter

The radius of the circle needs to be manually adjusted depending on the output. When we try to rebuilt the image using both of those Fourier Transform, we get the original images.

 Low frequency image High frequency image

Since in my secondary screen I can barely see Einstein’s face, I tried to increase the contrast to make it easier to see in case you have the same issue.

The code is provided in the Source code section.

## Interesting Links

1. S. Lehar. “An Intuitive Explanation of Fourier Theory”, http://cns-alumni.bu.edu/~slehar/fourier/fourier.html.

## Brief Introduction

Line detection is one of the most important and basic feature extraction methods. Many currently developing and promising fields such as self driving cars may use line detection to detect lanes. Thus, it is important to understand how it works (both mathematically and the implementation).

As we are using a 2D plane (an image) we can use Cartesian or Polar parameterization. Polar parameterization is useful not only because of its own advantages, but also because it allows the algorithm to reduce costs by space reduction.

## Cartesian

Let us keep in mind the line equation:

In homogeneous form:
where

To determine the line we must find

The way HT works is by simply counting the potential solution in an accumulator, tracing all possible lines for each point within the main iteration. Hence, finding the maximum in the accumulator means finding the line with the highest probability.

When iterating, after checking that a black pixel (typically corresponding to an edge) has been detected, it iterates over two different “for” loops. The first loop corresponds to angles between -45 and 45 degrees (both inclusive) and the second loop between 45 and 135. It is necessary to separate them because for slopes whose degrees are larger than 45 or lower than -45, (intersection with y-axis) may take large values. Thus, an additional accumulator for angles between 45 and 135 is needed, which will store a similar variable whose value is the intersection with x-axis rather than y-axis.

As we can see in the image below for the case when angles are between -45 and 45, when is out of bounds (a) (bounds are 0 and the height), the accumulator is not increased. Otherwise, the accumulator will increase for all those angles between the allowed boundaries (b) (green). Note that all those angles that are outside are later taken into account when examining x-axis.

In the following picture, we have 5 points that may compound a line. In the green zone of the left side you can see how the region in the middle is getting larger and larger. That represents the accumulator values for those angles and intersection with the y-axis, and it shows that there is a high probability to find a line, as it is. Likewise, we can also see that the behavior of this algorithm is strong against noise and occlusion. As a drawback, two large matrices are needed.

#### Cartesian Algorithm

Iterate over rows (y)
Iterate over columns(x)
If an edge is detected
For angles between -45 and 45 (m)
Calculate c (y-axis intersections)
If c is between the bounds, increase accumulatorA
For angles between 45 and 135 (m)
Calculate c (x-axis intersections)
If c is between the bounds, increase accumulatorB

#### Correction

The previous algorithm taken from [1] was used to understand Hough Transform for Cartesian coordinate systems, however, this algorithm failed to classify some lines such as the following:

At first I thought that the problem could be my implementation of how to draw those lines given the accumulators, but after a deep study of the algorithm I realized what was the mistake. In addition to the author mistake, I added a small improvement that may help to understand HT in Cartesian coordinate systems.

First of all, in the author’s algorithm the accumulators are split depending on the degrees that are being examined. The first accumulator stores vertical intersections of the y-axis on angles between -45 and 45 whereas the second is responsible of the x-axis intersections on angles between 45 and 135.

If a nearly horizontal line is examined, the first accumulator (vertical intersections) will have a higher maxima than the second accumulator. This can be seen in the image above the algorithm: in the vertical accumulator a peak around the center will be created. In contrast, the horizontal accumulator will grow but very plain. Let us recall that in the accumulator there are represented the pixel where the line should start (the intersection with the axis) and the angle. Once this is completely understood, one can imagine many problematic scenarios such as the one depicted previously.

In the previous image, the line that should be generated must start in the x-axis. This means that the horizontal accumulator (the second) should have a higher peak than the vertical one. However, the angle corresponding to that line is between -45 and 45 degrees, so it is only examined by the first accumulator. Thus, the assumption that one accumulator should be in charge of a certain range of degrees while the second takes cares of the rest, is extremely naïve. The solution to this problem is by simply computing the range from -45 to 135 degrees in both accumulators. It is worth saying that the computation time is almost not affected at all, but we need a higher amount of memory.

The improvement to better understand the algorithm is more related with the later line drawing. As the “for” loops and pixel detection works, the image is examined from top to bottom and left to right. This makes our coordinates system move from the typical 0,0 starting in the bottom-left corner to the top-left corner. This shift arises problematic issues regarding the formulas, especially with the one used for the second accumulator (x-axis crossings detection). The formula used for detecting these crossings is:

Where represents the angle and represent the coordinates. This formula may work when the 0,0 is in the bottom-left corner:

But if the coordinate epicenter is moved, it will not work anymore. For this reason, instead of computing when is calculated, I decided to compute . An alternative solution would be changing the formula.

Final algorithm:
Iterate over rows (y)
Iterate over columns(x)
If an edge is detected
For angles between -45 and 135 (m)
Calculate yInv ()
Calculate c (y-axis intersections)
If c is between the bounds, increase accumulatorA
Calculate c (x-axis intersections)
If c is between the bounds, increase accumulatorB

Both algorithms (the original and the improved one) are in the Source code section.

## Polar

Polar coordinate system is an alternative to the Cartesian in which a radius and angle are needed to locate a single point, rather than X-Y coordinates. The maximum length of the radius can be obtain by the Pythagoras formula: where N is the largest size (width or height).

In contrast with Cartesian, in the Polar algorithm we only need one accumulator. The first dimension of the matrix is the radius which is between 0 and , and the second dimension is the angle (0-180). It will work in the same way as Cartesian: examining each point of the edge individually the accumulator will increase in those points which may generate the objective line. The final line will be drawn by finding the maximum value in the accumulator and using the radius and angle where it is located. It may seem a bit confusing how to calculate prospective points in the Polar coordinate system, so I tried to explain it using some drawings.

Imagine that we have the point 2,4. It is not difficult to calculate its angle and radius.

However, for the same point, it looks a bit confusing when examining different angles. This is how it looks when we try to figure out the radius of the same point for a 45º angle.

And here is an example of a straight line: 4 purple points in a row. If we examine all the angles, we will realize that for the 90º angle they all reach the same point (3), so the accumulator will be maximum there.

#### Polar Algorithm

Initialize max value of radius
Iterate over columns (x)
Iterate over rows (y)
If an edge is detected
For angles between 1 and 180 (m)
Calculate the radius (*)
If radius is between the bounds (0 and maximum), increase accumulator

#### Polar Examples

The same pictures as Cartesian Examples.

#### Correction

As in the Cartesian algorithm given in [1], in the Polar algorithm another mistake related to the one found in the Cartesian is found as well. This algorithm seems to work always except for one particular case: when one side of the line is bent pointing from top to bottom following a north-west to south-east direction.

 Ok. Fail Ok.

Again, the error is to naïvely assume that the previous studied radius-angles were all the possibilities.

The error is illustrated in the picture below. Given that angle (around 150º) the corresponding radius is negative and therefore, it is discarded (radius must be between 0 and ). The reason why the radius is negative is very simple: the intersection is in the other side of the line to which it is suppose to intersect (the red line with the arrow). Given this scenario the solution could be a negative radius and 150º degrees or a positive radius but a negative degrees (150-180 = -30º). Both scenarios cannot be stored in the accumulator for obvious reasons. The real (and more expensive in terms of memory) solution would be to extent the accumulator from 1-180 to 1-360 degrees to cover all cases. In this case, this line would be detected in the angle -30+360 = 330º and the radius will be positive because of the orientation of the arrow.

Nonetheless, I tried to study how good or bad was assuming that we only needed to check 1-180 degrees. For this, I run the algorithm through a 150×150 black image to make it fire in every pixel and try each combination. After that, I checked which parts of the accumulator were 0, meaning this that the will never be modified. I did the same in the 1-360 case to see those cases that cannot be seen from the first 1-180º implementation. The black color represents those elements who are never increased whereas the white color represents a zone that can be modified. The width indicates each angle, so in the first case the picture has 180 columns and the second one has 360.

The conclusion drawn from these pictures is that it is possible to make a more efficient algorithm to iterate only over those cases that may be meaningful.

## Space Reduction

The space reduction is a modification of the polar algorithm in which the accumulator matrix is reduced from to two matrices: . The huge save is obvious, but again, the naïve approach to enclose the problem from 1 to 180 degrees will have the same consequences as in the previous section.

The algorithm presented in the book does not iterate over all angles. Instead, it checks whether a point is located in a certain neighborhood (a 5×5 window) and it calculates the angle for that point.

This approach is more statistical than the previous algorithms, so instead of the accuracy given by knowing the coordinates which correspond to the characteristics of the line, it decides the parameters of the line given the statistics from the accumulator.

The code given in [1], page 211, does not work for almost any line. To make it work, one needs to fix it as in the previous section: adding the 360 degrees.

## Additional notes for further improvements

·The accuracy is extremely related with the counter value
·Instead of taking the max, you can take the 2 or 3 max values since more lines may be found.
·Instead of 2 or 3 max, you can establish a threshold
·It can also be possible to study only those lines in a certain region of the picture. For instance, if you want to make a lane recognizer you should focus on the half in the bottom.

The code is provided in the Source code section.

## References

1. M. Nixon and A. Aguado. 2008. “First order edge detection operators”, Feature Extraction & Image Processing.

## [Image Processing] Thresholding and Subtracting

One of the simplest methods to extract features from a picture is by subtracting and thresholding. Imagine that from a static background we want to get any figure that appears in front. For instance, let us say that we want to measure the height of different people who will lean against a wall. At first, the background (the wall) is observed. Then, someone will appear, and later, by subtracting the new picture from the background we will be able to extract the person who appeared. After that, it will not be difficult to guess the height. The thresholding operation comes from the fact that we have to decide how strong is the change to consider that it indeed changed.

The most impressive advantage of this method is that it is really easy to implement and fast, similar to the temporal median which can actually be used to generate the background. The biggest drawback is that it is very sensitive to noise and luminosity changes as we will see.

I cropped a couple of pictures used in the temporal median to try this out.

 Background
 Background + figure

And these are the results after applying thresholding and subtraction. The first picture has a lot of noise as you can see, but I think is very easy to remove in this case. I think this noise comes from that when these pictures were taken, there was a bit of wind and pixels are not exactly the same. In order to remove the noise, in the second attempt I firstly used a Gaussian filter. By the way, both pictures were converted first to gray scale to make it simple and faster since the background and foreground will be in a different color, although Gaussian took really long compared to the first one. In any case, in the original image my right arm is almost blended with the background. That is why it is not well detected.

 Simple thresholding and subtracting
 Using a Gaussian filter first

When subtracting you can be very imaginative and try different things depending on the background, foreground and the application:
a) Having single thresholds for each color channel
b) Having a global threshold made from the sum of the subtracting of each channel
c) Combining a) and b)
d) Using gray scale
e) Applying a template convolution (Gaussian or any other)
f) Check out the neighborhood
and so on.

I wanted to try out how to use the webcam to process and show the results “in real time”, although my computer does not compute very fast and I took a picture every 1 or 1.5 seconds, but it is still interesting. I also wrote a post about how to take pictures from the webcam with Matlab.

This is the algorithm of the code I made

Initialize webcam, max_times
Wait 2 seconds before taking a picture of the background (to let me hide)
Take a picture of the background
Wait 1 second
while max_times>=0
Take a picture
result = blackPicture (background color)
Iterate over each pixel (y,x)
If background(y,x,redChannel) – picture(y,x,redChannel) > threshold || background(y,x,greenChannel) – picture(y,x,greenChannel) > threshold || background(y,x,blueChannel) – picture(y,x,blueChannel) > threshold
result(x,y,channels) = newColor
End if

Show picture (or store it)
Decrease max_times

## Results

Some times we can see that the whole area is green. This is because the luminosity changes depending on where the camera is focusing, and the focus changes depending on where the camera detects something. As the luminosity of the whole picture changes, everything turns to green. Shadows also make the luminosity change.

An example of how luminosity changes depending on where the webcam is focused.

 Background picture
 Take a look to the luminosity of the walls

The code is provided in the Source code section.

## References

1. M. Nixon and A. Aguado. 2008. “First order edge detection operators”, Feature Extraction & Image Processing.

## How to take pictures from the webcam with Matlab

In Image Processing, taking pictures as well as recording videos is an important task since it is the first step before processing the images. Thus, I consider interesting to write an entry about configuring the webcam in Matlab. I have to say that I was extremely astonished by how easy this was. I was expecting installing external drivers or add-ons in Matlab (actually that was my first and wrong step) but nothing like that is needed. You have to, at least, have installed the camera in your PC, which seems to be quite obvious if you want to use it. The only requirement is having the Image Acquisition Toolbox installed, which I had installed by default in my R2013a Matlab version.

At first, we will use imaqhwinfo to see the adaptors recognized by Matlab:

 12345678 >> imaqhwinfo ans =     InstalledAdaptors: {'gentl'  'gige'  'matrox'  'winvideo'}         MATLABVersion: '8.1 (R2013a)'           ToolboxName: 'Image Acquisition Toolbox'        ToolboxVersion: '4.5 (R2013a)'

“winvideo” seems to be the adaptor I want to use, so I will try to get more information about it:

 123456789 >> devices = imaqhwinfo('winvideo') devices =        AdaptorDllName: [1x81 char]     AdaptorDllVersion: '4.5 (R2013a)'           AdaptorName: 'winvideo'             DeviceIDs: {[1]  [2]}            DeviceInfo: [1x2 struct]

We can see in “DeviceIDs” that I have two cameras connected: my laptop camera and a USB camera. If I want to get more information about each camera, I will print out DeviceInfo.

 1234567891011121314151617181920212223 >> devices.DeviceInfo(1) ans =              DefaultFormat: 'YUY2_160x120'        DeviceFileSupported: 0                 DeviceName: 'USB2.0 Camera'                   DeviceID: 1      VideoInputConstructor: 'videoinput('winvideo', 1)'     VideoDeviceConstructor: 'imaq.VideoDevice('winvideo', 1)'           SupportedFormats: {1x5 cell} >> devices.DeviceInfo(2) ans =              DefaultFormat: 'MJPG_1280x1024'        DeviceFileSupported: 0                 DeviceName: '1.3M HD WebCam'                   DeviceID: 2      VideoInputConstructor: 'videoinput('winvideo', 2)'     VideoDeviceConstructor: 'imaq.VideoDevice('winvideo', 2)'           SupportedFormats: {1x18 cell}

When we are using a camera in Matlab, we need to determine which format will be used. I decided that I want to use the in-built camera, so let’s check what formats does it support.

 12345678910111213141516171819 >> device2 = devices.DeviceInfo(2); >> device2.SupportedFormats ans =   Columns 1 through 5     'MJPG_1280x1024'    'MJPG_1280x720'    'MJPG_1280x800'    'MJPG_1280x960'    'MJPG_160x120'   Columns 6 through 10     'MJPG_176x144'    'MJPG_320x240'    'MJPG_352x288'    'MJPG_640x480'    'YUY2_1280x1024'   Columns 11 through 15     'YUY2_1280x720'    'YUY2_1280x800'    'YUY2_1280x960'    'YUY2_160x120'    'YUY2_176x144'   Columns 16 through 18     'YUY2_320x240'    'YUY2_352x288'    'YUY2_640x480'

My recommendation is to use MJPG rather than YUY2, and to use a small size like 640×480 or lower because the lower, the faster to process. In addition, if you want to test your camera in Matlab, you can also type imaqtool and the Simulator will pop up. Now we have to configure Matlab writing which camera and format will be used, frames per second captured, and the color space:

 123 vid = videoinput('winvideo', 2, 'MJPG_640x480'); vid.FramesPerTrigger = 1; vid.ReturnedColorspace = 'rgb';

When we want to capture a picture with the camera, we simple have to trigger:

 1 start(vid);

To retrieve the capture picture(s):

 1 picture = getdata(vid);

When using RGB, we would expect that the variable picture have 3 dimensions (height, width, color channel), but if FramesPerTrigger is more than 1, this variable will have 4 dimensions. The 4th dimension will be each frame, so if we want to save the first and last frame taken, we will simply do:

 1234567 vid = videoinput('winvideo', 2, 'MJPG_640x480'); vid.FramesPerTrigger = 30; vid.ReturnedColorspace = 'rgb'; start(vid) frames = getdata(vid); imwrite(frames(:,:,:,1),'firstframe.jpg'); imwrite(frames(:,:,:,end),'lastframe.jpg');

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

## Optimization and Quadratic Programming

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
3. Inequality-constrained Quadratic Programming – Example https://www.youtube.com/watch?v=e6jDGxNZ-kk

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

## Matlab

How to take pictures from the webcam with Matlab