Kernel Support Vector Machines for Classification and Regression in C#

Kernel methods in general have gained increased attention in recent years, partly due to the grown of popularity of the Support Vector Machines. Support Vector Machines are linear classifiers and regressors that, through the Kernel trick, operate in reproducing Kernel Hilbert spaces and are thus able to perform non-linear classification and regression in their input space.

Foreword

If you would like to use SVMs in your .NET applications, download the Accord.NET Framework through NuGet. Afterwards, creating support vector machines for binary and multi-class problems with a variety of kernels becomes very easy. The Accord.NET Framework is a LGPL framework which can be used freely in commercial, closed-source, open-source or free applications. This article explains a bit how the SVM algorithms and the overall SVM module was designed before being added as part of the framework.

Contents

  1. Introduction
    1. Support Vector Machines
    2. Kernel Support Vector Machines
      1. The Kernel Trick
      2. Standard Kernels
  2. Learning Algorithms
    1. Sequential Minimal Optimization
  3. Source Code
    1. Support Vector Machine
    2. Kernel Support Vector Machine
    3. Sequential Minimal Optimization
  4. Using the code
  5. Sample application
    1. Classification
    2. Regression
  6. See also
  7. References

Introduction

Support Vector Machines

Support vector machines (SVMs) are a set of related supervised learning methods used for classification and regression. In simple words, given a set of training examples, each marked as belonging to one of two categories, a SVM training algorithm builds a model that predicts whether a new example falls into one category or the other. Intuitively, an SVM model is a representation of the examples as points in space, mapped so that the examples of the separate categories are divided by a clear gap that is as wide as possible. New examples are then mapped into that same space and predicted to belong to a category based on which side of the gap they fall on.

A linear support vector machine is composed of a set of given support vectors z and a set of weights w. The computation for the output of a given SVM with N support vectors z1, z2, … , zN and weights w1, w2, … , wN is then given by:

F(x) = sum_{i=1}^N  w_i , left langle z_i,x right rangle  + b

Kernel Support Vector Machines

The original optimal hyperplane algorithm proposed by Vladimir Vapnik in 1963 was a linear classifier. However, in 1992, Bernhard Boser, Isabelle Guyon and Vapnik suggested a way to create non-linear classifiers by applying the kernel trick (originally proposed by Aizerman et al.) to maximum-margin hyperplanes. The resulting algorithm is formally similar, except that every dot product is replaced by a non-linear kernel function. This allows the algorithm to fit the maximum-margin hyperplane in a transformed feature space. The transformation may be non-linear and the transformed space high dimensional; thus though the classifier is a hyperplane in the high-dimensional feature space, it may be non-linear in the original input space.

Using kernels, the original formulation for the SVM given SVM with support vectors z1, z2, … , zN and weights w1, w2, … , wN is now given by:

F(x) = sum_{i=1}^N  w_i , k(z_i,x) + b

It is also very straightforward to see that, using a linear kernel of the form K(z,x) = <z,x> = zTx, we recover the original formulation for the linear SVM.

The Kernel trick

The Kernel trick is a very interesting and powerful tool. It is powerful because it provides a bridge from linearity to non-linearity to any algorithm that solely depends on the dot product between two vectors. It comes from the fact that, if we first map our input data into a higher-dimensional space, a linear algorithm operating in this space will behave non-linearly in the original input space.

Now, the Kernel trick is really interesting because that mapping does not need to be ever computed. If our algorithm can be expressed only in terms of a inner product between two vectors, all we need is replace this inner product with the inner product from some other suitable space. That is where resides the “trick”: wherever a dot product is used, it is replaced with a Kernel function. The kernel function denotes an inner product in feature space and is usually denoted as:

K(x,y) = <φ(x),φ(y)>

Using the Kernel function, the algorithm can then be carried into a higher-dimension space without explicitly mapping the input points into this space. This is highly desirable, as sometimes our higher-dimensional feature space could even be infinite-dimensional and thus infeasible to compute.

Standard Kernels

Some common Kernel functions include the linear kernel, the polynomial kernel and the Gaussian kernel. Below is a simple list with their most interesting characteristics.

 

Linear Kernel The Linear kernel is the simplest kernel function. It is given by the common inner product <x,y> plus an optional constant c. Kernel algorithms using a linear kernel are often equivalent to their non-kernel counterparts, i.e. KPCA with linear kernel is equivalent to standard PCA. k(x, y) = x^T y + c
Polynomial Kernel The Polynomial kernel is a non-stationary kernel. It is well suited for problems where all data is normalized. k(x, y) = (alpha x^T y + c)^d
Gaussian Kernel The Gaussian kernel is by far one of the most versatile Kernels. It is a radial basis function kernel, and is the preferred Kernel when we don’t know much about the data we are trying to model. k(x, y) = expleft(-frac{ lVert x-y rVert ^2}{2sigma^2}right)

For more Kernel functions, check Kernel functions for Machine Learning Applications. The accompanying source code includes definitions for over 20 distinct Kernel functions, many of them detailed in the aforementioned post.

Learning Algorithms

Sequential Minimal Optimization

Previous SVM learning algorithms involved the use of quadratic programming solvers. Some of them used chunking to split the problem in smaller parts which could be solved more efficiently. Platt’s Sequential Minimal Optimization (SMO) algorithm puts chunking to the extreme by breaking the problem down into 2-dimensional sub-problems that can be solved analytically, eliminating the need for a numerical optimization algorithm.

The algorithm makes use of Lagrange multipliers to compute the optimization problem. Platt’s algorithm is composed of three main procedures or parts:

  • run, which iterates over all points until convergence to a tolerance threshold;
  • examineExample, which finds two points to jointly optimize;
  • takeStep, which solves the 2-dimensional optimization problem analytically.

The algorithm is also governed by three extra parameters besides the Kernel function and the data points.

  • The parameter Ccontrols the trade off between allowing some training errors and forcing rigid margins. Increasing the value of C increases the cost of misclassifications but may result in models that do not generalize well to points outside the training set.
  • The parameter ε controls the width of the ε-insensitive zone, used to fit the training data. The value of ε can affect the number of support vectors used to construct the regression function. The bigger ε, the fewer support vectors are selected and the solution becomes more sparse. On the other hand, increasing the ε-value by too much will result in less accurate models.
  • The parameter T is the convergence tolerance. It is the criterion for completing the training process.

After the algorithm ends, a new Support Vector Machine can be created using only the points whose Lagrange multipliers are higher than zero. The expected outputs yi can be individually multiplied by their corresponding Lagrange multipliers ai to form a single weight vector w.

F(x) = sum_{i=0}^N { alpha_i y ,  k(z_i,x) } + b = sum_{i=0}^N { w_i , k(z_i,x) } + b

Sequential Minimal Optimization for Regression

A version of SVM for regression was proposed in 1996 by Vladimir Vapnik, Harris Drucker, Chris Burges, Linda Kaufman and Alex Smola. The method was called support vector regression and, as is the case with the original Support Vector Machine formulation, depends only on a subset of the training data, because the cost function for building the model ignores any training data close to the model prediction that is within a tolerance threshold ε.

Platt’s algorithm has also been modified for regression. Albeit still maintaining much of its original structure, the difference lies in the fact that the modified algorithm uses two Lagrange multipliers âi and ai for each input point i. After the algorithm ends, a new Support Vector Machine can be created using only points whose both Lagrange multipliers are higher than zero. The multipliers âi and ai are then subtracted to form a single weight vector w.

F(x) = sum_{i=0}^N { (hat{alpha_i} - alpha_i) ,  k(z_i,x) } + b = sum_{i=0}^N { w_i , k(z_i,x) } + b

The algorithm is also governed by the same three parameters presented above. The parameter ε, however, receives a special meaning. It governs the size of the ε-insensitive tube over the regression line. The algorithm has been further developed and adapted by Alex J. Smola, Bernhard Schoelkopf and further optimizations were introduced by Shevade et al and Flake et al.

Source Code

Here is the class diagram for the Support Vector Machine module. We can see it is very simple in terms of standard class organization.

svm-classdiagram1

Class diagram for the (Kernel) Support Vector Machines module.

Support Vector Machine

Below is the class definition for the Linear Support Vector Machine. It is pretty much self explanatory.

Kernel Support Vector Machine

Here is the class definition for the Kernel Support Vector Machine. It inherits from Support Vector Machine and extends it with a Kernel property. The Compute method is also overridden to include the chosen Kernel in the model computation.

Sequential Minimal Optimization

Here is the code for the Sequential Minimal Optimization (SMO) algorithm.

Using the code

In the following example, we will be training a Polynomial Kernel Support Vector Machine to recognize the XOR classification problem. The XOR function is classic example of a pattern classification problem that is not linearly separable.

Here, remember that the SVM is a margin classifier that classifies instances as either 1 or –1. So the training and expected output for the classification task should also be in this range. There are no such requirements for the inputs, though.

To create the Kernel Support Vector Machine with a Polynomial Kernel, do:

After the machine has been created, create a new Learning algorithm. As we are going to do classification, we will be using the standard SequentialMinimalOptimization algorithm.

After the model has been trained, we can compute its outputs for the given inputs.

The machine should be able to correctly identify all of the input instances.

Sample application

The sample application is able to perform both Classification and Regression using Support Vector Machines. It can read Excel spreadsheets and determines the task to be performed depending on the number of the columns in the sheet. If the input table contains two columns (e.g. X and Y) it will be interpreted as a regression problem X –> Y. If the input table contains three columns (e.g. x1, x2 and Y) it will be interpreted as a classification problem <x1,x2> belongs to class Y, Y being either 1 or -1.

Classification

To perform classification, load a classification task data such as the Yin Yang classification problem.

svm2-1

Yin Yang classification problem. The goal is to create a model which best determines whether a given point belongs to class blue or green. It is a clear example of a non-linearly separable problem.

svm2-2 svm2-3

Creation of a Gaussian Kernel Support Vector Machine with σ = 1.2236, C = 1.0, ε = 0.001 and T = 0.001.

svm2-4

Classification using the created Support Vector Machine. Notice it achieves an accuracy of 97%, with sensitivity and specifity rates of 98% and 96%, respectively.

Regression

To perform regression, we can load the Gaussian noise sine wave example.

svm2-7

Noise sine wave regression problem.

 

svm2-9 svm2-8

Creation of a Gaussian Kernel Support Vector Machine with σ = 1.2236, C = 1.0, ε = 0.2 and T = 0.001.

After the model has been created, we can plot the model approximation for the sine wave data. The blue line shows the curve approximation for the original red training dots.

svm2-10

Regression using the created Kernel Support Vector Machine. Notice the coefficient of determination r² of 0.95. The closer to one, the better.

See also

 

References

Java over-engineered?

The following gem, that belongs into a Java programming best practices book, was found in the source of Sun’s JDK.

Well, I must confess this is almost better than the simple Hello World in Java [cached copy].

Partial Least Squares Analysis and Regression in C#

PLS-2_thumb-5B3-5D

Partial Least Squares Regression (PLS) is a technique that generalizes and combines features from principal component analysis and (multivariate) multiple regression. It has been widely adopted in the field of chemometrics and social sciences.

The code presented here is also part of the Accord.NET Framework. The Accord.NET Framework is a framework for developing machine learning, computer vision, computer audition, statistics and math applications. Please see the starting guide for mode details. The latest version of the framework includes the latest version of this code plus many other statistics and machine learning tools.

Contents

  1. Introduction
  2. Overview
    1. Multivariate Linear Regression in Latent Space
    2. Algorithm 1: NIPALS
    3. Algorithm 2: SIMPLS
  3. Source Code
    1. Class Diagram
    2. Performing PLS using NIPALS
    3. Performing PLS using SIMPLS
    4. Multivariate Linear Regression
  4. Using the code
  5. Sample application
  6. See also
  7. References

Introduction

Partial least squares regression (PLS-regression) is a statistical method that is related to principal components regression. The goal of this method is to find a linear regression model by projecting both the predicted variables and the observable variables to new, latent variable spaces. It was developed in the 1960s by Herman Wold to be used in econometrics. However, today it is most commonly used for regression in the field of chemometrics.

In statistics, latent variables (as opposed to observable variables), are variables
that are not directly observed but are rather inferred (through a mathematical model) from other variables that are observed (directly measured). Mathematical models that aim to explain observed variables in terms of latent variables are called latent variable models.

A PLS model will try to find the multidimensional direction in the X space that explains the maximum multidimensional variance direction in the Y space. PLS-regression is particularly suited when the matrix of predictors has more variables
than observations, and when there is multicollinearity among X values. Its interesting to note that standard linear regression would likely fail to produce meaningful interpretable models in those cases.

Overview

Multivariate Linear Regression in Latent Space

linear-regressionMultiple Linear Regression is a generalization of simple linear regression for multiple inputs. In turn, Multivariate Linear Regression is a generalization of Multiple Linear Regression for multiple outputs. The multivariate linear regression is a general linear regression model which can map an arbitrary dimension space into another arbitrary dimension space using only linear relationships. In the context of PLS, it is used to map the latent variable space for the inputs X into the latent variable space for the output variables Y. Those latent variable spaces are spawned by the loading matrices for X and Y, commonly denoted P and Q, respectively.

The goal of PLS algorithms are therefore to find those two matrices. There are mainly two algorithms to do this: NIPALS and SIMPLS.

Algorithm 1: NIPALS

Here is an exposition of the NIPALS algorithm for finding the loading matrices required for PLS regression. There are, however, many variations of this algorithm which normalize or do not normalize certain vectors.

Algorithm:

  • Let X be the mean-centered input matrix,
  • Let Y be the mean-centered output matrix,
  • Let P be the loadings matrix for X, and let pdenote the i-th column of P;
  • Let Q be the loadings matrix for Y, and let qdenote the i-th column of Q;
  • Let T be the score matrix for X, and tdenote the i-th column of T;
  • Let U be the score matrix for Y, and udenote the i-th column of U;
  • Let W be the PLS weight matrix, and wdenote the i-th column of W; and
  • Let B be a diagonal matrix of diagonal coefficients bi

Then:

  1. For each factor i to be calculated:
    1. Initially choose ui as the largest column vector in
      X (having the largest sum of squares)
    2. While (ti has not converged to a desired precision)
      1. wi ∝ X’u(estimate X weights)
      2. ti ∝ Xw(estimate X factor scores)
      3. qi ∝ Y’t(estimate Y weights)
      4. ui = Yq(estimate Y scores)
    3. bi = t’u (compute prediction coefficient b)
    4. pi = X’t (estimate X factor loadings)
    5. X = X – tp’ (deflate X)

In other statistical analysis such as PCA, it is often interesting to inspect how much of the variance can be explained by each of the principal component dimensions. The same can also be accomplished for PLS, both for the input (predictor) variables X and outputs (regressor) variables Y. For the input variables, the amount of variance explained by each factor can be computed as bi². For outputs, it can be computed as the sum of the squared elements of its column in the matrix P,  i.e. as Sum(pi²).

Algorithm 2: SIMPLS

SIMPLS is an alternative algorithm for finding the PLS matrices P and Q that has been derived considering the true objective of maximizing the covariance between the latent factors and the output vectors. Both NIPALS and SIMPLS are equivalent when there is just one output variable Y to be regressed. However, their answers can differ when Y is multi-dimensional. However, because the construction of the weight vectors used by SIMPLS is based on the empirical variance–covariance matrix of the joint input and output variables, outliers present in the data can adversely impact its performance.

Algorithm:

  • Let X be the mean-centered input matrix,
  • Let Y be the mean-centered output matrix,
  • Let P be the loadings matrix for X, and let pi denote the i-th column of P;
  • Let C be the loadings matrix for Y, and let ci denote the i-th column of C;
  • Let T be the score matrix for X, and ti denote the i-th column of T;
  • Let U be the score matrix for Y, and ui denote the i-th column of U; and
  • Let W be the PLS weight matrix, and wi denote the i-th column of W.

Then:

  1. Create the covariance matrix C = X’Y
  2. For each factor i to be calculated:
    1. Perform SVD on the covariance matrix and store the first left singular vector in wi and the first right singular value times the singular values in ci.
    2. ti ∝ X*wi            (estimate X factor scores)
    3. pi = X’*ti           (estimate X factor loadings)
    4. ci = ci/norm(ti)     (estimate Y weights)
    5. wi = wi/norm(ti)     (estimate X weights)
    6. ui = Y*ci            (estimate Y scores)
    7. vi = pi              (form the basis vector vi)
    8. Make v orthogonal to the previous loadings V
    9. Make u orthogonal to the previous scores T
    10. Deflate the covariance matrix C
      1. C = C – vi*(vi‘*C)

 

Source Code

This section contains the realization of the NIPALS and SIMPLS algorithms in C#. The models have been implemented considering an object-oriented structure that is particularly suitable to be data-bound to Windows.Forms (or WPF) controls.

Class Diagram

pls-diagram

Class diagram for the Partial Least Squares Analysis.

Performing PLS using NIPALS

Here is the source code for computing PLS using the NIPALS algorithm:

Performing PLS using SIMPLS

And here is the source code for computing PLS using the SIMPLS algorithm:

Multivariate Linear Regression

Multivariate Linear Regression is computed in a similar manner to a Multiple Linear Regression. The only difference is that, instead of having a weight vector and a intercept, we have a weight matrix and a intercept vector.

The weight matrix and the intercept vector are computed in the PartialLeastSquaresAnalysis class by the CreateRegression method. In case the analyzed data already was mean centered before being fed to the analysis, the constructed intercept vector will consist only of zeros.

 

Using the code

As an example, lets consider the example data from Hervé Abdi, where the goal is to predict the subjective evaluation of a set of 5 wines. The dependent variables that we want to predict for each wine are its likeability, and how well it goes with meat, or dessert (as rated by a panel of experts). The predictors are the price, the sugar, alcohol, and acidity content of each wine.

Next, we proceed to create the Partial Least Squares Analysis using the Covariance
method (data will only be mean centered but not normalized) and using the SIMPLS
algorithm.

After the analysis has been computed, we can proceed and create the regression model.

Now after the regression has been computed, we can find how well it has performed. The coefficient of determination r² for the variables Hedonic, Goes with Meat and Goes with Dessert can be computed by the CoefficientOfDetermination method of the MultivariateRegressionClass and will be, respectively, 0.9999, 0.9999 and 0.8750 – the closer to one, the better.

Sample application

The accompanying sample application performs Partial Least Squares Analysis and Regression in Excel worksheets. The predictors and dependent variables can be selected once the data has been loaded in the application.

Wine example from Hervé Abdi Variance explained by PLS using the SIMPLS algorithm
Left: Wine example from Hervé Abdi. Right: Variance explained by PLS using the SIMPLS algorithm

 

Partial Least Squares Analysis results and regression coefficients for the full regression model Projection of the dependent and predictors variables using the three first factors
Left: Partial Least Squares Analysis results and regression coefficients for the
full regression model. Right: projection of the dependent and predictors variables
using the three first factors.


Results from the Multivariate Linear Regression performed in Latent Space using three factors from PLS
Results from the Multivariate Linear Regression performed in Latent Space using
three factors from PLS.

Example data from Geladi and Kowalski in the PLS sample application Analysis results for the data using NIPALS. We can see that just two factors are enough to explain the whole variance of the set.
Left: Example data from Geladi and Kowalski. Right: Analysis results for the data using NIPALS. We can see that just two factors are enough to explain the whole variance of the set.

 

Projections to the latent spaces detected by the Partial Least Squares Analysis Loadings and coefficients for the two factor Multivariate Linear Regression (MLR) model discovered by Partial Least Squares (PLS)
Left: Projections to the latent spaces. Right: Loadings and coefficients for the
two factor Multivariate Linear Regression model.


Results from the Partial Least Squares Regression showing a perfect fit using only the first two factors

Results from the Partial Least Squares Regression showing a perfect fit using only the first two factors.

 

References

 

See also

Cleaning Cached Blog Entries in Google Reader – Or: How to Remove Unwanted Posts from Google Reader

While I was working on my next article using Windows Live Writer, I’ve hit the “publish” button too soon and ended up with a published draft in my blog. I just went and re-drafted the entry, thinking everything was going to be fine. Unfortunately, I did not realize that Google Reader automatically caches everything it finds, and do not delete entries even if them have been deleted from their original blog.

After some researching, I’ve found out that if I published a new post with the same GUID as the unwanted entry, it would be automatically updated in Reader. So here are the steps to remove an unwanted blog post from Google Reader:

Removing an unwanted blog post from Google Reader

Step 1: Consulting Reader’s cache

Type the following address in your address bar, substituting yourblogname by your actual blog name:

http://www.google.com/reader/atom/feed/http://yourblogname.blogspot.com/feeds/posts/default?r=n&n=100

Go to the page, then right click its content and select “View page source” or equivalent.

Step 2: Find the offending post

Find the string “blogger.googleusercontent.com/tracker/” and notice the two numbers that come after it:

https://blogger.googleusercontent.com/tracker/88422212108117265282876694319097447217?l=yourblog.blogspot.com

Those are your blog ID and post ID, respectively.

Step 3: Resurrection!

Copy and paste these two numbers in the placeholders of the following URL:

http://draft.blogger.com/post-edit.g?blogID=yourblogid&postID=yourpostid

Finally, open this URL and watch your once deleted (?) blog post be resurrected from the dead. Update it or just leave it blank, set the post date to the future and publish it again. Voilà!

 

Update: Unfortunately, the original post title will remain as the URL for the entry. As you can see, this was going to be a post about Partial Least Squares Analysis. However, I’ll leave it as is to prove this procedure really works. Cheers!

Update 2: I made a simple application to browse and edit deleted blogger posts that have been cached by Google Reader. The program, together with the C# source code can be found here. The program uses the Google Reader API developed by Matt Berseth.