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

Iterate over columns (x)
Iterate over rows (y)
If an edge is detected
For angles between 1 and 180 (m)
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.

·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)'

 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.

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.

Definition

Despite the huge simplicity of temporal median (both theoretical and practical approaches), I considered it very interesting since it allows to remove undesired objects from a static background. This can be especially useful when someone wants to take a picture of a very crowded sightseeing or monument, although it consumes a very important amount of resources.

First we have to assume that the pictures were taken from the same spot, they have the same luminosity and the same size. These are quite strong constraints but can be achieved by using a tripod and a remote trigger. In my case, I used my smartphone which has a function that by making an intense noise (snap) it takes a picture.

The algorithm iterates over each coordinate and calculates the median of each pixel and each color channel from the different images. The value of each color channel is then mixed and located in that coordinates.

Let us say that we have 3 pictures with the same background and it has a single pixel located in different spots. When the iteration arrives to [5,8] it encounters a black dot in the first picture.

When median is calculated, the pixel will be:

And therefore, the black pixel will disappear.

Other temporal operations use mode and average instead of median. In case of average, the result is a blended picture.

Results

4 images were processed (4208×2368) by an under-average laptop and it took 35 minutes to generate the result.

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.

Laplacian

First order detection is based on the differentiation of intensity within the same region to detect changes whereas the second order gets zero when the rate of change is constant. Therefore, when a zero-crossing is found, the algorithm would have found an edge.

Laplacian operator is a template which implements this. By differentiating between two adjacent pixels (first order), the second order is approximated.

Which can be translated into an horizontal (or vertical if transposed) as:

 -1 2 1

And:

 0 -1 0 -1 4 -1 0 -1 0
 -1 -1 -1 -1 8 -1 -1 -1 -1

Marr-Hildreth operator

The Marr-Hildreth operator combines Gaussian filtering to smooth the image with Laplacian (LoG operator, Laplacian of Gauss). After the second differentiation of Gauss we have the corresponding formula to find the coefficients to the template to convolve the image with.

This function, which can be approximated by a difference of Gaussians, is called Mexican hat wavelet because of its shape:

After the image is convolved with the generated template, we have do determine the zero-crossing points. There are many techniques to achieve this goal, but a much simpler solution is shown: first we divide a 3×3 window in 4 sections as in the following picture, all of them containing the pixel in the center. The average of each section is computed, and if the maximum value is positive and the minimum is negative, a zero-crossing is found and therefore the pixel in the center will be set as white (otherwise is marked as black). This has to be applied to the whole image.

Results

See how a simple figure changes after Laplacian is applied.

Laplacian

Original input

After Laplacian

In this case we would have to detect the zero-crossings to obtain the final result.

Marr-Hildreth

 Original
 2nd derivative Gaussian: {size: 3, sigma: 0.7}
 2nd derivative Gaussian: {size: 5, sigma: 0.7}
 2nd derivative Gaussian: {size: 7, sigma: 0.7}
 2nd derivative Gaussian: {size: 9, sigma: 0.7}
 2nd derivative Gaussian: {size: 5, sigma: 0.5}
 2nd derivative Gaussian: {size: 5, sigma: 0.6}
 2nd derivative Gaussian: {size: 5, sigma: 0.8}
 2nd derivative Gaussian: {size: 5, sigma: 0.9}
 2nd derivative Gaussian: {size: 5, sigma: 1}

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.

Definition

An MLP (Multilayer perceptron) is a feedforward neural network which consists of many perceptrons joined in many layers. The most basic MLP has 3 layers: one input layer, one output layer and one hidden layer, but it may have as many hidden layers as necessary. Each individual layer may contain a different number of neurons.

Feedforward means that nodes have a direct connection such that nodes located in between are fed by the outputs of previous nodes and so on. This is very simple to program because it is basically as the perceptron: multiply weights (including bias nodes) by the input vector, give the result to the activation function, and the output will be the input of the next layer until the output layer is reached.

In the entry about the perceptron I used the step function as the activation function, but in MLP a variety of them can be used. Most of them are sigmoid (mathematical functions having an “S” shape) such as:

The difference between these two sigmoids is that the hyperbolic tangent goes from -1 to 1 whereas the other goes from 0 to 1.

Sometimes linear functions are also needed for cases when neural networks are not used for classification but for extrapolation and any kind of prediction.

If the MLP misclassifies an input, it is necessary to back-propagate the error rate through the neural network in order to update old weights. Gradient descent through derivatives is used to correct the weights as much as possible. Derivatives show how the error varies depending on the weights to later apply the proper correction.

In perceptrons, the error function was basically (desired output minus system’s output) but in MLP the squared error function will be used instead :

• It has a sum because each element has its own error and it is necessary to sum them up.
• It is squared because convex functions’ local and global minima are the same.
• It has a to make it simpler when obtaining the derivative.

The following mathematical explanation regarding the formulas for the learning process is based on the 2x3x1 neural network depicted in the first picture of the entry, but before that, some terms need to be introduced to avoid misunderstandings:

Input matrix.
Weights’ matrix that connects the input and hidden layers.
Weights’ matrix that connects the hidden and output layers.
Desired output.
Learning rate.
Content of each node in the hidden layer (before activation).
Content of each node in the hidden layer (after activation).
Content of each node in the output layer (before activation).
MLP output.
Squared error function.

First, let us calculate the update formula for . For this, it is necessary to calculate the derivative of the error with respect to to see how much the error varies depending on .

By the sum rule in differentiation we can take the sum off the fraction, and from now on it is no longer needed since at the end we can sum each sample individually, so let us derive it.

The derivative of y with respect to is 0 since y does not depend on .

By applying the chain rule:

Which finally:

In case of the procedure is very similar:

Learning process (update rules):

Results

The MLP I developed was able to correctly classify samples from its training set from 3 different classes. I have not written a word about overfitting because I will probably do that in a different entry with a good solution to overcome it, but this algorithm probably overfits and cannot classify other samples with the same good result.

Finally, I recorded the evolution of the error with two different learning rate to show that if is too big, it can escape from the minimum with an unknown result. In this case, it resulted absolutely good, but it is not always the case.

Left: . Right:

The code is provided in the Source code section.

References

I strongly recommend the set of videos to which this one belongs to.