AI voor Iedereen

Search

Search chapters and demos

πŸ›‘οΈ Support Vector Machines

πŸ›£οΈ The widest margin

🍎 Apples and pears

In the chapter on nearest neighbors a machine sorted fruit by its width and height. Here it only sorts apples and pears: two classes instead of three.

With one neighbor, the decision boundary between an apple and a pear always ran exactly through the middle, perpendicular to the line between them. That produced a boundary made of many small pieces, and for every prediction the algorithm had to go through all the fruit. Can it be simpler, with one straight line as the rule: everything above the line is a pear, everything below it an apple? Such a rule is fast, because you only look at which side of the line a piece of fruit lies on, and you can read it: the line shows you which features matter.

Try it out: drag the purple line, or one of the white dots on it, until all the apples lie on one side and all the pears on the other. Fruit on the wrong side gets a red ring; with you put the line back. As soon as your line separates everything, the demo draws an empty band around it, as wide as the fruit allows: the margin. Then make that margin as wide as possible: the fruit with a purple ring holds it back.

Loading demo

A horizontal line, which only looks at the height, does not work: the two smallest pears (81 and 83 mm tall) are no taller than the tallest apple (83 mm). You have to tilt the line, because a pear is mainly tall relative to its width. Two classes that you can separate with one straight line like this are called linearly separable.

πŸ“ The wider, the safer

Quite a few lines separate all the apples from all the pears, but which one do you trust most for new fruit? A line that just grazes a pear is risky: a new pear that is only slightly wider already ends up on the wrong side. Safer is the line with the widest possible margin, as you already tried to find in the demo above: a street as wide as possible between the apples and the pears, with the boundary as its center line. New fruit that differs a little from the fruit you already saw then still falls on the right side. It is a safety margin, just as you do not design a bridge for exactly the expected load either.

Support vector machine Definition

The margin is the empty band around a boundary, up to the nearest points on either side. A (linear) support vector machine (SVM) separates two classes with the straight boundary that leaves the widest margin.

How close did you get? In the demo above, click the trophy: the widest margin appears as a dashed line, and you see what share of it you achieved. It is 12.4 mm wide, and there is only one: shift or tilt the boundary a little, and the margin becomes narrower.

πŸ›‘οΈ Support vectors

The widest margin rests on just three pieces of fruit: two apples on one edge and one pear on the other. They are the borderline cases: the apples that look most like a pear, and the pear that looks most like an apple. Those three are called the support vectors: they support the margin, and give the method its name. A vector here is simply a data point, a list of numbers such as the width and the height.

Try it out:

  • Drag an apple far from the boundary: nothing changes. Drag a support vector: the boundary turns and shifts with it.
  • With you show only the support vectors. The model needs nothing more to determine the boundary.
  • Choose "One apple, one pear" from the menu: the boundary then runs exactly through the middle between the two, just as with one neighbor (you show the regions of the nearest neighbor with ). Choose 🍎 or 🍐 at the top and click in the chart to add fruit: only fruit that ends up inside the margin or on the wrong side of the boundary moves it, while the boundary of the nearest neighbor breaks into more and more pieces.
  • Put a pear in the middle of the apples: now no straight line separates the two kinds anymore, so the SVM finds no boundary. The nearest neighbor has no problem with that: it simply draws a little island around that pear. You will see how an SVM deals with this in the section on the soft margin.
Loading demo

This is the big difference from nearest neighbors, which remembers all the fruit and goes through it for every question. An SVM does the work once, during training, and afterwards keeps only the line, which depends only on the support vectors. So it is not a lazy learner but an eager learner.

🎯 Classifying new fruit

A trained SVM classifies new fruit by looking at which side of the boundary it lies on.

Try it out: click or drag in the chart to place a new piece of fruit. On the right you see the predicted kind and the distance to the boundary.

Loading demo

That distance also says something about how sure the model is. A piece of fruit 70 mm wide and 85 mm tall lies inside the margin, only 2.7 mm from the boundary: closer to the boundary than all the training fruit, so a borderline case. An SVM thus gives a score, but not a probability: "2.7 mm on the pear side" does not mean "70% probability of a pear".

πŸ” What the line tells you

You can read a straight boundary as a points tally. For the boundary with the widest margin, which the SVM found above, every piece of fruit gets +0.125 points per millimeter of height and βˆ’0.101 points per millimeter of width. If it scores more than 3.11 points in total, it is a pear, otherwise an apple. The 70 by 85 mm piece of fruit from above scores a little over 3.5 points: a pear, but only just.

Those points per feature are called the weights of the model, and they tell you right away what it has learned:

  • The sign says in which direction a feature pushes: positive for the height, so the taller, the more pear; negative for the width, so the wider, the more apple.
  • The size says how heavily a feature counts. A millimeter of height weighs slightly more than a millimeter of width, but the difference is small, so the model mainly looks at how much taller than wide a piece of fruit is. That is why you had to tilt the line.
  • A weight close to zero says that a feature hardly matters. If you also measure how heavy each piece of fruit is, that feature gets its own points per gram, and you see right away whether it adds anything on top of the width and the height.

You can only compare weights if the features are on the same scale. Width and height are both in millimeters, but you cannot simply compare the weight of a feature in grams with that of a feature in millimeters: normalize the features first.

Being able to see in the model itself what it bases its decisions on is called interpretability. It lets you check whether the model looks at the right things, and explain why it reached a decision. That matters as soon as a decision affects people, as with a loan or a medical diagnosis.

Weights as an image Remark

In an image every pixel is a feature, so every pixel gets a weight of its own. If you put each weight in the place of its pixel, the weights themselves form an image, with the pixels that argue for one class in one color and those that argue for the other class in the other.

🧾 The margin in formulas

You write a straight line as a weighted sum of the features. For a piece of fruit x\mathbf{x} with width x1x_1 and height x2x_2 that is

f(x)=w1x1+w2x2+bf(\mathbf{x}) = w_1 x_1 + w_2 x_2 + b

with two weights w1w_1 and w2w_2 and an offset bb. The boundary is the line where f(x)=0f(\mathbf{x}) = 0. On the pear side ff is positive, on the apple side negative, and the farther a piece of fruit lies from the boundary, the larger ff is in absolute value. For the SVM from the demos that is

f(x)=βˆ’0.101β‹…width+0.125β‹…heightβˆ’3.11f(\mathbf{x}) = -0.101 \cdot \text{width} + 0.125 \cdot \text{height} - 3.11

That is the points tally from above: ff is the number of points minus the threshold of 3.11. More compactly, you write f(x)=wβ‹…x+bf(\mathbf{x}) = \mathbf{w} \cdot \mathbf{x} + b, with the weights together in a vector w=(w1,w2)\mathbf{w} = (w_1, w_2) and wβ‹…x=w1x1+w2x2\mathbf{w} \cdot \mathbf{x} = w_1 x_1 + w_2 x_2 their dot product. With more features you simply get more weights, and the line becomes a hyperplane (with three features, a flat plane).

An SVM puts the edges of the margin on the lines where f(x)=1f(\mathbf{x}) = 1 and f(x)=βˆ’1f(\mathbf{x}) = -1. How far those edges lie from the boundary then depends on the size of the weights: with small weights ff grows only slowly as you step away from the boundary, so the edges lie far away.

Width of the margin Rule
margin=2βˆ₯wβˆ₯withβˆ₯wβˆ₯=w12+w22\text{margin} = \frac{2}{\lVert\mathbf{w}\rVert} \qquad \text{with} \qquad \lVert\mathbf{w}\rVert = \sqrt{w_1^2 + w_2^2}

The smaller the weights, the wider the margin. For the apples and pears that is 2/0.1012+0.1252β‰ˆ12.42 / \sqrt{0.101^2 + 0.125^2} \approx 12.4 mm.

So finding the widest margin means: choose w\mathbf{w} and bb so that βˆ₯wβˆ₯\lVert\mathbf{w}\rVert is as small as possible, on condition that every pear lies on or beyond its edge (f(x)β‰₯1f(\mathbf{x}) \geq 1) and every apple on or beyond its own (f(x)β‰€βˆ’1f(\mathbf{x}) \leq -1).

In the demo below you see ff and the margin in numbers. Place new fruit on the edge of the margin: ff is about 11 or βˆ’1-1 there, and about 00 on the boundary.

Loading demo

🧽 Soft margin

🍐 One round pear

So far one pear from the nearest neighbors dataset has stayed out of the picture: a strikingly round pear, 60 mm wide and 72 mm tall. If you put it back, the widest margin shrinks from 12.4 mm to 5.1 mm. One exception now determines the whole boundary, just as a single point got its own little island with one neighbor.

With a nashi pear (external link) (an Asian pear, as round as an apple) among the apples, not a single straight line separates all the apples from all the pears anymore. The strict version from above, in which no piece of fruit may lie inside the margin, is called an SVM with a hard margin, and it then has no solution. Real data can rarely be separated so neatly: measurements are imprecise, labels are sometimes wrong, and classes often overlap a little.

🎚️ How strict: C

With a soft margin, fruit may lie inside the margin, and even on the wrong side of the boundary, but every violation costs penalty points: the farther past the edge on its own side, the more. The SVM then looks for a compromise between a wide margin and as few penalty points as possible.

You set how heavily those penalty points weigh with a number CC, which, like kk, is a hyperparameter you choose beforehand:

  • A high CC is strict: the boundary follows every exception and the margin stays narrow, with a risk of overfitting. C=∞C = \infty forbids every violation: that is the hard margin.
  • A low CC is lenient: a wide margin that ignores exceptions. If CC is too low, the model also ignores the real differences between the classes: underfitting.

Try it out: the demo starts with the round pear and C=∞C = \infty, a margin of 5.1 mm.

  • At C=10C = 10 the SVM gives up on that one pear (it ends up on the wrong side), and the margin becomes more than twice as wide: 12.4 mm, the same margin as without the round pear.
  • At C=1C = 1 the margin is 24.1 mm wide, but six pieces of fruit lie inside that margin, and the round pear is still on the wrong side. The orange lines show how far each violator lies past the edge on its own side.
  • Choose "With a nashi pear" from the menu: at C=∞C = \infty the SVM finds no boundary, at every finite CC it does.
Loading demo

You measure which CC is best on fruit the model did not see. Just as you choose kk with nearest neighbors, you choose CC with a validation set or with cross-validation, and you try values on a logarithmic scale (0.01, 0.1, 1, 10, 100). Which value works well depends on your data: the numbers in this demo hold for this fruit.

πŸͺ Penalty points in formulas

Give every pear the label y=+1y = +1 and every apple the label y=βˆ’1y = -1. Then yβ‹…f(x)β‰₯1y \cdot f(\mathbf{x}) \geq 1 for every piece of fruit that lies on or beyond the edge on its own side, and smaller than 11 for every violator. The penalty points of a piece of fruit are

max⁑(0,β€…β€Š1βˆ’yβ‹…f(x))\max\bigl(0,\; 1 - y \cdot f(\mathbf{x})\bigr)

If it lies on or beyond its own edge, that is 00. Otherwise it is how far it lies past that edge, measured in half margin widths: between 00 and 11 inside the margin, more than 11 on the wrong side of the boundary. That formula is called the hinge loss, after the kink (the hinge) at the edge.

A soft-margin SVM then chooses the w\mathbf{w} and bb for which this sum is as small as possible:

min⁑w, bβ€…β€Šβ€…β€Š12βˆ₯wβˆ₯2β€…β€Š+β€…β€ŠCβˆ‘imax⁑(0,β€…β€Š1βˆ’yi(wβ‹…xi+b))\min_{\mathbf{w},\, b} \;\; \tfrac{1}{2}\lVert\mathbf{w}\rVert^2 \;+\; C \sum_i \max\bigl(0,\; 1 - y_i(\mathbf{w}\cdot\mathbf{x}_i + b)\bigr)

Here xi\mathbf{x}_i and yiy_i are the features and the label of the ii-th piece of fruit. The first term is small when the weights are small, so when the margin is wide. The second term adds up the penalty points of all the fruit, and CC weighs the two against each other. At C=∞C = \infty every violation is unaffordable: that is the hard margin from above.

The orange lines in the demo show the penalty points of each piece of fruit. At C=1C = 1 the round pear gets just over 11, because it lies just on the wrong side of the boundary. Lower CC and watch the weights in ff get smaller and the margin wider.

Loading demo

Such a sum of penalty points over all the data is called a loss function, and the chapter on regression covers it at length.

πŸŒ€ The kernel trick

An SVM always draws a straight boundary, but with extra features it can still become a curved boundary. Suppose a fruit company sends the medium-sized apples to the shop, and the ones that are too light or too heavy to the juice factory. On the weight axis the shop apples then lie in the middle and the juice apples on both sides: no single threshold separates them.

Try it out: click "Add weightΒ²". Every apple gets the square of its (scaled) weight as a second feature, and moves up onto a parabola. In that plane a straight line does separate the two kinds, and back on the axis that comes down to two thresholds: shop between 138 g and 217 g, juice outside that range.

Loading demo

A straight boundary in the new space thus becomes a curved boundary in the old one, just as x2x^2 turns a straight line into a curve in regression.

With many features, such extra features quickly add up: with a hundred features there are already more than five thousand squares and products of two features. Fortunately an SVM never has to compute them itself. It follows from the math behind the widest margin that it always uses the features of two points together, in one number that says how strongly those points resemble each other: their dot product. A kernel is a formula that computes that number for the larger space directly from the original features. That way the SVM works as if it had all the extra features, without ever computing or storing them: that is the kernel trick.

The most popular kernel, and the default in scikit-learn (kernel="rbf"), measures that similarity as closeness: two points that lie close to each other resemble each other strongly. What the SVM does with it is best seen as a landscape above the features, with ff as the height. Every support vector pushes the land around it up (for one class) or down (for the other), and the closer a point lies to that support vector, the stronger the push. The boundary is then the coastline: where the land rises above sea level (f>0f > 0), the SVM predicts one class, below it the other. A new point thus gets the class of the support vectors in its neighborhood: a kind of nearest neighbors with only the support vectors as neighbors.

Try it out: the shop now only takes nice, medium-sized apples, so not too small, not too large, not too flat and not too elongated. With width and height as features, the shop apples then lie like an island in the middle, with the juice apples around them, and no straight line separates the two. On the left you see the boundary that an SVM with an RBF kernel finds, on the right the landscape behind it: drag it to rotate it.

Loading demo

You set how wide each hill is with a second hyperparameter, Ξ³\gamma (gamma). With a small Ξ³\gamma the hills are wide: five support vectors are enough for one smooth, round island, just as a large kk gives a smooth boundary with nearest neighbors. With a large Ξ³\gamma they become narrow peaks: at Ξ³=300\gamma = 300 every piece of fruit is a support vector, and the island falls apart into eight little islands around the shop apples. As with k=1k = 1, the boundary then follows every point separately, and that is overfitting. Like CC, you therefore choose Ξ³\gamma with cross-validation.

πŸ”§ Strengths and weaknesses

βœ… Strengths

❌ Weaknesses

  • πŸ“ Only straight boundaries: a curved boundary needs extra features, a kernel or another model, such as a decision tree. With a kernel you do lose the readable weights.
  • πŸ”’ Sensitive to scale: the margin is a distance, so just as with nearest neighbors, the feature with the largest numbers dominates. So normalize the features first.
  • 🎲 No probabilities: an SVM says on which side and how far a point lies from the boundary. If you want a probability, you have to convert the scores afterwards and calibrate them.
  • πŸ”€ Only two classes at a time: for more classes you train several, for example one per class that separates that class from all the others (one-vs-rest), and the class with the highest score wins.
  • 🐒 Slow with a great deal of data, with a kernel: the computing time for training then grows at least quadratically with the number of examples, so training gets slow beyond a few tens of thousands of examples. A linear SVM suffers less from this: with a different training algorithm it trains on millions of examples too. On such large datasets, though, neural networks and groups of decision trees usually get better results.

🏭 When do you choose an SVM?

A linear SVM suits small to medium-sized datasets with clean, numeric features, especially when there are many features compared to few examples. Like nearest neighbors, it is a strong baseline, and an obvious choice when you need a fast, compact predictor that you can explain and that gives the same result every time you train it.

🏘️ Nearest neighborsπŸ›‘οΈ Support vector machine
What the model keepsall the fruitone line, determined by the support vectors
Shape of the boundarypiece by piece, as irregular as the dataone straight line
Trainingnothing: storing the data is enoughfinding the widest margin
Predictingcomputing the distance to all the fruitlooking at which side of the line the point lies on
Certaintythe ratio of the votesthe distance to the boundary, no probability
Explanation of a predictionthe neighbors that votedone weight per feature
Scale of the featuresnormalize firstnormalize first
Hyperparameterthe number of neighbors kkthe strictness CC
From Moscow to Bell Labs Did you know?

The idea of the widest margin comes from the Soviet mathematicians Vladimir Vapnik and Alexey Chervonenkis, in the 1960s. The SVM as you know it now, with the kernel trick and the soft margin, came about in the 1990s at AT&T Bell Labs in the United States. Around the turn of the century it was one of the most popular methods for recognizing handwriting, classifying texts and finding pedestrians in camera images, until deep neural networks took over for images and text from 2012 onward.

πŸ§ͺ Hands-on

In this Jupyter notebook you train a support vector machine yourself in Python, with the scikit-learn library. First on the apples and pears from this chapter: you find the same support vectors and weights again, and see what the strictness CC does with the round pear. Then on handwritten digits, in which every pixel is a feature: the weights then form an image themselves, and the support vectors show which zeros look most like a one, and the other way around. Finally a kernel draws a curved boundary around the shop apples, and you see why you first put the features on the same scale.

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.

πŸ•ΉοΈ Demos

πŸ—£οΈ Feedback

Just like machine learning algorithms, we also love learning from your feedback to improve the course.

Let us know how informative and how difficult you found this chapter, and where it could be better.

How informative did you find this chapter?
Was the difficulty of this chapter right for your level of knowledge and skill? This chapter was...
Anonymous with random ID