π‘οΈ 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.
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.
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.
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.
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.
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 with width and height that is
with two weights and and an offset . The boundary is the line where . On the pear side is positive, on the apple side negative, and the farther a piece of fruit lies from the boundary, the larger is in absolute value. For the SVM from the demos that is
That is the points tally from above: is the number of points minus the threshold of 3.11. More compactly, you write , with the weights together in a vector and 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 and . How far those edges lie from the boundary then depends on the size of the weights: with small weights grows only slowly as you step away from the boundary, so the edges lie far away.
The smaller the weights, the wider the margin. For the apples and pears that is mm.
So finding the widest margin means: choose and so that is as small as possible, on condition that every pear lies on or beyond its edge () and every apple on or beyond its own ().
In the demo below you see and the margin in numbers. Place new fruit on the edge of the margin: is about or there, and about on the boundary.
π§½ 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 , which, like , is a hyperparameter you choose beforehand:
- A high is strict: the boundary follows every exception and the margin stays narrow, with a risk of overfitting. forbids every violation: that is the hard margin.
- A low is lenient: a wide margin that ignores exceptions. If 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 , a margin of 5.1 mm.
- At 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 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 the SVM finds no boundary, at every finite it does.
You measure which is best on fruit the model did not see. Just as you choose with nearest neighbors, you choose 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 and every apple the label . Then for every piece of fruit that lies on or beyond the edge on its own side, and smaller than for every violator. The penalty points of a piece of fruit are
If it lies on or beyond its own edge, that is . Otherwise it is how far it lies past that edge, measured in half margin widths: between and inside the margin, more than 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 and for which this sum is as small as possible:
Here and are the features and the label of the -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 weighs the two against each other. At 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 the round pear gets just over , because it lies just on the wrong side of the boundary. Lower and watch the weights in get smaller and the margin wider.
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.
A straight boundary in the new space thus becomes a curved boundary in the old one, just as 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 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 (), 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.
You set how wide each hill is with a second hyperparameter, (gamma). With a small the hills are wide: five support vectors are enough for one smooth, round island, just as a large gives a smooth boundary with nearest neighbors. With a large they become narrow peaks: at every piece of fruit is a support vector, and the island falls apart into eight little islands around the shop apples. As with , the boundary then follows every point separately, and that is overfitting. Like , you therefore choose with cross-validation.
π§ Strengths and weaknesses
β Strengths
- π Readable: a linear SVM gives every feature a weight, so you see which features steer the decision and in which direction. That helps to check the model and to explain its decisions.
- π― Strong with little data and many features: the wide margin leaves room for variation and only the support vectors count, which counters overfitting. Think of tens to thousands of examples with hundreds of features: spectra (one feature per wavelength), vibration measurements of machines, or texts (one feature per word).
- π Always the same solution: there is only one boundary with the widest margin, so the same data and the same always give the same model. Handy when you have to validate a model or have it certified.
- β‘ Compact and fast at prediction time: you keep only the line, and a prediction is one short calculation, even on a small chip in a sensor.
- ποΈ Few knobs: a linear SVM has only one hyperparameter, the strictness .
β 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 keeps | all the fruit | one line, determined by the support vectors |
| Shape of the boundary | piece by piece, as irregular as the data | one straight line |
| Training | nothing: storing the data is enough | finding the widest margin |
| Predicting | computing the distance to all the fruit | looking at which side of the line the point lies on |
| Certainty | the ratio of the votes | the distance to the boundary, no probability |
| Explanation of a prediction | the neighbors that voted | one weight per feature |
| Scale of the features | normalize first | normalize first |
| Hyperparameter | the number of neighbors | the strictness |
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 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.

πΉοΈ Demos
Experiment further with the full simulators and demos featured above.
π£οΈ 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.
