Neighbors, Kernels & SVMs
Learning by similarity: nearest neighbors, margins and the kernel trick.
To guess what a house will sell for, look at the prices of similar houses nearby. That simple idea, predict like your neighbors, grows into some of the most elegant models in machine learning: nearest neighbors, support vector machines that find the widest gap between two classes, the kernel trick that bends straight lines into curves, and Gaussian processes that put error bars on their own predictions.
What you’ll learn
- Classify a new point by a vote of its nearest neighbors, and explain how trades flexibility for stability.
- Explain why distances need features on comparable scales, and why "nearest" means less and less as the number of features grows.
- Describe a support vector machine as the widest street between two classes, and say why only the points on its edges matter.
- Use the kernel trick's core idea: add a feature such as so that a straight cut separates data no line could.
- Read a Gaussian process's prediction and error band, and explain why the band widens away from the data.
Learning by similarity
Most learning methods build a formula from the data and then throw the data away. k-nearest neighbors (k-NN) does the opposite: it keeps every example and builds nothing. To classify a new point it does three things:
- Measure the distance from the new point to every example in the training set.
- Pick the closest examples, its neighbors.
- Let them vote: predict the most common label among them. (To predict a number, such as a price, average their values instead.)
The whole method rests on one assumption: points that are close together tend to have the same answer. Everything in this topic is a way of making "close" and "similar" precise.
| Training point | Position | Class | Distance to the new point |
|---|---|---|---|
| A | red | ||
| B | blue | ||
| C | blue | ||
| D | red | ||
| E | red |
Using the table, what does 3-nearest-neighbors predict for the point , and what changes with ?
- Red for , because there are more red points overall
- Blue for ; with every point votes and red wins, 3 to 2
- Blue for both, because the single closest point is blue
- It cannot be decided, because A and D are tied
Show the answer
B. Blue for ; with every point votes and red wins, 3 to 2
The three closest points are C (1), B (1.41) and E (2): two blue, one red, so the prediction is blue. With all five points vote, and the three reds outvote the two blues. The choice of can flip the answer.
How many neighbors?
The number is not learned from the data: you choose it, so it is a hyperparameter. It sets how local the vote is.
With each training point claims the patch of the plane closest to it, so a single mislabeled or unusual point carves out its own island. With a large the vote averages over a wide neighborhood: islands disappear and the boundary smooths out, but a real bend in the classes can get averaged away too.
Think first k-NN has no training phase at all. So where does it pay the price?
At prediction time. Every new query must be compared with every stored example, so the cost of one prediction grows with the size of the training set, and the whole training set must be kept in memory. Search structures such as k-d trees, and approximate methods that find almost nearest neighbors, make this practical for millions or billions of points.
What counts as close?
Each example is a list of numbers, its features. With two features, the Euclidean distance between examples and is Pythagoras again, and it extends to any number of features by adding more squares:
| Customer | Age (years) | Income ($) | Distance to Q, raw | Distance to Q, standardized |
|---|---|---|---|---|
| Q (new) | 30 | 50,000 | — | — |
| P1 | 31 | 58,000 | 8,000 | 0.41 |
| P2 | 55 | 51,000 | 1,000 | 2.08 |
The fix is standardization: rescale each feature to mean 0 and standard deviation 1 before measuring distances. Compute the means and spreads on the training data only, then apply the same rescaling to new points. Changing a feature's units should not change who your neighbors are, and after standardizing it does not.
There is a second, stranger problem. In two dimensions, the 10 points nearest to a query really are close by. With hundreds of features that all vary independently, data are spread so thinly that even the nearest neighbors are far away, and all points end up at roughly the same distance from each other. This is the curse of dimensionality. (Real data often vary along far fewer directions than they have features, which softens the curse.)
Points are spread uniformly through a cube with 10 features, each ranging from 0 to 1. A smaller cube-shaped neighborhood should hold 10% of all the points. What fraction of each feature's range must its sides span?
Show the answer
79 %
A cube with side holds a fraction of the points, so gives . To catch just 10% of the data you must span 79% of every feature's range: the "neighborhood" is hardly local at all. In one dimension the side would be 10%; with 100 features it would be 98%.
The widest street
Now a different way to use geometry. When two classes can be split by a straight line, there are usually infinitely many such lines. Which one should you pick?
A support vector machine (SVM) picks the line that leaves the widest empty street between the classes, with the line running down the middle. The distance from the line to the nearest training points, half the street's width, is the margin, and the line with the largest margin is the maximum-margin separator. A wide margin means a new point can wander a long way from the training points of its class before it lands on the wrong side.
The street's edges rest on a few training points, the support vectors. They alone decide where the line goes. Every other point could move, or vanish, as long as it stays off the street, and nothing would change.
Real classes overlap, so a perfectly empty street rarely exists. The SVM therefore lets some points stand in the street, or on the wrong side, and charges a penalty for each. A setting called chooses the balance: a large makes violations expensive and narrows the street to fit the training points closely; a small accepts more violations in exchange for a wider, calmer street. This version is the soft-margin SVM, and is tuned like , by cross-validation.
Try the slider in the widget above (press "Reset points" first if you moved any). The start is . At the street is wider than the plot and all 60 points are support vectors; at the street is narrow and only 11 remain.
You train an SVM, then delete a training point that sits far from the street on its correct side, and train again. What happens to the boundary?
- It moves a little, because every point pulls on the line
- It moves toward the deleted point's old position
- It does not change at all
- The street gets narrower, because there is less data
Show the answer
C. It does not change at all
The boundary depends only on the support vectors, the points on or inside the street's edges. A point far away on its correct side has no say, so removing it leaves exactly the same street. That sparsity is the signature of the SVM.
The kernel trick: when no line will do
Some classes cannot be separated by any straight line. Picture one class filling a disk and the other forming a ring around it. No line can put the disk on one side and the ring on the other.
Here is the trick. Give each point one extra feature, its squared distance from the center, . Points in the disk have small and points in the ring have large , so a single threshold on the new feature separates them perfectly.
| Point | new feature | Class | ||
|---|---|---|---|---|
| 1 | 0.2 | 0.1 | 0.05 | disk |
| 2 | −0.1 | 0.3 | 0.10 | disk |
| 3 | 0.7 | 0.1 | 0.50 | ring |
| 4 | −0.4 | −0.5 | 0.41 | ring |
Adding features by hand works, but how do you know which ones to add, and what if you need thousands of them? The SVM has a remarkable property: the algorithm never needs the new features themselves. It only ever asks how similar are these two points?, computed as a sum of products of their features. A kernel is a function that computes that similarity directly, as if the points had been lifted into a large feature space, without ever building the space. This is the kernel trick.
The most popular kernel, the RBF (Gaussian) kernel, is a similarity that fades with distance:
Predictions with error bars
Suppose you measure a quantity, say the temperature of a chemical reaction, at only a handful of settings. You want a smooth curve through the measurements, and you also want to know where the curve is a guess.
A Gaussian process (GP) uses a kernel in a third way: as a statement about functions. It says that the outputs at two inputs are similar when the inputs are close. Before any data it allows countless possible curves. Each measurement makes the curves that miss it far less plausible, and what remains gives two things: a best-guess curve and a band of uncertainty around it.
Think first You can afford one more measurement. Where would the GP's picture tell you to take it?
Where the band is widest, if you want to learn the most about the curve, or where the band's top edge is highest, if you are hunting for the largest value. Choosing the next experiment from a GP's uncertainty is the idea behind Bayesian optimization, which tunes everything from chemical recipes to the hyperparameters of other machine learning models.
One idea, four methods
Every method in this topic replaces "learn a formula" with "measure similarity". k-NN votes among the most similar examples. An SVM keeps only the examples at the edge of the street and weighs them by a kernel. The kernel trick lets any method that only needs similarities work in a huge feature space for free. A Gaussian process turns similarity into uncertainty.
The price is the same everywhere: these methods compare examples with each other, so their cost grows quickly with the number of examples. With millions of examples, approximations are needed, and neural networks, which learn their own features, often take over.
| Descent lesson | What you will do there |
|---|---|
| Nearest Neighbors | Make k-NN precise: distance choices, weighted votes, regression, the bias–variance role of , fast search with k-d trees, and the Cover–Hart bound. |
| Support Vector Machines | Derive the margin , set up the optimization problem, add slack variables and , and meet the hinge loss. |
| The Kernel Trick | Build feature maps, prove which functions are valid kernels, and kernelize ridge regression and the SVM. |
| Gaussian Processes | Condition a Gaussian on data to get the posterior mean and variance, and fit the length scale by maximizing the marginal likelihood. |
Key takeaways
- k-NN stores the training data and predicts by a vote (or an average) of the closest examples. Small overfits, large underfits, and cross-validation picks .
- Distances depend on units: standardize features before using them. In very high dimensions, neighborhoods stop being local, the curse of dimensionality.
- A support vector machine picks the separating line with the widest margin. Only the support vectors, on or inside the street's edges, determine it, and trades margin width for violations.
- The kernel trick computes similarities in a lifted feature space without building it, so a linear method draws curved boundaries. The RBF kernel is the most common choice.
- A Gaussian process uses a kernel to predict a curve together with an uncertainty band that is narrow near data and wide far from it.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
On noisy two-class data, you raise in k-NN from 1 to 25. What typically happens?
- The boundary gets more jagged and training accuracy rises
- Nothing changes, because the same points are stored
- The test accuracy always keeps rising
- The boundary gets smoother and training accuracy falls from 100%
Show the answer
D. The boundary gets smoother and training accuracy falls from 100%
A larger vote averages over a bigger neighborhood, so isolated points stop carving islands and the boundary smooths out. Training accuracy drops from its perfect value, because a point is now outvoted by its neighbors when it disagrees with them. Test accuracy usually rises at first and falls once is too large.
A k-NN model uses two features: a person's height in meters and their yearly income in dollars, both unscaled. What does its distance mostly measure?
- Height and income equally
- Mostly height, because it is listed first
- Mostly income, because its differences are numerically far larger
- Neither: k-NN ignores units automatically
Show the answer
C. Mostly income, because its differences are numerically far larger
Heights differ by fractions of a meter while incomes differ by thousands of dollars, so the squared income differences swamp everything else. Standardizing each feature to mean 0 and standard deviation 1 puts them on an equal footing.
Which training points determine where an SVM's boundary goes?
- The support vectors: the points on the edges of the street or inside it
- All points equally, as in an average
- The points farthest from the boundary
- The centers of the two classes
Show the answer
A. The support vectors: the points on the edges of the street or inside it
The SVM's solution can be written using only the support vectors. Points beyond the street's edges, on their correct side, have no influence: move or delete them and the boundary stays the same.
What does a kernel let an SVM do?
- Train faster by ignoring most of the data
- Behave as if the data were mapped into a much larger feature space, computing only similarities between pairs of points
- Remove the need to choose any settings
- Guarantee 100% test accuracy on any dataset
Show the answer
B. Behave as if the data were mapped into a much larger feature space, computing only similarities between pairs of points
The SVM needs the data only through similarities between pairs of points. A kernel computes the similarity the points would have in a lifted feature space, so a straight boundary there, which can be a curve in the original space, comes at no extra cost.
A Gaussian process has been given five observations, all between and . Where is its uncertainty band widest?
- Right at the observations
- Exactly in the middle of the observations
- Everywhere the same width
- Far from all the observations, for example at
Show the answer
D. Far from all the observations, for example at
The kernel says outputs are similar only when inputs are close. Near the observations the GP is pinned down; far from them the data say little, and the band relaxes to its width before any data were seen.
Go deeper
- Nearest Neighbors · Predict like your neighbors: k-NN, distances and scaling.
- Support Vector Machines · The widest street between two classes.
- The Kernel Trick · Nonlinear patterns with linear algebra.
- Gaussian Processes · Distributions over functions with honest error bars.
Further reading
- G. James, D. Witten, T. Hastie & R. Tibshirani, An Introduction to Statistical Learning, 2nd ed. (Springer, 2021), chapters 2, 4 and 9.
- C. E. Rasmussen & C. K. I. Williams, Gaussian Processes for Machine Learning (MIT Press, 2006), chapters 1 and 2.