A kernel is a shortcut. It lets a flat plane cut data that no straight line could, in a space with millions of extra features, without ever building one of them.
Learn how the support vector machine becomes a curved classifier: the geometry of the dual, the lift, the kernel that skips the lift, and the test that says which functions are kernels.
Pick Rings, drag Lift to the top, then slide the Plane until every point is on its own side. A flat cut up in 3-D leaves a circle on the floor. Then we build, piece by piece, the geometry, the lift, the kernel and a machine you can train.
You need a dot product (multiply two lists of numbers entry by entry, then add) and the support vector machine from the last two lessons. We recap both.
Based on Lecture 11 of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci (Winter 2019), here our Lecture 19. Lecture slides and the course slide index. All figures and devices are our own.
Toy data, 44 points made with a fixed seed (illustrative). Rings lift by z = x₁² + x₂². XOR corners lift by z = x₁·x₂. Both are the feature maps of Chapter 3.
Chapter 0
See what a line can and cannot cut, and recall the SVM and its dual that the rest of the lecture bends
A vibration sensor on a pump reports two numbers every second: x1 and x2, its readings on two axes. When the pump runs quietly, both numbers stay near zero. When something is wrong, the readings swing wide, but in any direction. Plot many seconds and you see a dense blob with a ring of alarm points around it.
You want a rule that says “quiet” or “alarm” for a new reading. The simplest rule is a linear classifier: a straight line in the plane, with “quiet” on one side and “alarm” on the other. Try it yourself below. The ring is the toy version of this pump.
Warm points are the quiet blob, blue points are the alarm ring. Turn the line and slide it. Red rings mark points on the wrong side. Then ask for the best of all the lines.
Toy data (illustrative): 40 points from a fixed seed, an inner blob and an outer ring. A line may name either side “quiet”, so a score below half is flipped. The best line is found by trying 180 angles and 101 offsets.
No line gets every point right. The best of 18,180 lines still leaves a fifth of the points on the wrong side. The reason is geometry. A line splits the plane into two half-planes, and a ring has the blob on the inside and the alarms on all sides. No half-plane holds the blob without also holding some of the ring.
Write a point as a list of numbers, x = (x1, x2). A line is the set of points where wTx + b = 0. The vector w (the weights) points across the line, and the number b (the bias) slides it. The symbol wTx is the dot product: w1x1 + w2x2.
The classifier is sign(wTx + b). A positive value says class +1. A negative value says class −1. The two sliders above are exactly w (the angle) and b (the offset).
Many lines can split two clean groups. The support vector machine (SVM) picks the one with the widest empty street between the groups. The width of the street is 2/‖w‖, so a wide street means a short w. Real data overlaps, so the SVM lets each point i cross its street by a small amount si, called a slack variable. The lecture opens with this problem.
The last lesson turned this problem inside out with convex duality. The new unknowns are one number αi per data point, a weight that says how much point i matters. Most αi end at zero. The points with a nonzero αi are the support vectors. The lesson before it built the primal form above.
This is the seed of the whole lecture. The data enter the dual only through dot products, and the answer is a mix of data points. If we can bend a line into a curve by changing only what the dot product means, the SVM draws curves for free.
Chapter 1
Turn the dual problem into a picture: find the two closest points of two convex hulls
Picture two clouds of pins stuck in a board: warm pins on the left, blue pins on the right. Stretch a rubber band around each cloud. Each band hugs its pins and encloses a flat shape. You now have two shapes with a gap between them. Where would you draw the fence?
Most people say: halfway across the narrowest part of the gap. That instinct is the support vector machine. This chapter proves it, using only the dual problem from Chapter 0 and a few steps of algebra. The proof matters later, because it shows that the SVM only ever cares about how far apart points are.
First, remove slack. Let C grow without limit. A huge C makes any crossing of the street too expensive, so every point must stay on its own side. This is the hard margin SVM. In the dual, the cap C/n on each αi disappears. The double sum also collapses into one squared length, because summing over every pair i, j is the same as squaring the sum.
Every label yi is +1 or −1. So the mixed vector is the warm points minus the blue points, each weighted by its α. Write i∈+ for the warm points and i∈− for the blue ones. The balance rule says the two groups carry equal total weight. The lecture then does six small moves, and each one is simple.
Now name the shapes. A weighted average of some points is their balance point: give each point a weight of 0 or more, make the weights sum to 1, and add up weight times point. The set of all such averages of a cloud is its convex hull, the shape the rubber band makes. So Σ+ αixi is some point inside the warm hull. And Σ− αixi is some point inside the blue hull.
This is the slide’s punchline: the dual SVM is the minimum distance between two convex hulls. Drag the pins below. The teal bar joins the two closest points, one on each hull. The SVM fence stands in the middle of that bar, at a right angle to it.
Drag any pin, or slide the blue group toward the warm one. Labels show each support vector’s α. The dashed lines are the fence and the two edges of the street.
Toy pins (illustrative). The closest pair is found exactly: every hull vertex against every edge of the other hull. The α labels use αi = γ* × (the point’s weight in its hull).
Take two warm points A = (3, 0) and B = (3, 2), and one blue point C = (1, 1). The warm hull is the vertical segment from A to B. The blue hull is the single point C. The closest point of the segment to C is (3, 1), the midpoint, so the weights on A and B are 0.5 each.
The squared distance is D = ‖(3, 1) − (1, 1)‖2 = 4. So γ* = 2/4 = 0.5. The weights in the original scale are αA = αB = 0.5 × 0.5 = 0.25 and αC = 0.5 × 1 = 0.5. They balance: 0.25 + 0.25 − 0.5 = 0.
Now rebuild w. Use w* = Σ αiyixi = 0.25(3, 0) + 0.25(3, 2) − 0.5(1, 1) = (1, 0). The bias comes from a support vector on the street edge: 3 + b = 1, so b = −2. The blue point checks out: 1 − 2 = −1. The street is 2/‖w‖ = 2 units wide, which is exactly the distance between the hulls.
D = 4 → γ* = 2/D = 0.5 → w* = (1, 0), b = −2 → street = 2/‖w*‖ = 2 = distance between hulls
Slide the blue group left in the device until the shapes overlap. The symptom is that the distance reads 0. The measurement is D = 0, so γ* = 2/D has no value: no fence can keep every point on its own side. The fix is the one Chapter 0 already holds. Bring the slack back with a finite C, and let a few points cross.
Chapter 2
Score every class with its own line, then compare the one-vs-all and one-vs-one shortcuts
A microphone is clamped to a motor. Every second it reports two numbers, summarizing the sound. The motor can be in one of three states: healthy, unbalanced, or a worn bearing. You want a rule that names the state. One line can only split the plane into two halves. Three states need a different idea.
The SVM so far answers a yes-or-no question. The lecture now extends it to K classes, with K = 3 here. There are two ways to do it, and the lecture shows both.
Give every class its own line: a weight vector wk and a bias bk. For a point x, class k gets the score wkTx + bk. A big score means “this looks like class k.” The prediction is the class with the biggest score. The lecture’s prediction slide says exactly this.
Look at the shapes. A point x has d numbers. Stack the K weight vectors into a matrix W with K rows and d columns. Then W x + b is a list of K scores, and the arg max of that list is the answer. For the motor, d = 2 and K = 3, so W holds 6 numbers and b holds 3.
The training rule is the two-class street rule, repeated. The score of the correct class must beat every other class by a margin of 1, minus a slack si for point i. The lecture writes it like this.
Take the point x = (2, 1) with true class A. Suppose the three scores are 3.1 for A, 2.4 for B and −0.5 for C. The closest rival is B. The lead is 3.1 − 2.4 = 0.7. The rule asks for a lead of 1 − s, so 0.7 ≥ 1 − s, which gives s ≥ 0.3. The classifier is right, because A wins. But the point sits inside the margin, so it pays slack 0.3.
Only the nearest rival matters, because beating the closest rival by 1 also beats every farther rival by more than 1. Try it below. The button trains the three lines on 30 toy points with the lecture’s rule, using gradient steps.
Each tinted region is where one class has the top score. Press Train and watch the three lines settle. Ringed points are inside a margin or wrong.
Toy data (illustrative): three blobs of 10 points, a fixed seed. Training is plain subgradient descent on the lecture’s objective, step 0.05, so the lines are close to the optimum, not exact. The third class borrows purple.
Notice the regions meet at a point, and every border is a straight line. Each border is where two scores tie. A straight line is still all this method can draw. Chapter 3 fixes that.
You can also reuse the two-class SVM you already have. The lecture offers two ways. In one vs all, train K binary SVMs: class k against every other class, for k = 1 to K. To predict, pick the class whose classifier gives the highest score. In one vs one, train one SVM for every pair of classes, which is K(K−1)/2 classifiers. To predict, let each pair vote, and pick the class with the most votes.
The counts grow quickly. With K = 10 classes, one vs all trains 10 SVMs and one vs one trains 45. With K = 26 letters of the alphabet, it is 26 and 325. But each one-vs-one SVM sees only two classes, so about 2n/K points instead of n.
Slide the number of classes K. The bars show how many binary SVMs each plan trains.
The counts K and K(K−1)/2 are the lecture’s. The cost line is our arithmetic and assumes training cost grows like n² and balanced classes (illustrative).
That last read-out is a reminder, not a rule. One vs one trains many more models, but each model is small. If training cost grows faster than the data size, the many small models can cost less in total. If it grows only in a line, one vs all wins. Ties in the vote need a rule too, for example adding up the decision values. That detail is not on the slide.
Chapter 3
Add new features made from the old ones, and watch a circle turn into a plane
Go back to the sensor ring. The quiet blob sits at the centre, and the alarms circle it. No line cuts it. But a circle cuts it perfectly: inside the circle is quiet, outside is alarm. A circle is described by a centre (c1, c2) and a radius r. The rule is the lecture’s circular classifier, one line long.
class = sign( (x1 − c1)2 + (x2 − c2)2 − r2 ) (positive outside the circle, negative inside)
This rule is not linear in x, because x1 and x2 appear squared. The trick of this chapter is to ask a different question. Is it linear in other numbers built from x? Expand the squares and see.
Multiply out the two brackets. You get x1² + x2² − 2c1x1 − 2c2x2 + (c1² + c2² − r²). Every term is a number times one of five ingredients: x1, x2, x1x2, x1² and x2², plus one constant. The lecture lists exactly these five as the feature map.
Here is a full check. Take the circle with centre (1, −0.5) and radius 1.5. Then w = (−2, 1, 0, 1, 1) and b = 1 + 0.25 − 2.25 = −1. Test the point x = (1, 0.5). Its features are Φ(x) = (1, 0.5, 0.5, 1, 0.25). The dot product is −2 + 0.5 + 0 + 1 + 0.25 = −0.25, and adding b gives −1.25. The negative sign says “inside.” The direct formula agrees: 0² + 1² − 2.25 = −1.25. Same number, two routes.
Move the circle. The bars on the right are the weights w and the bias b that the lifted linear rule needs to draw that exact circle.
Toy data (illustrative): 44 points of a ring pair centred at (0.8, −0.4), with a little radial noise. The score is computed with the five features, not with the circle formula, so the two always agree. “Best circle” scans centres and radii.
The lecture calls the map Φ a lift. Think of the flat plane as a sheet on the floor. Each point is pushed up to a height set by the new features. Take only the height z = x1² + x2². The sheet bends into a bowl. The blob at the centre sits at the bottom. The ring is up the walls. A flat cut across the bowl at height h now separates them. That is the hero at the top of this page.
Look at what the flat cut does back on the floor. The plane meets the bowl where x1² + x2² = h, which is a circle of radius √h. A tilted plane z = a x1 + b x2 + h gives a circle with centre (a/2, b/2) and radius² = h + (a² + b²)/4. So every circle is the shadow of some plane. Hyperplanes in the lifted space are curves in the original space. That is the whole idea of the lecture’s “Hyperplanes in lifted space” picture.
The lecture reminds us of an old friend from the Bayes classifier lesson. You record N samples x1, …, xN. Under class 1 they are pure noise with variance σ1². Under class 2 they are signal plus noise, with a larger variance σ2². The best rule, with prior chances π1 and π2, says “class 2” when the following holds.
Read it as a feature map. Let Φ(x) be the single number Σ xi². The rule is linear in that one feature: weight times Φ against a threshold. Here the lift goes down from N numbers to 1. The lesson is the same: choose features in which a flat rule works. A worked case: N = 64, σ1² = 1, σ2² = 2 and equal priors. The threshold on the energy is (64/2) ln 2 / (1/2 − 1/4) = 22.18 / 0.25 = 88.7. Pure noise has average energy 64. Signal plus noise has 128.
Top: one recording of pure noise and one of signal plus noise. Bottom: the energy of 4,000 recordings of each. Drag the sliders and watch the two piles overlap.
Simulated Gaussian samples (illustrative), with σ1² = 1 and equal priors. The threshold is the lecture’s Bayes rule. The error is counted on the 8,000 simulated recordings.
More samples pull the piles apart, because energy adds up while its spread grows more slowly. A weaker signal pushes them together. At the overlap, no threshold is perfect, and that is the best that any classifier can do.
Chapter 4
Compute the dot product of two lifted points without lifting either one
Lifting a point from 2 numbers to 5 is cheap. Now picture a small grey image, 28 by 28 pixels, so 784 numbers. Add every product of two pixels, as the circle map added x1x2 and x1². The lifted point has 307,720 numbers. Do that for 60,000 images and your memory is gone before the SVM starts.
The lecture says it plainly: since Φ(x) is high dimensional, we may not compute it explicitly. Then it gives a way out. Look back at the dual SVM from Chapter 0. The data entered it in one place only: the dot product xiTxj. After a lift, that term becomes the dot product of two lifted points.
Give that dot product a name. The kernel function of a feature map Φ takes two points and returns the dot product of their lifted versions.
The lecture adds three facts. A kernel is a real number from two arguments. It is usually symmetric, so κ(x, x′) = κ(x′, x). And it can be read as a similarity: a big value says “these two are alike.” The headline fact is the next one. A kernel can sometimes be computed fast even if Φ(x) is infinite dimensional. Let us see one that works.
Take two points in the plane, x = (x1, x2) and y = (y1, y2). Define κ(x, y) = (xTy)²: take the ordinary dot product, then square it. Expand, one step at a time.
That is the lecture’s example, and its feature map has three entries. Now use real numbers. Let x = (1, 2) and y = (3, 1). Route one, the kernel: xTy = 3 + 2 = 5, and 5² = 25. Route two, the lift: Φ(x) = (1, 2√2, 4) and Φ(y) = (9, 3√2, 1). The products are 1×9 = 9, then (2√2)(3√2) = 12, then 4×1 = 4. The sum is 25. Both routes agree, but the first never built a lifted vector.
Drag the tip of either arrow, or use the sliders. Left: the points. Right: the three lifted features, and the product of each pair. Their sum is always the squared dot product.
Exact arithmetic on the numbers you set. The multiplication counts are for d = 2: the kernel takes 2 for the dot product and 1 to square it, while building both lifted vectors takes 4 + 4 and their dot product takes 3.
The same steps work for points with d numbers. Write the square of a sum as a double sum: (Σi xiyi)(Σj xjyj) = ΣiΣj (xixj)(yiyj). Each pair (i, j) gives one product of two lifted entries xixj and yiyj. Pairs with i ≠ j appear twice, once as (i, j) and once as (j, i). Merge each twin pair into one feature √2 xixj.
The lecture’s feature map has d squares x1², …, xd² and d(d−1)/2 cross terms, so d + d(d−1)/2 features in all. For d = 784 pixels that is 784 + 306,936 = 307,720 numbers. The kernel gets the same answer with 784 multiplications and one squaring.
d = 784: lifted dot product ≈ 3 × 307,720 = 923,160 multiplications vs kernel = 785 multiplications
Here is the symptom to watch for. Training stalls or runs out of memory on a kernel method, although the feature count looks harmless. The measurement is the kernel matrix, the table of κ for every pair of training points. It has n × n entries. For n = 60,000 images, that is 3.6 billion numbers, about 14 GB at 4 bytes each. This is our arithmetic, not the slide’s. The fix is to pick the smaller side of the trade. Lift explicitly when n is huge and the lifted dimension is small. Use the kernel when the lifted dimension is huge and n is moderate.
Chapter 5
Find the feature map of any power, and count how many features the kernel saves you from building
The squared kernel gave us a lift with three features. What about a cube? The lecture hands us this as an exercise: for κ(x, y) = (xTy)3, find the feature map Φ(x). Let us do it for points in the plane, and then for any power.
Expand (x1y1 + x2y2)3. Call a = x1y1 and b = x2y2. Then (a + b)3 = a3 + 3a2b + 3ab2 + b3. Put the letters back. The four terms are x13y13, then 3x12x2y12y2, then 3x1x22y1y22, then x23y23.
Each term is a product of an x-part and a y-part. The coefficient 3 splits as √3 × √3, one root per side, as the 2 did in Chapter 4. So the feature map has four entries.
Φ(x) = ( x13, √3 x12x2, √3 x1x22, x23 )
Check with x = (1, 2) and y = (3, 1). The kernel route gives (xTy)3 = 53 = 125. The lifted route gives Φ(x) = (1, 2√3, 4√3, 8) and Φ(y) = (27, 9√3, 3√3, 1). The four products are 27, then (2√3)(9√3) = 54, then (4√3)(3√3) = 36, then 8. They add to 125.
Pick two points, then slide the power p. Each row is one feature. Its bar is the product of the two lifted entries. The bars always add to (x·y)p.
Exact arithmetic. The feature for the monomial x₁p−jx₂j is the square root of C(p, j) times that monomial, which is the lecture’s multinomial map with d = 2.
The pattern is the multinomial theorem. A power of a sum expands into every way of choosing how many times each term is used. For d numbers and power p, the lecture writes it this way.
Split each coefficient into two square roots, one for each side, and the feature map is the list of √(coefficient) × monomial. The lecture’s summary is short: the features are all monomials of degree p.
The lecture also lists the inhomogeneous kernel (1 + xTy)p. The reason it works is a small trick. The number 1 + xTy is the dot product of (1, x) and (1, y), which are the points with a constant 1 glued on the front. So (1 + xTy)p is the homogeneous kernel in d + 1 dimensions. Its features are all monomials of degree up to p in the original d inputs, including the constant.
How many monomials of degree p exist in d inputs? Picture p identical balls dropped into d boxes, one box per input. A box’s count is its exponent. The number of ways is C(d + p − 1, p). For d = 2 that is p + 1, which matches the table: a square has 3 features and a cube has 4. For the inhomogeneous kernel the count is C(d + p, p).
Now watch the explosion. Take a 28 by 28 image, so d = 784. At p = 2 there are 307,720 features. At p = 3 there are 80,622,640, about 645 MB for one point stored at 8 bytes per number. At p = 4 there are 15.9 billion. The kernel costs the same 784 multiplications every time.
Pick a real signal size, then slide the power. The top bar is the number of features of one lifted point. The bottom bar is the work of the kernel. Both scales are logarithmic.
Counts use C(d + p − 1, p), exact up to rounding in the largest. Memory assumes 8 bytes per number (illustrative). The kernel work is d multiplications for the dot product plus about log₂p to raise it to the power p.
Chapter 6
Test a similarity function with its kernel matrix, and meet the Gaussian kernel with its endless features
You have two short recordings of a machine, and you invent a score for how alike they are. Maybe it is minus the distance between them. Maybe it is how well their waves line up. Can you drop your score into an SVM as its kernel? The answer is not “any score works.” The lecture asks the exact question: when does κ(x, y) = ⟨Φ(x), Φ(y)⟩ hold? When can we find a feature map at all?
Pick any n points x1, …, xn. Build the kernel matrix K, an n by n table where entry Kij = κ(xi, xj). The lecture’s answer is a definition. A kernel is a positive definite kernel if, for every choice of points, K is a symmetric positive semidefinite matrix.
What does that mean? A symmetric matrix K is positive semidefinite when vTKv ≥ 0 for every list v of n numbers. Think of vTKv as a squared length. A squared length is never negative. An equivalent test: all of K’s eigenvalues (the stretch factors of K along its special directions) are 0 or more.
Suppose κ(x, y) really equals ⟨Φ(x), Φ(y)⟩. Then for any list v, the number vTKv is a squared length. Here is the short proof.
So every genuine kernel passes the test. The converse also holds, though the slide only states the definition: a function that passes it for all point sets does have a feature map, possibly with infinitely many entries. This is the content of Mercer’s theorem, a standard result from outside the slides. The next lesson on RKHS builds that feature space step by step.
Test “minus the distance” on three numbers x = 0, 1, 2 with κ(x, y) = −|x − y|. The matrix is the table below. Its diagonal is all zeros, so its eigenvalues sum to 0, and they cannot all be zero because the off-diagonal entries are not. Some eigenvalue must be negative.
K = [ 0 −1 −2 ; −1 0 −1 ; −2 −1 0 ] → take v = (1, 1, 0): vTKv = 0 + 0 + 2(−1) = −2 < 0
That says ‖Φ(0) + Φ(1)‖2 = −2, which is impossible for any feature map. So “minus the distance” is not a kernel. The symptom of a fake kernel in practice is an SVM solver that diverges or returns nonsense. The measurement is the smallest eigenvalue of K. The fix is a valid kernel from the lecture’s list below, which fits the same idea of similarity.
The six small waves are three pairs: a slow sine, a fast sine and a ramp, each with and without noise. Pick a similarity. Left: its kernel matrix. Right: the eigenvalues of that matrix. Any negative bar means it is not a kernel.
Toy signals (illustrative): 32 samples each, scaled to length 1, noise from a fixed seed. Passing on six signals does not prove a function is a kernel for all signals. Failing on six proves it is not.
Slide 32 lists three kernels, and all pass the test. The homogeneous polynomial kernel is κ(x, y) = (xTy)p. The inhomogeneous polynomial kernel is (1 + xTy)p. Chapter 5 gave the features of both. The third is the one that matters most in practice, the Gaussian kernel, also called the radial basis function (RBF) kernel.
Take σ = 1. Two points at distance 1 get e−0.5 = 0.607. At distance 2 they get e−2 = 0.135. At distance 3 they get e−4.5 = 0.011. Nearby points count a lot, far points almost nothing. This matches the lecture’s reading of a kernel as a measure of similarity.
Where is its feature map? Expand the squared distance: ‖x − y‖2 = ‖x‖2 + ‖y‖2 − 2xTy. The exponential of a sum is a product, so the kernel splits into three factors.
κ(x, y) = e−‖x‖²/2σ² · e−‖y‖²/2σ² · exTy/σ², and exTy/σ² = Σk=0∞ (xTy)k / (σ2k k!)
The first two factors each depend on one point only, so they just scale the features. The sum is a polynomial kernel of every degree k, each with a positive weight. By Chapter 5 each degree brings its own monomial features. Together the Gaussian kernel has monomials of all degrees: infinitely many features. That is the lecture’s remark that a kernel can be computed efficiently even if Φ(x) is infinite dimensional. We cannot store such a Φ, but one exponential gives us its dot product.
Chapter 7
Swap every dot product in a linear method for a kernel, and train a curved SVM with the same solver
You now hold two facts. Chapter 0 showed that the dual SVM touches the data only through dot products. Chapters 4 to 6 showed that a kernel is a dot product in a lifted space, and that we can compute it without lifting. Put them together and you get the idea the whole lecture is named for.
The lecture states the kernel trick as three steps.
Nothing else changes. The solver, the constraints and the objective stay the same. You trained a linear method, but every dot product secretly became a dot product in a lifted space. The method now draws a flat cut up there, which is a curve down here.
To see the swap clearly, pack the dual into matrices. Stack the n data points as the rows of a matrix X with n rows and d columns. Then X XT is an n by n table whose entry (i, j) is xiTxj. Let Diag(y) be the n by n matrix with the labels on its diagonal. The double sum Σij αiαjyiyjxiTxj is then αT Diag(y) X XT Diag(y) α. The lecture writes the problem this way.
Look at the shapes. The solver sees only n by n tables. It never sees d, and it never sees the lifted dimension M. That is why a kernel SVM costs the same whether the lifted space has 5 features or infinitely many.
Take four XOR corners. The same-sign corners are class +1: x1 = (1, 1) and x2 = (−1, −1). The mixed-sign corners are class −1: x3 = (1, −1) and x4 = (−1, 1). No line separates them. Use the kernel κ(x, y) = (xTy)².
We never wrote w, and never needed to. Chapter 8 uses these four weights to classify a new point.
The solver is the same each time. Only the kernel changes. Start with the dot product, then try the others. Ringed points are support vectors. The small square is the kernel matrix K, sorted by class.
Toy data (illustrative): 40 noise-free points from a fixed seed. The solver is a small SMO routine on the dual of slide 38, with the box 0 ≤ αi ≤ C/n. The map shades how far each spot is from the boundary.
Start with the dot product on Rings. The symptom is a map cut by a single straight line, with many points wrong. The measurement is the accuracy in the read-out. The cure is one click: choose the Gaussian kernel, and the same solver draws a closed curve around the blob. The data did not change. Only the number that fills the kernel matrix changed.
Chapter 8
Predict a new point as a weighted vote of the support vectors, and tune the two knobs that decide if it generalizes
The SVM is trained. The solver handed back one weight αi for each training point, and a bias. A new reading arrives from the sensor. How do you label it? You never built the lifted weights w, so you cannot compute wTΦ(x). The last three slides of the lecture show that you do not need to.
Chapter 0 gave the rule w* = Σi αi* yixi. The best weights are a signed mix of the data points. The lecture’s first move is a small one: the rule holds in any space where the SVM runs. After lifting each point x to Φ(x), the SVM trained there has w* = Σi αi* yiΦ(xi). The vector w* lives in the lifted space, and we never write it down.
The lecture also writes the line as sign(xTw + b) = sign(x̃Tw̃). Here x̃ is x with a 1 glued on the end, and w̃ is w with b glued on. This only hides the bias inside the weights, so one symbol covers both. Our device keeps b as its own number, which is the usual bookkeeping when the constraint αTy = 0 is in force.
Take a new point x. Lift it to Φ(x), and take the dot product with w*. Then slide Φ(x) inside the sum, which is allowed because a dot product distributes over a sum.
Read it as a vote. Each training point i casts a vote of size αiyi. Its sign is the point’s label. The vote is scaled by κ(x, xi), how similar the new point is to point i. Add up all votes, add the bias, and take the sign. Points with αi = 0 cast no vote, so only the support vectors count.
Now the shapes. The new point x has d numbers. The kernel gives a list of n similarities, one per training point. The list α ∘ y has n numbers too. Their dot product is one number. To predict you need only the support vectors and their weights, not the whole training set.
Chapter 7 found αi = 0.125 and b = 0 for the four XOR corners, with κ(x, y) = (xTy)². Classify the new point x = (0.5, 2). Its kernel values are κ(x, x1) = (0.5 + 2)² = 6.25, then κ(x, x2) = (−0.5 − 2)² = 6.25, then κ(x, x3) = (0.5 − 2)² = 2.25, then κ(x, x4) = (−0.5 + 2)² = 2.25.
The votes are 0.125 × (+1) × 6.25 = +0.78 twice, and 0.125 × (−1) × 2.25 = −0.28 twice. The total is 1.56 − 0.56 = 1.00. The sign is positive, so the new point is a same-sign corner. And x1x2 = 0.5 × 2 = 1.0, the same number. The sum collapses to f(x) = x1x2 for every x.
Drag the teal probe, or use the sliders. Each line is one vote, and its thickness is the size of the vote. Warm lines vote for class +1, blue lines vote for −1.
Exact numbers from Chapter 7: κ = (x·y)², αi = 0.125 on all four corners, b = 0. The shading is the sum of the votes, which simplifies to x₁x₂.
A kernel machine has two main knobs. One is C, the price of slack. The other, for the Gaussian kernel, is the width σ. Both can make the machine memorize noise. The symptom is a machine that is perfect on its training points and weak on new ones. The measurement is the gap between training accuracy and accuracy on fresh points. The fix is to move the knob back.
Think of what σ does to the vote. A small σ makes κ(x, xi) near 0 except right on top of xi. Every training point becomes its own tiny island. The kernel matrix looks like the identity, every point is a support vector, and the boundary hugs each point. A large σ makes every kernel value near 1, the votes blur into one, and the boundary flattens toward a straight line. A good σ sits between, at the scale of the gap between the classes.
Noisy rings: the classes overlap a little. Filled dots are training points, small hollow dots are 300 fresh points the machine never saw. The curves show both accuracies for every width at your C.
Toy data (illustrative): 50 training and 300 fresh points from the same noisy rings, fixed seeds, radial noise 0.5. The width slider is logarithmic. Accuracy on fresh points is a sample, so small differences are noise.
Slide the width to its smallest value. Training accuracy climbs to 100% while fresh accuracy falls. That gap is the memorizing. Slide to the largest value and both fall together, which is underfitting. The best fresh accuracy lives in the middle. The same story holds for C: a huge C punishes every crossing and chases the noisy points.
Chapter 9
Keep the numbers, the checklist and the core code of the lecture on one page
The lecture has one move, told in six steps. A straight cut fails on curved data. A lift turns the curve into a flat cut. The SVM needs only dot products. A kernel gives the lifted dot product without the lift. A function is a kernel when its matrix is positive semidefinite. The trained machine classifies by a vote of support vectors weighted by kernel similarity.
| Idea | The rule or the number | Chapter |
|---|---|---|
| Soft margin SVM | min ½‖w‖² + C(1/n)Σsi, with yi(wTxi + b) ≥ 1 − si | 0 |
| Dual SVM | 0 ≤ αi ≤ C/n, Σαiyi = 0, w* = Σαi*yixi | 0 |
| Hard margin as geometry | the minimum distance between two convex hulls; γ* = 2/D. Example: D = 4 gives w* = (1, 0), b = −2 | 1 |
| Multi-class SVM | one score wkTx + bk per class, the true class leads by 1 − si | 2 |
| Binary shortcuts | one vs all trains K SVMs, one vs one trains K(K−1)/2. For K = 10: 10 and 45 | 2 |
| Circle as a lift | Φ(x) = (x1, x2, x1x2, x1², x2²), w = (−2c1, −2c2, 0, 1, 1) | 3 |
| Energy detector | threshold on Σxi². For N = 64, σ2² = 2: 88.7 | 3 |
| Kernel function | κ(x, x′) = ⟨Φ(x), Φ(x′)⟩. For (xTy)²: d + d(d−1)/2 features, 307,720 at d = 784 | 4 |
| Polynomial kernels | (xTy)p has C(d+p−1, p) features; (1 + xTy)p has C(d+p, p). At d = 784, p = 3: 80,622,640 | 5 |
| Valid kernel | Kij = κ(xi, xj) symmetric positive semidefinite for all points: vTKv ≥ 0, all eigenvalues ≥ 0 | 6 |
| Gaussian kernel | e−‖x−y‖²/2σ², infinitely many features. At σ = 1: 0.607, 0.135, 0.011 at distances 1, 2, 3 | 6 |
| Kernel trick | replace X XT with K. The solver sees n × n numbers, never d | 7 |
| Kernel machine | class = sign(Σαi* yi κ(x, xi)); only support vectors vote | 8 |
The whole lecture fits in about 40 lines. The page you played with runs the same routine in JavaScript. The solver gets only the n by n kernel matrix K, and prediction uses only the support vectors.
pythonimport numpy as np def rbf(A, B, sigma): # A: (n, d), B: (m, d) -> (n, m) table of kernel values d2 = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2 * A @ B.T return np.exp(-d2 / (2 * sigma**2)) def train_kernel_svm(X, y, sigma=1.0, C=100.0, tol=1e-3, max_passes=6, seed=0): # X: (n, d) points, y: (n,) labels in {-1, +1}. Solves the dual of slide 38 with SMO. n = len(y) K = rbf(X, X, sigma) # (n, n): the only thing the solver sees box = C / n # cap on every alpha alpha, b, passes = np.zeros(n), 0.0, 0 rng = np.random.default_rng(seed) f = lambda i: (alpha * y) @ K[:, i] + b # decision value of training point i while passes < max_passes: changed = 0 for i in range(n): Ei = f(i) - y[i] if (y[i] * Ei < -tol and alpha[i] < box) or (y[i] * Ei > tol and alpha[i] > 0): j = rng.choice([k for k in range(n) if k != i]) Ej, ai, aj = f(j) - y[j], alpha[i], alpha[j] if y[i] != y[j]: L, H = max(0, aj - ai), min(box, box + aj - ai) else: L, H = max(0, ai + aj - box), min(box, ai + aj) eta = 2 * K[i, j] - K[i, i] - K[j, j] if L >= H or eta >= 0: continue aj_new = np.clip(aj - y[j] * (Ei - Ej) / eta, L, H) if abs(aj_new - aj) < 1e-5: continue ai_new = ai + y[i] * y[j] * (aj - aj_new) b1 = b - Ei - y[i] * (ai_new - ai) * K[i, i] - y[j] * (aj_new - aj) * K[i, j] b2 = b - Ej - y[i] * (ai_new - ai) * K[i, j] - y[j] * (aj_new - aj) * K[j, j] alpha[i], alpha[j] = ai_new, aj_new b = b1 if 0 < ai_new < box else b2 if 0 < aj_new < box else (b1 + b2) / 2 changed += 1 passes = passes + 1 if changed == 0 else 0 return alpha, b def predict(Xnew, X, y, alpha, b, sigma): sv = alpha > 1e-7 # only the support vectors vote return np.sign(rbf(Xnew, X[sv], sigma) @ (alpha[sv] * y[sv]) + b) # (m, s) @ (s,) -> (m,)
Kernels let a linear method draw curves, at the price of an n by n table. The SVM is one such method. The next lesson uses kernels for regression and builds the feature space (the RKHS) that Mercer’s theorem promises. Earlier lessons behind this one are the support vector machine, convex duality, the Bayes classifier behind the energy detector, and Fisher’s linear discriminant, another linear rule. Least squares comes in the regression lesson.
Credit. This lesson follows Lecture 11 of Stanford EE269, Signal Processing for Machine Learning, taught by Mert Pilanci in Winter 2019. See the course site, the lecture slides and the slide index. The words, the devices and the toy data on this page are ours.
Now press Present or Teach and explain from memory three things. Why is a circle a flat cut after a lift? Why does the kernel give the lifted dot product for free? How do the support vectors vote on a new point? Then go back to the plane and cut the rings again.