Skip to main content

Support vector machines

Examples

The maximal margin

fitting and drawing
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC

rng = np.random.default_rng(3)
X = np.vstack([rng.normal([0, 0], 0.6, (15, 2)), rng.normal([2.5, 2.2], 0.6, (15, 2))])
y = np.array([-1] * 15 + [1] * 15)
svm = SVC(kernel="linear", C=1e6).fit(X, y)

g1, g2 = np.meshgrid(np.linspace(-1.5, 4, 200), np.linspace(-2, 4, 200))
f = svm.decision_function(np.column_stack([g1.ravel(), g2.ravel()])).reshape(g1.shape)
fig, axes = plt.subplots(1, 2, figsize=(8, 3.8))
for ax in axes:
    ax.scatter(X[:, 0], X[:, 1], c=np.where(y == 1, "C1", "C0"), s=16)
    ax.set(xlim=(-1.5, 4), ylim=(-2, 4), aspect="equal", xlabel="$x_1$", ylabel="$x_2$")
x1 = np.linspace(-1.5, 4, 2)
for slope, intercept in [(-0.6, 1.8), (-1.2, 2.3), (-2.5, 4.0)]:
    axes[0].plot(x1, intercept + slope * x1, "k", lw=1)
axes[1].contour(g1, g2, f, levels=[-1, 0, 1], colors="k",
                linestyles=["--", "-", "--"], linewidths=1)
sv = svm.support_vectors_
axes[1].scatter(sv[:, 0], sv[:, 1], s=90, facecolors="none", edgecolors="k")
plt.show()
1
A linear kernel with a huge \(C\) gives the maximal margin classifier.
Figure 56.1: Left, three of the infinitely many lines that separate the two classes. Right, the maximal margin classifier, with the margin (dashed) and the three support vectors (circled).

Kernels

SVC uses the radial kernel by default, \(K(x_i, x) = \exp\big(-\gamma \|x_i - x\|^2\big)\).

The decision boundary, with the support vectors marked. Switch to the rings and to the RBF kernel to see a boundary that no hyperplane could produce.

The default SVC() is a radial kernel with \(C = 1\). On three blobs, two of them in the same class, it draws the boundary one would draw by hand.

Code
from sklearn.datasets import make_blobs

X, y = make_blobs(centers=3, random_state=23)
y[y == 2] = 0
svm = SVC().fit(X, y)

g1, g2 = np.meshgrid(np.linspace(X[:, 0].min() - 1, X[:, 0].max() + 1, 200),
                     np.linspace(X[:, 1].min() - 1, X[:, 1].max() + 1, 200))
pred = svm.predict(np.column_stack([g1.ravel(), g2.ravel()])).reshape(g1.shape)
fig, ax = plt.subplots(figsize=(4.4, 3.8))
ax.contourf(g1, g2, pred, alpha=0.2, levels=1, colors=["C0", "C1"])
ax.scatter(X[:, 0], X[:, 1], c=np.where(y == 0, "C0", "C1"), s=14)
ax.set(xlabel="$x_1$", ylabel="$x_2$")
plt.show()
1
Two classes only: the third blob joins class 0.
Figure 56.2: The classifier of SVC() on three blobs, two of them in the same class.

In practice

The kernel uses distances, so the predictors should be standardized. \(C\) and \(\gamma\) are tuned together by cross-validation, here on two noisy rings.

from sklearn.datasets import make_circles
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = make_circles(300, noise=0.2, factor=0.5, random_state=0)
model = make_pipeline(StandardScaler(), SVC())
search = GridSearchCV(model, {"svc__C": [0.1, 1, 10, 100],
                              "svc__gamma": [0.01, 0.1, 1, 10]}, cv=5)
search.fit(X, y)
print(search.best_params_, round(search.best_score_, 3))
{'svc__C': 10, 'svc__gamma': 0.1} 0.89

More than two classes

SVC fits one classifier for every pair of classes, each on the points of its two classes only, and predicts the class that wins most pairs.

fitting the three pairwise classifiers and drawing them
from itertools import combinations

X, y = make_blobs(300, centers=[(0, 0), (3, 0), (1.5, 2.6)], cluster_std=0.9,
                  random_state=2)
g1, g2 = np.meshgrid(np.linspace(-3, 6, 200), np.linspace(-3, 5.5, 200))
grid = np.column_stack([g1.ravel(), g2.ravel()])

votes = np.zeros((len(grid), 3))
fig, axes = plt.subplots(1, 4, figsize=(12, 3.2))
for ax, (a, b) in zip(axes, combinations(range(3), 2)):
    keep = (y == a) | (y == b)
    pair = SVC(gamma=0.5).fit(X[keep], y[keep])
    p = pair.predict(grid)
    votes[np.arange(len(grid)), p] += 1
    ax.contourf(g1, g2, p.reshape(g1.shape), levels=[-0.5, 0.5, 1.5, 2.5],
                colors=["C0", "C1", "C2"], alpha=0.2)
    ax.scatter(X[keep, 0], X[keep, 1], c=[f"C{c}" for c in y[keep]], s=8)
    ax.set_title(f"class {a} against class {b}")
vote = votes.argmax(axis=1)
axes[3].contourf(g1, g2, vote.reshape(g1.shape), levels=[-0.5, 0.5, 1.5, 2.5],
                 colors=["C0", "C1", "C2"], alpha=0.2)
axes[3].scatter(X[:, 0], X[:, 1], c=[f"C{c}" for c in y], s=8)
axes[3].set_title("majority vote")
for ax in axes:
    ax.set(xticks=[], yticks=[], aspect="equal")
plt.show()
Figure 56.3: Three classes. The first three panels show the classifier of each pair of classes, fitted on the points of these two classes only. The last one shows the majority vote of the three.

SVC does the same on its own:

svm = SVC(gamma=0.5).fit(X, y)
print("same prediction as the vote:", np.mean(svm.predict(grid) == vote))
1
A fixed \(\gamma\), as for the pairs above. The default gamma="scale" computes \(\gamma\) from the spread of the points it is fitted on, which differs between a pair of classes and all three.
same prediction as the vote: 1.0

Handwritten digits

On the MNIST digits, we compare a support vector machine with logistic regression and a random forest, fitted on the first 5000 training images and tested on the 10000 test images. All pixels are on the same scale, from 0 to 1, so we do not standardize them.

loading the images, as in week 5
from sklearn.datasets import fetch_openml

mnist = fetch_openml(data_id=554, as_frame=False, parser="auto")
X_all = mnist.data / 255.0                                # pixels scaled to [0, 1]
y_all = mnist.target.astype(int)
X_train, y_train = X_all[:5000], y_all[:5000]
X_test, y_test = X_all[60000:], y_all[60000:]
import time
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier

models = {"logistic regression": LogisticRegression(max_iter=2000),
          "random forest": RandomForestClassifier(500, random_state=0),
          "SVC()": SVC()}
for name, model in models.items():
    model.fit(X_train, y_train)
    start = time.time()
    acc = model.score(X_test, y_test)
    print(f"{name:20s} test accuracy {acc:.3f}, "
          f"prediction of 10000 images {time.time() - start:.1f} s")
print("support vectors:", models["SVC()"].n_support_.sum())
logistic regression  test accuracy 0.895, prediction of 10000 images 0.0 s
random forest        test accuracy 0.942, prediction of 10000 images 0.7 s
SVC()                test accuracy 0.951, prediction of 10000 images 11.3 s
support vectors: 2379

The support vector machine is the most accurate, but it is slow at prediction: every test image is compared with each of the 2379 support vectors, almost half of the training images. Tuning \(C\) and \(\gamma\) helps a little more.

search = GridSearchCV(SVC(), {"C": [1, 10, 100], "gamma": [0.01, 0.03, 0.1]},
                      cv=3, n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_, f"test accuracy {search.score(X_test, y_test):.3f}")
{'C': 10, 'gamma': 0.03} test accuracy 0.960