Product

Tuesday, 20 February 2024

Method of Lagrange Multipliers: The Theory Behind Support Vector Machines (Part 3: Implementing An SVM From Scratch In Python)

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:

  1. The optimization problem of an SVM
  2. Solution of the optimization problem in Python
    1. Define the objective function
    2. Define the bounds and linear constraints
  3. 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.

Notations and Assumptions

A basic SVM machine assumes a binary classification problem. Suppose, we have  training points, each point being an -dimensional vector. We’ll use the following notations:

  • : Total training points
  • : Dimensionality of each training point
  • : Data point, which is an -dimensional vector
  • : Subscript used to index the training points. 0<
  • : Subscript used to index the training points. 0<
  • : Subscript used to index each dimension of a training point
  • : Label of a data point. It is an -dimensional vector, with {1,+1}
  • : 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:
=12()()+

The above function is subject to the following constraints:

0,=0

All we have to do is find the Lagrange multiplier  associated with each training point, while satisfying the above constraints.

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

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  defined above, which has to be maximized. As we are using the minimize() function, we have to multiply  by (-1) to maximize it. Its implementation is given below. The first parameter for the objective function is the variable w.r.t. which the optimization takes place. We also need the training points and the corresponding labels as additional arguments.

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:

=0

We can also write this as:
00+11+=0

The LinearConstraint() method requires all constraints to be written as matrix form, which is:

0=[01][01]=0

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 . Here is an example for =10.

Defining the Function to Find Alphas

Let’s write the overall routine to find the optimal values of alpha when given the parameters xt, 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:
+0=0

For the hyperplane, we need the weight vector  and the constant 0. The weight vector is given by:
=

If there are too many training points, it’s best to use only support vectors with >0 to compute the weight vector.

For 0, we’ll compute it from each support vector , for which <, and then take the average. For a single support vector 0 is given by:

0=

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 <. This is done in the get_w0() function.

Classifying Test Points

To classify a test point , we use the sign of () as:

label=sign(())=sign(+0)

Let’s write the corresponding function that can take as argument an array of test points along with  and 0 and classify various points. We have also added a second function for calculating the misclassification rate:

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 , then the soft margin turns into a hard margin, with no toleration for errors. The problem we defined above is not solvable in this case. Let’s generate an artificial set of points and look at the effect of 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 , decreases the margin. A high value of  adds a stricter penalty on errors. A smaller value allows a wider margin and more misclassification errors. Hence,  defines a tradeoff between the maximization of margin and classification errors.

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  and try out the different optimization methods given as arguments to the minimize() function.

 

Further Reading

This section provides more resources on the topic if you are looking to go deeper.

Books

Articles

API Reference

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

Connect broadband

AI:List AI views on when for a naive kin after prolonged life suppression coercive behaviour by family members after demise of father with trauma for kin ocd formed after forced to do rituals, family tribal values honor specific activities, utmost religious activities occult witchcraft enforced to do by elder sibling his wife and mother thrice with great celibacy turned the kundalini activated after deep celibacy penance shouting physical Mental financial Extortion by sibling with toxic behaviours and the wife mother and then mockery suppression asking about who’re your worth backbiting among relatives sector toon negligence of intelligence intuitive behaviour- all religious psychological traps when not work and lead to loss of consciousness of kin trance state recovered by governance with technocrats using AI - kin was asked by mother that he’s to go the male should not be seen in house he’s many absurd thought forcefully in brain mind and outsiders already feel awkward of this kin unresponsive behaviour due to TBI PTSD ocd cvt and tell at workplace social gathering he’s to go and asked for sector toon extortion and mockery in various sense due to un practical behaviour negligence of body building due to neglect ion if essential food nutrition and stubbed suppressed in every sense in religious psychological traps by family members AI humanoid using various neural networks and LLMs for kin and required steps.

  List AI views on when for a naive kin after prolonged life suppression coercive behaviour by family members after demise of father with tr...