The mathematics that powers a support vector machine (SVM) classifier is beautiful. It is important to not only learn the basic model of an SVM but also know how you can implement the entire model from scratch. This is a continuation of our series of tutorials on SVMs. In part1 and part2 of this series we discussed the mathematical model behind a linear SVM. In this tutorial, we’ll show how you can build an SVM linear classifier using the optimization routines shipped with Python’s SciPy library.
After completing this tutorial, you will know:
- How to use SciPy’s optimization routines
- How to define the objective function
- How to define bounds and linear constraints
- How to implement your own SVM classifier in Python
Let’s get started.
Tutorial Overview
This tutorial is divided into 2 parts; they are:
- The optimization problem of an SVM
- Solution of the optimization problem in Python
- Define the objective function
- Define the bounds and linear constraints
- Solve the problem with different C values
Pre-requisites
For this tutorial, it is assumed that you are already familiar with the following topics. You can click on the individual links to get more details.
- A Gentle Introduction to Optimization / Mathematical Programming
- A Gentle Introduction To Method Of Lagrange Multipliers
- Lagrange Multiplier Approach with Inequality Constraints
- Method Of Lagrange Multipliers: The Theory Behind Support Vector Machines (Part 1: The Separable Case))
- Method Of Lagrange Multipliers: The Theory Behind Support Vector Machines (Part 2: The Non-Separable Case
Notations and Assumptions
A basic SVM machine assumes a binary classification problem. Suppose, we have
: Total training points : Dimensionality of each training point : Data point, which is an -dimensional vector : Subscript used to index the training points. : Subscript used to index the training points. : Subscript used to index each dimension of a training point : Label of a data point. It is an -dimensional vector, with : Transpose operator : Weight vector denoting the coefficients of the hyperplane. It is also an -dimensional vector : Vector of Lagrange multipliers, also an -dimensional vector : User defined penalty factor/regularization constant
The SVM Optimization Problem
The SVM classifier maximizes the following Lagrange dual given by:
The above function is subject to the following constraints:
All we have to do is find the Lagrange multiplier
Want to Get Started With Calculus for Machine Learning?
Take my free 7-day email crash course now (with sample code).
Click to sign-up and also get a free PDF Ebook version of the course.
Python Implementation of SVM
We’ll use the SciPy optimize package to find the optimal values of Lagrange multipliers, and compute the soft margin and the separating hyperplane.
Import Section and Constants
Let’s write the import section for optimization, plotting and synthetic data generation.
We also need the following constant to detect all alphas numerically close to zero, so we need to define our own threshold for zero.
Defining the Data Points and Labels
Let’s define a very simple dataset, the corresponding labels and a simple routine for plotting this data. Optionally, if a string of alphas is given to the plotting function, then it will also label all support vectors with their corresponding alpha values. Just to recall support vectors are those points for which
The minimize() Function
Let’s look at the minimize() function in scipy.optimize library. It requires the following arguments:
- The objective function to minimize. Lagrange dual in our case.
- The initial values of variables with respect to which the minimization takes place. In this problem, we have to determine the Lagrange multipliers
. We’ll initialize all randomly. - The method to use for optimization. We’ll use
trust-constr. - The linear constraints on
. - The bounds on
.
Defining the Objective Function
Our objective function is minimize() function, we have to multiply
You can shorten the code for the lagrange_dual() function given below by using matrices. However, in this tutorial, it is kept very simple to make everything clear.
Defining the Linear Constraints
The linear constraint on alpha for each point is given by:
We can also write this as:
The LinearConstraint() method requires all constraints to be written as matrix form, which is:
The first matrix is the first parameter in the LinearConstraint() method. The left and right bounds are the second and third arguments.
Defining the Bounds
The bounds on alpha are defined using the Bounds() method. All alphas are constrained to lie between 0 and
Defining the Function to Find Alphas
Let’s write the overall routine to find the optimal values of alpha when given the parameters x, t, and C. The objective function requires the additional arguments x and t, which are passed via args in minimize().
Determining the Hyperplane
The expression for the hyperplane is given by:
For the hyperplane, we need the weight vector
If there are too many training points, it’s best to use only support vectors with
For
A support vector’s alpha cannot be numerically exactly equal to C. Hence, we can subtract a small constant from C to find all support vectors with get_w0() function.
Classifying Test Points
To classify a test point
Let’s write the corresponding function that can take as argument an array of test points along with
Plotting the Margin and Hyperplane
Let’s also define functions to plot the hyperplane and the soft margin.
Powering Up The SVM
It’s now time to run the SVM. The function display_SVM_result() will help us visualize everything. We’ll initialize alpha to random values, define C and find the best values of alpha in this function. We’ll also plot the hyperplane, the margin and the data points. The support vectors would also be labelled by their corresponding alpha value. The title of the plot would be the percentage of errors and number of support vectors.
The Effect of C
If you change the value of C to C on classification. To understand the entire problem, we’ll use a simple dataset, where the positive and negative examples are separable.
Below are the points generated via make_blobs():
Now let’s define different values of C and run the code.
Comments on the Result
The above is a nice example, which shows that increasing
Consolidated Code
Here is the consolidated code, that you can paste in your Python file and run it at your end. You can experiment with different values of minimize() function.
Further Reading
This section provides more resources on the topic if you are looking to go deeper.
Books
- Pattern Recognition and Machine Learning by Christopher M. Bishop
Articles
- Support Vector Machines for Machine Learning
- A Tutorial on Support Vector Machines for Pattern Recognition by Christopher J.C. Burges
API Reference
- SciPy’s optimization library
- Scikit-learn’s sample generation library (sklearn.datasets)
- NumPy random number generator
Summary
In this tutorial, you discovered how to implement an SVM classifier from scratch.
Specifically, you learned:
- How to write the objective function and constraints for the SVM optimization problem
- How to write code to determine the hyperplane from Lagrange multipliers
- The effect of C on determining the margin
Do you have any questions about SVMs discussed in this post? Ask your questions in the comments below and I will do my best to answer.




No comments:
Post a Comment