ML fundamentals12 / 22

Lesson 12 · Other ways to draw a boundary

Support vector machines and kernels

The problem

Here are 12 deliveries, described by distance and a traffic score. Six were on time and six were late. Many straight lines separate them: the data is linearly separable. Which line should you pick?

A line that grazes one of the on-time deliveries is risky. A new on-time delivery a little further out would land on the wrong side. A line that keeps as far as possible from both groups leaves room for that. This lesson's first idea is to pick the line with the most room on both sides.

The widest street

Picture the boundary as the middle of a street. The street's two edges run parallel to it, one on each side. Make the street as wide as you can without any delivery standing in it. The boundary is the street's centre line.

01234567012345distance (km)traffic score

Street width 1.91 · 3 support vectors (circled) · 0 on the wrong side

○ on time · × late · solid line: the boundary · dashed: the street’s edges

Twelve deliveries and the widest street between them, found by a linear SVM trained live in your browser. Drag any delivery (or focus it and use the arrow keys). Circled points are the support vectors. Both axes use the same scale, so the street's width is true to the picture.

Things to notice, with C = 1:

  • Three deliveries touch the street's edges: one on-time delivery and two late ones. They're circled.
  • Drag a point that's far from the street, such as the on-time delivery at the bottom left. Nothing changes.
  • Drag a circled point. The street moves, turns or narrows straight away.
  • Drag a late delivery into the on-time group. The street can no longer be empty, and the method has to accept some mistakes. The section on soft margins explains how.

The gap between the boundary and the closest deliveries is the margin. A classifier that picks the boundary with the widest margin is a support vector machine, or SVM. The training points on the street's edges, or inside the street, are its support vectors. They "support" the street: they alone hold it in place.

Predict first

You delete a training delivery that sits far from the boundary, on the correct side. Does the SVM's boundary move?

Measuring the street

A linear classifier gives each point a score, s(x)=w⋅x+bs(\mathbf{x}) = \mathbf{w} \cdot \mathbf{x} + b: a dot product with a weight vector w\mathbf{w}, plus an intercept bb. Score above 0 means late; below 0 means on time. The boundary is where the score is exactly 0.

An SVM fixes the scale of the score so that the street's edges are where the score is +1+1 and −1-1. The edges are parallel lines, and the distance between them is

street width=2∥w∥.\text{street width} = \frac{2}{\lVert \mathbf{w} \rVert}.

Here ∥w∥\lVert \mathbf{w} \rVert is the length of the weight vector. Read it back: the score climbs from −1-1 to +1+1 across the street. The longer w\mathbf{w} is, the faster the score climbs, so the narrower the street. A wide street means a short w\mathbf{w}.

Worked example

The street in the figure

  1. scikit-learn's SVM (with C = 1) finds w=(0.87,0.58)\mathbf{w} = (0.87, 0.58) and b=−4.22b = -4.22, for features (distance in km, traffic score).

So "the widest street" means "the shortest w\mathbf{w} that puts every training point on or outside its edge". In symbols, with labels yi=+1y_i = +1 for late and −1-1 for on time: make ∥w∥\lVert \mathbf{w} \rVert as small as possible, subject to yi s(xi)≥1y_i \, s(\mathbf{x}_i) \ge 1 for every point. The product yi s(xi)y_i \, s(\mathbf{x}_i) is positive when the point is on its correct side, and at least 1 when it's also outside the street.

Scale your features first

The street's width is measured in feature units. Here both features have similar ranges, so that's fine.

Suppose distance were in metres (0 to 8,000) and traffic a score from 0 to 5. Then the "widest" street would be decided almost entirely by distance. As with nearest neighbours, put features on the same scale first. See feature scaling.

Soft margins and the hinge loss

Real data is rarely separable. Drag a late delivery deep into the on-time group, and no street can be empty. So the SVM allows points inside the street, or even on the wrong side, and charges each one a cost.

The cost is the hinge loss:

hinge(xi)=max⁡(0,  1−yi s(xi)).\text{hinge}(\mathbf{x}_i) = \max\big(0,\; 1 - y_i\, s(\mathbf{x}_i)\big).
−2−1012300.511.522.53y × score (how far on the right side)lossstreet’s edge— hinge- - cross-entropy

y × score = 0.5: inside the street, on the right side. Hinge loss 0.5; cross-entropy 0.68.

The hinge loss (solid) against y × score. It is 0 beyond the street's edge and grows in a straight line inside the street and beyond the boundary. The dashed curve is the cross-entropy loss, for comparison. Drag the dot along the axis.

Read it back, using the figure:

  • A point outside the street on its correct side has yi s≥1y_i\, s \ge 1: loss 0. It costs nothing, which is why such points can't move the boundary.
  • A point inside the street but on the correct side has 0<yi s<10 < y_i\, s < 1: a small loss.
  • A point on the boundary has loss 1. A point on the wrong side has loss above 1, growing the further it is.

The SVM now balances two goals: a wide street (a short w\mathbf{w}) and a small total hinge loss. One setting, C, says how much each unit of hinge loss costs:

minimise12∥w∥2  +  C∑ihinge(xi).\text{minimise} \quad \tfrac{1}{2}\lVert \mathbf{w} \rVert^2 \;+\; C \sum_i \text{hinge}(\mathbf{x}_i).

The first part is the same kind of penalty as L2 regularisation. It pushes the weights to be small, and here small weights mean a wide street.

  • Large C: mistakes are expensive. The street narrows to keep points out of it.
  • Small C: mistakes are cheap. The street widens, even if several points end up inside it.

Try the C buttons in the widest-street figure. With C = 0.1, the street widens from 1.91 to 3.08. Six points are now inside it or on its edges, so all six are support vectors. With C = 10, nothing changes from C = 1: the data can be separated, and the widest empty street is already the best deal. Now drag a point across and compare C = 0.1 and C = 10 again.

DeeperHinge loss vs cross-entropyLogistic regression and a linear SVM both draw a straight line. Their losses differ in one place: far from the boundary. · 2 min

Both losses are functions of the same number, y×y \times score: how far a point is on its correct side. The figure above draws both. The cross-entropy curve is the one logistic regression uses, measured in bits so that it's 1 at the boundary, like the hinge.

  • On the wrong side, both grow in a straight line. A badly wrong point costs a lot under either loss.
  • Near the boundary, both are about 1.
  • Far on the right side, they differ. The hinge loss is exactly 0 once y×y \times score ≥1\ge 1. The cross-entropy loss gets small but never reaches 0. So under cross-entropy every point, even a safe one, still pulls a little on the boundary.

That flat zero region is why an SVM has support vectors and logistic regression doesn't. It's also why an SVM gives no probabilities. Its score says which side and how far. It was never trained to match how often late deliveries happen. (scikit-learn's SVC(probability=True) fits a separate calibration step to get them.)

In practice the two lines are often close. Logistic regression gives probabilities; a linear SVM gives a boundary that ignores easy points.

Curved boundaries: the kernel idea

The rush-hour data needs a curved boundary: short trips are late around 19:00 but not before or after. A straight street can't follow that. The fix is to give the SVM more features, so that a straight boundary in the bigger feature space is curved in the original one.

Start with a smaller version of the problem: one feature, the hour a delivery was sent. Late deliveries are in the middle of the evening.

1718192021time sent (hour)
Step 0 of 3

One feature, the hour sent. Late deliveries (×) sit in the middle of the evening, so no single cut separates them.

Ten deliveries by the hour sent: late (×) in the middle of the evening, on time (○) before and after. Step through: add a second feature, find a straight line, then look at it in one feature again.

Things to notice:

  • With one feature, any single cut gets at least three deliveries wrong. A linear SVM on the hour alone gets 60% of them right.
  • Add a second feature, z2z^2, where zz is the hour minus 19. Deliveries near 19:00 have small z2z^2; those far from it have large z2z^2. The late ones now sit at the bottom.
  • In the lifted picture a straight line separates the two kinds perfectly.
  • Back in one feature, that straight line is two cuts, at about 18:27 and 19:48. A straight boundary in the bigger space is a curved one (here, an interval) in the original space.

Adding powers of a feature is the same trick as polynomial features for linear regression. The catch is size. With 2 features and all products up to degree 5, there are 20 new features. With 20 features, there are over 50,000. Building them all gets slow.

The kernel trick

SVMs have a way around this. A result from the theory of SVMs (their "dual form") helps here. The trained SVM's score can always be written with dot products alone, between the new point and the support vectors:

s(x)=∑i ∈ support vectorsai (xi⋅x)+b,s(\mathbf{x}) = \sum_{i \,\in\, \text{support vectors}} a_i \, (\mathbf{x}_i \cdot \mathbf{x}) + b,

where the numbers aia_i come out of training. Training also only needs dot products between pairs of training points. So the SVM never needs the features themselves, only dot products of them.

Now suppose the features are lifted, x→φ(x)\mathbf{x} \to \varphi(\mathbf{x}). Every dot product becomes φ(xi)⋅φ(x)\varphi(\mathbf{x}_i) \cdot \varphi(\mathbf{x}). If you have a quick formula for that dot product, you never need to build φ\varphi.

Worked example

A dot product without the features

  1. Lift one number to two features: φ(z)=(z,z2)\varphi(z) = (z, z^2), as in the figure.

A function k(u,v)k(\mathbf{u}, \mathbf{v}) that equals a dot product of lifted features, φ(u)⋅φ(v)\varphi(\mathbf{u}) \cdot \varphi(\mathbf{v}), for some lifting φ\varphi, is a kernel. You can read it as a similarity: a big kernel value means the two examples look alike in the lifted space.

Replacing every dot product in the SVM with a kernel is the kernel trick. The SVM still draws the widest straight street, but in the lifted space. Back in the original features, that street is curved. And the cost of each kernel value doesn't depend on how many lifted features there are.

The RBF kernel

The most used kernel is the RBF kernel (radial basis function), also called the Gaussian kernel:

k(u,v)=e−γ∥u−v∥2.k(\mathbf{u}, \mathbf{v}) = e^{-\gamma \lVert \mathbf{u} - \mathbf{v} \rVert^2}.

It's 1 when the two points are the same, and it fades towards 0 as they move apart. It has the bell shape of the normal distribution. The setting γ\gamma (gamma) says how fast it fades.

For example, take two deliveries 1 unit apart (in standardised features). With γ=1\gamma = 1, their similarity is e−1=0.37e^{-1} = 0.37. With γ=10\gamma = 10, it's e−10=0.00005e^{-10} = 0.00005: they barely count as neighbours.

The lifting behind the RBF kernel has infinitely many features, so it could never be built. The kernel trick makes it usable anyway. With it, the SVM's score at a new point is a weighted sum of bumps, one centred on each support vector:

s(x)=∑i ∈ support vectorsai e−γ∥xi−x∥2+b.s(\mathbf{x}) = \sum_{i \,\in\, \text{support vectors}} a_i \, e^{-\gamma \lVert \mathbf{x}_i - \mathbf{x} \rVert^2} + b.

Late support vectors add bumps up; on-time ones add bumps down. The boundary is where they balance.

Predict first

You raise γ from 1 to 100. Each bump gets much narrower. What happens to the boundary on the rush-hour data?

on time late P = 0.5

Training 90.0% · validation 93.5% · 96 of 200 deliveries are support vectors

00.511.522.5300.20.40.60.81distance apart (standardised units)similaritysimilarity with γ = 1
RBF-kernel SVMs on the rush-hour data, trained by scikit-learn for each pair of γ and C and stored as a grid. Shading is the SVM's score squashed to 0–1 (not a probability); the dark line is the boundary. The small plot below shows how fast similarity fades for the chosen γ.

Things to notice:

  • Small γ (0.1): wide bumps. The boundary is nearly straight and misses the dip at 19:00 (83% validation with C = 1).
  • γ = 1, C = 1: the boundary follows the dip. It gets 90% training and 93.5% validation accuracy, tied best in the grid with γ = 10, C = 1. That one needs more support vectors (141 vs 96).
  • Large γ (100): islands around single deliveries. 100% training accuracy and about 79% validation.
  • C works as before. With γ = 1, raising C from 0.1 to 100 lifts training accuracy from 84% to 94.5%. Validation accuracy goes from 88% up to 93.5%, then back down to 90.5%.
  • About half the training deliveries are support vectors here (96 of 200 at γ = 1, C = 1). With noisy, overlapping classes, many points sit inside the street.

So γ and C are both hyperparameters, and they interact. The usual way to choose them is a grid search with cross-validation, trying values spaced by factors of 10, as here.

DeeperGaussian processes: a kernel as a belief about functionsUse the kernel to say which inputs should get similar outputs, and get predictions with error bars that widen away from the data. · 4 min

A kernel says how similar two inputs are. A Gaussian process turns that into a model for numbers. Its one assumption: two inputs that the kernel calls similar should have similar outputs.

Take 5 deliveries with their times, and the RBF kernel on distance with a length scale ℓ\ell of 1 km. (It's the same kernel, written e−d2/(2ℓ2)e^{-d^2/(2\ell^2)}, so γ=1/(2ℓ2)\gamma = 1/(2\ell^2).) Two trips 1 km apart have similarity e−0.5=0.61e^{-0.5} = 0.61, so their times should be close. Two trips 4 km apart have similarity e−8=0.0003e^{-8} = 0.0003, so one says almost nothing about the other.

012345678010203040distance (km)minutes— mean · shaded: ±2 standard deviations

At 4 km (no data): 24.1 minutes, give or take 6.1 · at 8 km: 21.4, give or take 12.5

A Gaussian process through 5 delivery times. The line is the predicted time; the shaded band is ±2 standard deviations. Change the length scale.

Things to notice:

  • At each observed delivery the band is narrow: the model is sure of times it has seen (up to a little noise).
  • At 4 km, between the data, the band widens to about ±6 minutes.
  • Past 6 km there's no data, so the band keeps widening. The prediction drifts back towards the average of the 5 times, 20.6 minutes: at 8 km it's already down to 21.4. Far from the data, the model admits it doesn't know.
  • A longer length scale makes the curve stiffer and the band narrower between points. A shorter one lets it bend sharply and widens the band quickly.

The name comes from the maths. The model treats the outputs at any set of inputs as following a normal distribution together. The kernel says how strongly each pair moves together. Gaussian processes are popular when data is scarce and error bars matter, for example in tuning settings for expensive experiments. Like kernel SVMs, they get slow with many thousands of examples.

DigressionWhy SVMs are less common nowThey were a top method in the late 1990s and 2000s. Size is the main reason they faded. · 2 min

Kernel SVMs work with a table of kernel values between pairs of training points. With nn points, that's n2n^2 numbers, and training time grows faster than n2n^2. The scikit-learn documentation warns that SVC's fit time grows at least with the square of the number of rows. It calls it impractical beyond tens of thousands of rows.

For tabular data, gradient-boosted trees now usually match or beat them, scale to millions of rows and need less tuning. For images and text, neural networks took over. A linear SVM (no kernel) is still fast on large, sparse data such as word counts; scikit-learn's LinearSVC is built for that.

Kernels themselves are still widely used, for example in Gaussian processes.

DigressionWhere SVMs and the kernel trick come fromThe optimal margin in 1992, soft margins in 1995. · 1 min
  • The kernel trick for maximum-margin classifiers appeared in Bernhard Boser, Isabelle Guyon and Vladimir Vapnik's "A training algorithm for optimal margin classifiers" (1992). It combined the widest-margin boundary with kernels, so the boundary could curve.
  • Soft margins came from Corinna Cortes and Vapnik's "Support-vector networks" (1995). It allowed points inside the street, with a cost, so SVMs work on data that isn't separable. That paper introduced the name "support-vector network".

In scikit-learn

SVC(kernel="linear") is a linear SVM. After fitting, coef_ holds w\mathbf{w}, intercept_ holds bb, and support_ holds the row numbers of the support vectors (support_vectors_ holds the points themselves).

The widest street through 12 deliveries
def widest_street(C: float = 1.0) -> dict:
    """A linear SVM on the 12 deliveries: its weights, support vectors and margin width."""
    x, y = margin_data()
    svm = SVC(kernel="linear", C=C).fit(x, y)
    w, b = svm.coef_[0], svm.intercept_[0]  # boundary: w · x + b = 0
    return {
        "w": w,
        "b": b,
        "support": svm.support_,  # row numbers of the support vectors
        "width": 2 / np.linalg.norm(w),  # distance between the lines w · x + b = ±1
    }


street = widest_street()
print(f"w = {np.round(street['w'], 3)}, b = {street['b']:.3f}")
print(f"support vectors: rows {street['support'].tolist()}, margin width {street['width']:.2f}")
w = [0.87 0.58], b = -4.219
support vectors: rows [3, 6, 7], margin width 1.91

The same three support vectors and the same width as the figure. The figure's solver is simpler (it takes small steps downhill on the hinge loss) but finds the same street.

Changing C
for C in [0.1, 1.0, 10.0]:
    s = widest_street(C)
    print(f"C = {C:>4}: margin width {s['width']:.2f}, {len(s['support'])} support vectors")
C =  0.1: margin width 3.08, 6 support vectors
C =  1.0: margin width 1.91, 3 support vectors
C = 10.0: margin width 1.91, 3 support vectors

The lifting trick, done by hand with an extra column:

Adding z² makes the hours separable
def lift_accuracy() -> tuple[float, float]:
    """Training accuracy of a linear SVM on the hour alone, and on (hour − 19, (hour − 19)²)."""
    z = np.array(LIFT_HOURS) - 19
    y = np.array(LIFT_LATE)
    flat = SVC(kernel="linear", C=10.0).fit(z[:, None], y)
    lifted_x = np.column_stack([z, z**2])  # add a second feature: the squared distance from 19:00
    lifted = SVC(kernel="linear", C=10.0).fit(lifted_x, y)  # C = 10: no mistakes allowed here
    return flat.score(z[:, None], y), lifted.score(lifted_x, y)


flat_acc, lifted_acc = lift_accuracy()
print(f"one feature: {flat_acc:.0%} of training points right; with z² added: {lifted_acc:.0%}")
one feature: 60% of training points right; with z² added: 100%

For a kernel SVM, set kernel="rbf" with gamma and C. Always scale the features first. make_pipeline chains a StandardScaler and the SVC. The scaling learned on the training data is then applied to any new data too. Pipelines get a full explanation later in the course.

RBF-kernel SVMs on the rush-hour data
def rbf_svm(gamma: float, C: float) -> tuple[float, float, int]:
    """An RBF-kernel SVM on the rush-hour data, with the features standardised first."""
    x_train, y_train, x_val, y_val = load_rush_hour()
    model = make_pipeline(StandardScaler(), SVC(kernel="rbf", gamma=gamma, C=C))
    model.fit(x_train, y_train)
    n_support = len(model[-1].support_)  # model[-1] is the SVC step of the pipeline
    return model.score(x_train, y_train), model.score(x_val, y_val), n_support


for gamma in [0.1, 1.0, 10.0, 100.0]:
    train_acc, val_acc, n_sv = rbf_svm(gamma, C=1.0)
    print(f"gamma {gamma:>5}: train {train_acc:.1%}, validation {val_acc:.1%}, {n_sv} support vectors")
gamma   0.1: train 77.5%, validation 83.0%, 119 support vectors
gamma   1.0: train 90.0%, validation 93.5%, 96 support vectors
gamma  10.0: train 94.5%, validation 93.5%, 141 support vectors
gamma 100.0: train 100.0%, validation 78.5%, 196 support vectors

These are the numbers behind the γ × C figure, for C = 1. With gamma=100, 196 of the 200 deliveries are support vectors: every point gets its own bump. The default, gamma="scale", sets γ\gamma from the number of features and their spread. It's a reasonable start, not a replacement for a search.

The Gaussian process from the aside uses GaussianProcessRegressor with an RBF kernel. optimizer=None keeps the length scale fixed; by default scikit-learn would tune it to the data.

A Gaussian process through 5 delivery times
def gp_fit(grid: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """A Gaussian process through 5 delivery times: its mean and standard deviation on a grid."""
    gp = GaussianProcessRegressor(
        kernel=RBF(length_scale=1.0),  # similarity exp(−d² / 2) for two trips d km apart
        alpha=0.01,  # a little noise on each observed time
        normalize_y=True,  # work with times scaled to mean 0 and standard deviation 1
        optimizer=None,  # keep the length scale fixed at 1 km
    )
    gp.fit(np.array(GP_KM)[:, None], np.array(GP_MINUTES))
    mean, std = gp.predict(grid[:, None], return_std=True)
    return mean, std


km = np.array([4.0, 8.0])
mean, std = gp_fit(km)
for k, m, s in zip(km, mean, std):
    print(f"{k:.0f} km: {m:.1f} minutes, give or take {2 * s:.1f}")
4 km: 24.1 minutes, give or take 6.1
8 km: 21.4 minutes, give or take 12.5

Putting it together

Worked example

An RBF SVM scores one delivery

  1. Standardise the new delivery with the training set's means and standard deviations, as the pipeline does.

Common misconceptions

"Every training point helps place the SVM's boundary." Only the support vectors do. Points outside the street have zero hinge loss and could be deleted without changing anything.

"A bigger γ means a smoother boundary." The opposite. Bigger γ\gamma makes each support vector's bump narrower, so the boundary can wrap single points. Small γ\gamma is close to a straight line.

"The kernel trick builds the extra features, cleverly." It never builds them. It computes their dot products straight from the original features. For the RBF kernel the lifted space is infinitely large, and the trick still works.

"An SVM's score is a probability." It's a signed distance-like number: which side, and how far. Use logistic regression, or a calibration step, if you need probabilities.

"SVMs don't need scaled features." They need it more than most models. The street's width, and the RBF kernel's distances, are measured in feature units.

Recap

  • A support vector machine picks the boundary with the widest street (margin) between the classes. The street's width is 2/∥w∥2/\lVert \mathbf{w} \rVert.
  • Only the support vectors, the points on or inside the street, decide where the boundary goes.
  • Soft margins let points into the street at a cost, the hinge loss. C sets that cost: large C narrows the street to avoid mistakes; small C widens it.
  • A kernel is a dot product in a lifted feature space, computed without building the features. Swapping it in (the kernel trick) lets the SVM draw curved boundaries.
  • The RBF kernel's similarity fades with distance at a rate set by γ\gamma. Small γ\gamma is nearly linear; large γ\gamma overfits. Choose γ\gamma and C together by cross-validation.
  • Python names in this lesson: scikit-learn's SVC (kernel, C, gamma, coef_, intercept_, support_, support_vectors_), make_pipeline, StandardScaler, LinearSVC, and GaussianProcessRegressor with the RBF kernel.