Lecture 7: Kernels
Stanford CS229 lecture 7 notes: Kernels.
- cs229
- machine-learning
- course-notes
On this page
The motivation#
Linear classifiers can only draw straight boundaries. What if the data isn't linearly separable?
One idea: map the inputs to a bigger feature space where it is separable. For example, from to . A linear boundary in the new space is a curved boundary in the original.
The issue is that if has a million (or infinitely many) dimensions, computing it is a nightmare.
The kernel trick#
We saw that the SVM only ever needs inner products . So, replace them with .
Define the kernel:
The trick: for many choices of , we can compute without ever computing .
Example: . Expanding it gives . This corresponds to a feature map with all pairwise products . Computing explicitly takes , but computing takes just .
The recipe:
- Write the algorithm in terms of inner products only.
- Pick a kernel .
- Replace every inner product with .
Common kernels#
- Linear: (just regular SVM)
- Polynomial: (features: all monomials up to degree )
- Gaussian (RBF):
The Gaussian kernel corresponds to an infinite dimensional feature space. We can still compute it in .
Intuition: a kernel measures similarity. is large if and are similar (close together), and small if not.
Which functions are valid kernels?#
A function is a valid kernel (it corresponds to some ) if and only if the matrix is symmetric positive semi-definite for any set of points. This is Mercer's theorem.
Kernels beyond SVMs#
The trick isn't SVM specific. Anything that can be written in terms of inner products can be kernelized: linear regression, logistic regression, perceptron, PCA, and so on.
Soft margin SVM (dealing with noise)#
What if the data isn't separable, even in feature space? Or one outlier would force a tiny margin?
We allow some points to violate the margin, but pay a price:
The are slack variables.
- Big : violations are expensive, so you get a narrow margin that fits training data tightly (risk of overfitting).
- Small : tolerant to violations, wider margin (smoother, risk of underfitting).
The dual looks almost identical to before, except the constraint becomes .
Solving it: SMO#
The dual is a big quadratic program with variables. Sequential Minimal Optimization (SMO) solves it by repeatedly picking just two 's, and optimizing them while keeping all others fixed. (Two, because the constraint means you can't change just one.) Each step has a closed form solution, so it's really fast.