The apples and pears from the chapter, handwritten digits and a kernel: find support vectors, read weights as numbers and as an image, and see why you scale features first.
Run in Google ColabColab requires a Google account, but you can also .
Reading mode. Below is the whole notebook, with the output of the code included. So you can simply read all of it here. To change the code and see what happens, you can go to Google Colab (external link).
In the chapter Support Vector Machines, a support vector machine looked for the straight boundary with the widest margin between two classes, and only a few points, the support vectors, decided where that boundary runs. This notebook shows what that looks like in code, with scikit-learn (external link), the standard library for machine learning in Python.
You will train three SVMs:
- 🍎 one that tells the apples from the pears of the chapter, with two features: width and height;
- ✍️ one that tells handwritten digits apart, with 784 features: one per pixel;
- 🌀 one with a kernel, which draws a curved boundary around the apples for the shop.
The first two times, you read what the SVM learned from its weights and its support vectors. The third time, you see why you put your features on the same scale before you train.
Prior knowledge: the chapter Support Vector Machines. You don't need any programming experience: you can run the whole notebook without changing a single line.
Estimated time: about 30 minutes.
This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/support-vector-machines, and you can open it directly in Google Colab (external link).
🚀 First time in a notebook?
Then the short introductory notebook explains everything step by step. The most important things:
- Make your own copy: File → Save a copy in Drive (in the menu at the top left), and work in that copy.
- Run a cell by clicking in it and pressing Shift+Enter, or with the ▶ button to its left. The result appears below the cell.
- Run the cells in order, from top to bottom, because a cell uses what the cells above it made. Does something behave strangely? Choose Runtime → Restart session and run everything again from the top.
Prefer not to use Google? Download the notebook file and open it in Jupyter (external link) or Visual Studio Code (external link), with scikit-learn and matplotlib installed.
🐍 Python in this notebook
New to Python? The introductory notebook explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:
| Code | Meaning |
|---|---|
np.array(apples + pears) | A NumPy array: a table of numbers that Python computes with all at once. X[y == 0] keeps only the rows where y is 0. |
svm.fit(X, y) | Trains the model on the examples in X (one row per example, one column per feature) and their labels in y. Every model in scikit-learn has this fit, and a predict that classifies new examples. |
svm.coef_ | What the model learned. scikit-learn ends such names with an underscore: they only exist after fit. |
[i for i in numbers if i > 0] | A list built in one line: every i in numbers, but only those that pass the test after if. |
make_pipeline(StandardScaler(), SVC()) | A pipeline: two steps in one model. fit first puts every feature on the same scale and then trains the SVM, and predict scales a new example the same way before it classifies it. |
C = 1 # @param [...] | A comment that Colab turns into an input next to the code, such as a dropdown menu. In other notebook programs, it is just a comment. |
🍎 Apples and pears
These are the 19 pieces of fruit from the chapter: their width and height in millimeters. In y, a 0 stands for an apple and a 1 for a pear.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
# Width and height (mm) of the fruit in the chapter
apples = [[57, 63], [74, 61], [83, 66], [62, 55], [66, 69],
[94, 74], [77, 75], [86, 73], [98, 83], [78, 80]]
pears = [[61, 103], [62, 83], [74, 96], [72, 113], [78, 127],
[81, 114], [83, 139], [58, 81], [68, 92]]
X = np.array(apples + pears)
y = np.array([0] * len(apples) + [1] * len(pears)) # 0 = apple, 1 = pearSVC, short for support vector classifier, is the support vector machine of scikit-learn for classification. Without further settings, it draws a curved boundary with a kernel, as at the end of this notebook; kernel="linear" asks for the straight boundary of the chapter. A huge C makes fruit inside the margin so expensive that none ends up there: the hard margin from the chapter.
svm = SVC(kernel="linear", C=1e6, tol=1e-6) # tol: compute a bit more precisely than the default
svm.fit(X, y)
print("Support vectors:", svm.support_vectors_.astype(int).tolist())
print(f"Width of the margin: {2 / np.linalg.norm(svm.coef_):.1f} mm")Support vectors: [[57, 63], [78, 80], [62, 83]] Width of the margin: 12.4 mm
Below, a function that draws the fruit, the boundary (solid line) and the edges of the margin (dashed), with a black ring around every support vector. Inside the margin, the colors are lighter. You don't need to understand its code.
def show_svm(model, X, y, names=("apple", "pear")):
svm = model[-1] if hasattr(model, "steps") else model # the SVM itself, also at the end of a pipeline
width, height = np.meshgrid(np.linspace(X[:, 0].min() - 10, X[:, 0].max() + 10, 300),
np.linspace(X[:, 1].min() - 10, X[:, 1].max() + 10, 300))
f = model.decision_function(np.column_stack([width.ravel(), height.ravel()])).reshape(width.shape)
plt.figure(figsize=(5, 6))
plt.contourf(width, height, f, levels=[-1e9, -1, 0, 1, 1e9], colors=["#fecaca", "#fef2f2", "#f0fdf4", "#bbf7d0"])
plt.contour(width, height, f, levels=[-1, 0, 1], colors="#334155", linestyles=["--", "-", "--"])
plt.scatter(*X[y == 0].T, color="#dc2626", label=names[0])
plt.scatter(*X[y == 1].T, color="#22c55e", label=names[1])
plt.scatter(*X[svm.support_].T, s=220, facecolors="none", edgecolors="black", label="support vector")
plt.gca().set_aspect("equal")
plt.xlabel("width (mm)")
plt.ylabel("height (mm)")
if svm is model and svm.kernel == "linear":
plt.title(f"Margin: {2 / np.linalg.norm(svm.coef_):.1f} mm")
else:
plt.title(f"{len(svm.support_)} support vectors")
plt.legend(loc="upper left", bbox_to_anchor=(1.02, 1))
plt.show()
show_svm(svm, X, y)🔍 What the line tells you
The SVM stores its boundary as one weight per feature, in svm.coef_, plus a shift, in svm.intercept_. Together they give each piece of fruit a score: weight × width + weight × height + shift. A positive score means pear, a negative one apple, and the boundary is where the score is 0.
w_width, w_height = svm.coef_[0]
shift = svm.intercept_[0]
print(f"Weight of the width: {w_width:+.3f} per mm")
print(f"Weight of the height: {w_height:+.3f} per mm")
print(f"Shift: {shift:+.2f}")
new_fruit = [70, 85] # width and height in mm
print()
print("Score of a fruit of 70 by 85 mm:", round(svm.decision_function([new_fruit])[0], 2))
print("Prediction:", "pear" if svm.predict([new_fruit])[0] == 1 else "apple")Weight of the width: -0.101 per mm Weight of the height: +0.125 per mm Shift: -3.11 Score of a fruit of 70 by 85 mm: 0.44 Prediction: pear
The weight of the height is positive: the taller, the more pear. The weight of the width is negative: the wider, the more apple. The two are about equally large, so the SVM mostly looks at how much taller than wide a piece of fruit is. The fruit of 70 by 85 mm scores just above 0: a pear, but only just.
Try it yourself: change the numbers of an apple far from the boundary, such as [98, 83], and run the cells again from 🍎 Apples and pears. The boundary stays where it is. Now change a support vector, such as [78, 80]: the boundary turns.
🎚️ A round pear and the strictness C
Now the round pear of the chapter joins the others: 60 mm wide and 72 mm high. With a hard margin, that one pear squeezes the margin from 12.4 to 5.1 mm. A lower C lets fruit inside the margin, and even onto the wrong side, at a cost. Pick a value for C (in Colab, with the menu next to the code) and run the cell.
C = 1000000 # @param [1000000, 0.05, 0.03, 0.002] {type:"raw"}
X_round = np.vstack([X, [60, 72]])
y_round = np.append(y, 1) # the round pear is a pear
soft = SVC(kernel="linear", C=C, tol=1e-6)
soft.fit(X_round, y_round)
score = soft.decision_function(X_round)
own_side = np.where(y_round == 1, score, -score) # 1 or more: on or beyond its edge of the margin; below 0: wrong side
print("Inside the margin:", np.sum((own_side >= 0) & (own_side < 0.999)))
print("On the wrong side:", np.sum(own_side < 0))
show_svm(soft, X_round, y_round)Inside the margin: 0 On the wrong side: 0
Try it yourself: at C = 0.05, the round pear lies inside the margin, which widens to 7.8 mm. At C = 0.03, the SVM gives up on it: the round pear ends up on the wrong side, and the margin is back to 12.4 mm. At C = 0.002, the margin is 19.7 mm wide, with six pieces of fruit inside it.
These values are much smaller than in the demo of the chapter, which first rescales the fruit. C depends on the units of the features: in millimeters, the weights are small numbers, so the C that weighs the fines against them has to be small too. One more reason to put your features on a common scale first, and to choose C by testing on fruit the SVM didn't see.
✍️ Handwritten digits
An image is also just a list of numbers. Every image in MNIST (external link), a classic collection of handwritten digits, has 28 × 28 pixels: 784 numbers from 0 (white) to 255 (black). To an SVM, such an image is a point with 784 features instead of 2.
The cell below downloads a sample of 5,000 images, 500 of every digit (less than 1 MB), and shows the first ten.
The images are a sample of the MNIST database (external link) by Yann LeCun, Corinna Cortes and Christopher J. C. Burges.
import io
import urllib.request
DATA_URL = "https://ai.kuleuven.be/aivooriedereen/notebooks/data/"
with urllib.request.urlopen(DATA_URL + "mnist-sample.npz") as response:
mnist = np.load(io.BytesIO(response.read()))
images, labels = mnist["images"], mnist["labels"]
print(len(images), "images of", images.shape[1], "by", images.shape[2], "pixels")
fig, axes = plt.subplots(1, 10, figsize=(10, 1.4))
for ax, image, label in zip(axes, images, labels):
ax.imshow(image, cmap="gray_r")
ax.set_title(label)
ax.axis("off")
plt.show()5000 images of 28 by 28 pixels
0️⃣ 1️⃣ Two digits
Pick two digits, and train an SVM that tells them apart: the same SVC as for the fruit, with a straight boundary. A quarter of their images stays aside as a test: images the SVM never sees during training. A low C gives a soft margin, which makes the weights below easier to read.
from sklearn.model_selection import train_test_split
digit_a = 0 # @param {type:"integer"}
digit_b = 1 # @param {type:"integer"}
chosen = (labels == digit_a) | (labels == digit_b)
X_digits = images[chosen].reshape(-1, 28 * 28) / 255 # every image as one row of 784 numbers between 0 and 1
y_digits = labels[chosen]
X_train, X_test, y_train, y_test = train_test_split(X_digits, y_digits, test_size=0.25, random_state=0)
digit_svm = SVC(kernel="linear", C=0.01)
digit_svm.fit(X_train, y_train)
print(f"Correct on the test images: {digit_svm.score(X_test, y_test):.1%}")
print("Support vectors:", len(digit_svm.support_), "of the", len(X_train), "training images")Correct on the test images: 100.0% Support vectors: 48 of the 750 training images
🖼️ The weights as an image
The SVM gives every pixel a weight. Put each weight back on its own pixel, and the weights form an image themselves: red pixels count for one digit, blue pixels for the other, and white pixels hardly matter.
low, high = digit_svm.classes_
weights = digit_svm.coef_.reshape(28, 28)
largest = np.abs(weights).max()
plt.imshow(weights, cmap="RdBu_r", vmin=-largest, vmax=largest)
plt.title(f"Red: more like a {high}. Blue: more like a {low}.")
plt.colorbar()
plt.axis("off")
plt.show()For zeros against ones, the middle is red: that is where a one has its stroke, and a zero its hole. Around it, the image is blue, where a zero has its ring. That is what makes a linear model so readable: for every input, you can see how much it counts and in which direction.
📊 The divide in one picture
To classify an image, the SVM adds up weight × pixel for all 784 pixels, plus a shift: one score per image, as for the fruit. Below 0, it is one digit; above 0, the other. The histogram below shows the scores of the test images, with the boundary at 0 and the edges of the margin at −1 and 1.
test_score = digit_svm.decision_function(X_test)
plt.figure(figsize=(8, 3))
for digit, color in zip(digit_svm.classes_, ["#2563eb", "#dc2626"]):
plt.hist(test_score[y_test == digit], bins=30, color=color, alpha=0.6, label=f"test images of a {digit}")
plt.axvline(0, color="black", label="boundary")
plt.axvline(-1, color="black", linestyle="--", label="edges of the margin")
plt.axvline(1, color="black", linestyle="--")
plt.xlabel("score")
plt.ylabel("number of test images")
plt.legend(loc="upper left", bbox_to_anchor=(1.02, 1))
plt.show()The zeros and the ones form two hills, each on its own side of the margin. The few test images between the dashed lines lie inside the margin: borderline cases, like the support vectors below.
🛡️ The support vectors
The support vectors are the borderline cases among the training images: the zeros that look most like a one, and the ones that look most like a zero. The cell below shows them, those closest to the boundary first.
train_score = digit_svm.decision_function(X_train)
for digit in digit_svm.classes_:
support = [i for i in digit_svm.support_ if y_train[i] == digit]
support = sorted(support, key=lambda i: abs(train_score[i])) # closest to the boundary first
fig, axes = plt.subplots(1, 10, figsize=(10, 1.4))
for ax in axes:
ax.axis("off")
for ax, i in zip(axes, support):
ax.imshow(X_train[i].reshape(28, 28), cmap="gray_r")
fig.suptitle(f"Support vectors that are a {digit}")
plt.show()Try it yourself
- Pick two other digits, such as 3 and 8, or 4 and 9, and run the cells again from 0️⃣ 1️⃣ Two digits. Which pixels does the SVM look at now, does it need more support vectors, and do the two hills in the histogram still stay apart?
- Which two digits are the hardest to tell apart? Compare the score on the test images for a few pairs.
- Set
C=1for zeros and ones: the SVM keeps fewer support vectors, and the image of the weights gets noisier.
🌀 A curved boundary, and why you scale
Not every problem has a straight boundary. In the chapter, a shop only takes nice, medium-sized apples: not too small, not too big, not too flat and not too tall. With width and height as features, the apples for the shop lie as an island among the apples for juice, and no straight line separates them.
Without kernel="linear", an SVC uses the RBF kernel of the chapter: every support vector raises or lowers the landscape around it, and gamma (γ) sets how wide each of those hills is. The pipeline first puts both features on the same scale; below, you see why. Pick a value for gamma and run the cell.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
gamma = 1 # @param [0.1, 1, 10, 100] {type:"raw"}
# Width and height (mm) of the apples in the kernel demo of the chapter
juice = [[93, 73], [93, 79], [89, 84], [86, 89], [78, 92], [72, 87], [67, 86], [65, 83], [61, 79],
[61, 73], [61, 66], [62, 59], [64, 55], [75, 57], [78, 55], [84, 58], [88, 61], [90, 67]]
shop = [[75, 68], [77, 71], [70, 73], [71, 73], [70, 75], [80, 74], [82, 71],
[74, 76], [81, 74], [79, 77], [71, 68], [80, 69], [76, 70], [82, 74]]
X_island = np.array(juice + shop)
y_island = np.array([0] * len(juice) + [1] * len(shop)) # 0 = juice, 1 = shop
island_svm = make_pipeline(StandardScaler(), SVC(kernel="rbf", gamma=gamma, C=1e6))
island_svm.fit(X_island, y_island)
show_svm(island_svm, X_island, y_island, names=("juice", "shop"))Try it yourself: at γ = 0.1, a handful of support vectors is enough for one smooth, round island. The larger γ, the narrower every hill, and the more apples become support vectors. At γ = 100, every apple is one, and every shop apple gets a small island of its own: overfitting, as with k = 1 for nearest neighbors. You choose γ, like C, by testing on apples the SVM didn't see. (The numbers differ a little from the demo in the chapter, which scales the apples in its own way.) And note: there is no weight per feature to read any more, because the boundary is no longer a line.
📏 Millimeters or centimeters?
An RBF kernel measures how far apart apples are, so the units of the features matter. Suppose the machine had measured the height in centimeters instead of millimeters. The apples stay the same; only the numbers change. Compare an SVM without and with the scaler, both with the default settings of SVC:
X_cm = X_island * [1, 0.1] # width still in mm, height now in cm
without_scaler = SVC().fit(X_cm, y_island)
with_scaler = make_pipeline(StandardScaler(), SVC()).fit(X_cm, y_island)
print(f"Without the scaler: {without_scaler.score(X_cm, y_island):.0%} of the apples right")
print(f"With the scaler: {with_scaler.score(X_cm, y_island):.0%} of the apples right")Without the scaler: 56% of the apples right With the scaler: 100% of the apples right
In centimeters, the heights only range from 5.5 to 9.2, against widths from 61 to 93 millimeters. To the kernel, all apples then lie close together in height, so it hardly sees the difference between tall and flat apples, and the SVM calls every apple juice: right for 18 of the 32. StandardScaler first gives every feature a mean of 0 and a standard deviation of 1, so the units you measured in no longer matter. It also makes the weights of a linear SVM comparable between features, as the chapter explained.
🧰 An SVM for your own problem
All three SVMs followed the same recipe:
- Put your examples in a table
X, one row per example and one column per feature, and their labels iny. - Put a scaler in front of the SVM,
make_pipeline(StandardScaler(), SVC(kernel="linear")), and train withfit(X, y). The apples and pears could do without, because both features were in millimeters, and so could the digits, whose pixels you divided by 255. - Read what it learned: the weights in
coef_and the support vectors insupport_(in a pipeline:model[-1].coef_).
Choose C, and for a kernel also gamma, on data the SVM didn't train on, for example with cross-validation. A straight boundary keeps one weight per feature to read; a kernel bends the boundary, but those weights are gone.
In scikit-learn, an SVM is one model among many: KNeighborsClassifier and DecisionTreeClassifier have the same fit and predict, so you can try several on the same X and y.
By Thomas Winters (external link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/support-vector-machines.
