Support vector machines

Find the boundary with the widest possible margin between classes, and bend it with a kernel when a straight line is not enough.

Lesson 30 of 6614 minIntermediate

You will learn to

  • Explain the maximum-margin idea and what a support vector is
  • Describe how the penalty C and the kernel parameter gamma change the boundary
  • Say when an SVM is a good choice and why it needs scaled inputs

Before this lesson

Intuition

Picture two groups of people standing on a field, and you must paint a line on the grass to separate them. Many lines work. Which one is best? A line that runs very close to one person is fragile: if that person takes one step, they are on the wrong side. A good line stays as far as possible from both groups. A support vector machine (SVM) finds exactly that line, the one with the widest empty strip, the margin, between the classes.

Only a few rows decide where the strip goes: the rows right at its edges. They are the support vectors. All other rows could be removed, and the line would not move.

Real data is rarely separable by a straight line, and some rows are mislabelled or noisy. Two ideas handle that. A soft margin lets a few rows be inside the strip or on the wrong side, for a price set by the parameter C. And the kernel trick lets the SVM draw curved boundaries by measuring similarity between rows in a smarter way, without building the new features explicitly.

Picture it

Decision boundaryMarginSupport vectorsSupport vectors
The boundary sits in the middle of the widest empty strip. The circled points touch the strip and are the support vectors; the other points do not influence the boundary.

Two things follow from the picture. The model depends only on a few rows, which makes it stable against rows far from the boundary. And it depends on distances, so the scale of each column matters a great deal.

The math

A linear SVM scores a row with f(x)=w⋅x+bf(x) = w \cdot x + b and predicts the class from the sign of f(x)f(x). The margin lines are where f(x)=+1f(x) = +1 and f(x)=−1f(x) = -1, so the width of the strip is 2/∥w∥2 / \lVert w \rVert. Making the strip wide means making ∥w∥\lVert w \rVert small. With a soft margin, the training problem is

min⁡w,b 12∥w∥2+C∑imax⁡ ⁣(0, 1−yif(xi))\min_{w,b}\ \tfrac{1}{2}\lVert w\rVert^{2} + C \sum_{i} \max\!\big(0,\ 1 - y_i f(x_i)\big)

with labels yiy_i equal to +1 or -1. The second term is the hinge loss: it is zero for rows on the correct side of their margin line and grows linearly for rows inside the strip or on the wrong side. A large CC makes margin violations expensive; a small CC favours a wide margin.

The RBF kernel replaces the plain dot product with a similarity that falls as two rows move apart:

K(x,x′)=exp⁡ ⁣(−γ ∥x−x′∥2)K(x, x') = \exp\!\big(-\gamma\,\lVert x - x'\rVert^{2}\big)

The parameter γ\gamma sets how quickly similarity fades. A large γ\gamma makes each row influence only its close neighbours, giving a wiggly boundary that can overfit. A small γ\gamma gives smooth, almost linear boundaries.

Worked example

Take one input with negatives at x = 1 and x = 2 and positives at x = 4 and x = 5. The widest strip lies between the closest opposite rows, x = 2 and x = 4, so the boundary is at x = 3.

  • The score is f(x) = x - 3, so w = 1 and b = -3.
  • At the support vectors, f(2) = -1 and f(4) = +1: exactly on the margin lines.
  • The margin width is 2 / |w| = 2, the distance from 2 to 4.
  • The rows at x = 1 and x = 5 have scores -2 and +2. They are not support vectors; removing them would not move the boundary.

We checked this with scikit-learn's SVC using a linear kernel and a very large C: it returns w = 1, b = -3 and support vectors at 2 and 4.

For the RBF kernel with γ=0.5\gamma = 0.5, two rows at distance 1 have similarity exp(-0.5) = 0.61, and two rows at distance 2 have exp(-2) = 0.14. With γ=5\gamma = 5, the same distances give 0.007 and almost zero, so each row only "sees" its immediate neighbours.

A computed comparison on a sample dataset with 768 rows, with a standard scaler and 5-fold stratified cross-validation in scikit-learn (seed 42, accuracy, scikit-learn default settings):

ModelAccuracy
Linear SVM0.771
RBF SVM, C = 0.10.753
RBF SVM, C = 10.762
RBF SVM, C = 100.728
RBF SVM, C = 1000.698

Raising C beyond 1 made the boundary chase noise, and the score fell. On this nearly linear problem, the simple linear SVM is as good as any.

How mlflow does it

Classification has SVM - Linear Kernel (svm) and SVM - Radial Kernel (rbfsvm). The linear one is trained by stochastic gradient descent with the hinge loss, so it scales to many rows and its tuning parameters are alpha (the penalty strength, where larger means more regularization), penalty, l1_ratio and learning_rate, not C. The radial one is a full kernel SVM with C set to 1 by default (searched from 0 to 50) and gamma set to auto, and it returns probabilities. Regression has Support Vector Regression (svm) with C, epsilon and shrinking. Add a scaler step before any SVM. A kernel SVM needs time that grows quickly with the number of rows, so it suits small and medium tables.

Common mistakes

  • Forgetting to scale. A column in the thousands dominates the distance. Scale first, and fit the scaler inside each fold.
  • Using a high C to push the training score up. It narrows the margin and overfits. Choose C by cross-validation, on a log scale such as 0.1, 1, 10.
  • Using a kernel SVM on a very large table. Training time grows quickly with the number of rows. Try the linear SVM or logistic regression first.
  • Expecting calibrated probabilities from the margin. The distance to the boundary is not a probability. Use the probability output and check calibration if you need risks.
  • Reaching for the RBF kernel by default. If a linear model scores about the same, keep the simpler one.

Try it in mlflow

Compare a linear and a radial SVM

  1. Open Pipelines and pick a classification pipeline.
  2. In the Columns part choose Standardise for the numeric columns, then open the Models part and add SVM - Linear Kernel and SVM - Radial Kernel.
  3. Click Train 2 algorithms and open the run.
  4. Compare the cross-validated scores. Then switch SVM - Radial Kernel to Manual, change C, train again and see how the score moves.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. What is a support vector?
  2. 2. You raise C a lot in an SVM with an RBF kernel. What is the most likely effect?
  3. 3. Why should inputs be scaled before an SVM?