Reading history

Support Vector Machine (SVM) in Python with Scikit-learn

5 min read 2 views

Learn support vector machines in Python: maximum margin, support vectors, linear, polynomial and RBF kernels, and the C and gamma parameters.

Many lines can separate two groups of points, but some are safer than others. A support vector machine (SVM) chooses the boundary that stays as far as possible from the nearest points of each class, giving the widest possible gap, or margin. With the kernel trick, SVMs can also draw curved boundaries without ever computing new features explicitly, which made them one of the most successful classifiers before deep learning.

In this lesson you will learn

  • The maximum-margin idea and support vectors
  • Training a linear SVM with SVC
  • Kernels: linear, polynomial and RBF
  • The C parameter and soft margins
  • Why SVMs need scaled features

This lesson builds on logistic regression and feature scaling.

The Maximum-Margin Line

import numpy as np
from sklearn.svm import SVC

# Two small groups of points that can be separated by a straight line
X = np.array([[1, 2], [2, 3], [2, 1], [3, 2],      # class 0
              [6, 5], [7, 7], [8, 6], [7, 5]])     # class 1
y = np.array([0, 0, 0, 0, 1, 1, 1, 1])

model = SVC(kernel="linear", C=1.0).fit(X, y)

w, b = model.coef_[0], model.intercept_[0]
print("Decision line: {:.2f}*x1 + {:.2f}*x2 {:+.2f} = 0".format(w[0], w[1], b))
print("Support vectors:\n", model.support_vectors_)
print("Margin width: {:.2f}".format(2 / np.linalg.norm(w)))
print("Predictions for (3,4) and (6,6):", model.predict([[3, 4], [6, 6]]))

Output

Decision line: 0.33*x1 + 0.33*x2 -2.67 = 0
Support vectors:
 [[3. 2.]
 [6. 5.]]
Margin width: 4.24
Predictions for (3,4) and (6,6): [0 1]
  • The learned boundary is the line 0.33·x1 + 0.33·x2 − 2.67 = 0, which is x1 + x2 = 8: points whose coordinates add up to less than 8 are class 0.
  • Only two points, (3, 2) and (6, 5), touch the edges of the margin. These are the support vectors. Moving any other point (without crossing the margin) would not change the model at all.
  • The margin width is 2 / ‖w‖ = 4.24, the distance between the two closest points measured across the boundary.
  • New points are classified by which side of the line they fall on: (3, 4) sums to 7, below 8, so it is class 0; (6, 6) sums to 12, so it is class 1.

Kernels and the C Parameter

from sklearn.datasets import make_circles
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

# Points in two rings: no straight line can separate them
X, y = make_circles(n_samples=300, factor=0.4, noise=0.08, random_state=3)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3)

for kernel in ["linear", "poly", "rbf"]:
    model = SVC(kernel=kernel, degree=2, gamma="scale").fit(X_train, y_train)
    print(f"{kernel:6s} kernel accuracy: {model.score(X_test, y_test):.3f}")

print()
for C in [0.01, 1, 100]:
    model = SVC(kernel="rbf", C=C).fit(X_train, y_train)
    print(f"RBF with C={C:<5}: support vectors = {model.n_support_.sum():3d}, "
          f"test accuracy = {model.score(X_test, y_test):.3f}")

Output

linear kernel accuracy: 0.444
poly   kernel accuracy: 1.000
rbf    kernel accuracy: 1.000

RBF with C=0.01 : support vectors = 201, test accuracy = 0.444
RBF with C=1    : support vectors =  28, test accuracy = 1.000
RBF with C=100  : support vectors =  11, test accuracy = 1.000
  • The two classes form an inner and an outer ring. A straight line cannot separate them, so the linear kernel scores only 44%.
  • A kernel measures similarity as if the points had been mapped into a higher-dimensional space where a flat boundary works. A degree-2 polynomial kernel and the RBF (radial basis function) kernel both find the circular boundary and score 100%.
  • C controls how much the SVM is penalised for points inside the margin or on the wrong side. A tiny C (0.01) allows almost every point to be a support vector and underfits. Larger C values fit the training data more tightly with fewer support vectors; too large can overfit noisy data.
  • For the RBF kernel, gamma sets how far each point’s influence reaches. gamma="scale" picks a sensible default from the data.

SVM Settings at a Glance

SettingSmall valueLarge value
CWide, soft margin; simpler model; may underfitNarrow margin; fits training data closely; may overfit
gamma (RBF)Smooth, broad boundaryWiggly boundary around individual points
kernel"linear" for many features (such as text), "rbf" as the general default, "poly" for known polynomial patterns

Choose C and gamma together with grid search. Always scale features first, because the margin is measured in distance.

Common Mistakes

  1. Not scaling features, so one large-valued feature dominates the distances.
  2. Using an RBF SVM on hundreds of thousands of rows; training time grows roughly with the square of the number of samples. Try LinearSVC or another model.
  3. Tuning C without gamma for the RBF kernel; they interact strongly.
  4. Expecting probabilities by default; SVC needs probability=True, which adds extra training time.

Practice Exercises

Exercise 1. Train an SVM on the wine dataset with and without scaling and compare test accuracy.

Show answer
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0, stratify=y)
print(SVC().fit(X_tr, y_tr).score(X_te, y_te))
print(make_pipeline(StandardScaler(), SVC()).fit(X_tr, y_tr).score(X_te, y_te))

The scaled version is far more accurate, because the proline feature no longer swamps the rest.

Exercise 2. In the first example, would adding the point (1, 1) to class 0 change the boundary?

Show answer

No. (1, 1) is far from the boundary and outside the margin, so it would not become a support vector. Only points on or inside the margin affect an SVM.

Frequently Asked Questions

Can SVMs do regression?

Yes. SVR fits a tube of width epsilon around the data and ignores errors inside it, using the same kernels and C parameter.

How do SVMs handle more than two classes?

SVC trains one SVM for every pair of classes (one-vs-one) and lets them vote. This happens automatically when y has more than two labels.

Summary

  • An SVM picks the boundary with the widest margin; only support vectors define it.
  • Kernels such as RBF give curved boundaries.
  • C trades margin width against training errors; gamma controls RBF flexibility.
  • Scale features and tune C and gamma together.

Next: Principal Component Analysis (PCA).

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *