Feature Maps & the Road to Kernels
Explicit feature expansions, their cost, and random features.
Every nonlinear model in this topic was linear in some features. The trouble is how many: the monomials of degree at most 3 in the 784 pixels of a small image already number about 81 million, and the Gaussian kernel's features are infinitely many. This lesson counts the cost of explicit expansions, shows that learning needs only inner products of features, and then goes back the other way: a few thousand random features approximate an infinite feature map with provable error, form a two-layer network with a frozen first layer, and trace a double-descent curve of their own.
What you’ll learn
- Count the monomials of an explicit polynomial expansion, , and weigh the computational and statistical cost of explicit features.
- Show that ridge regression on features needs only their inner products, and derive the feature maps behind the polynomial and Gaussian kernels.
- Derive random Fourier features from Bochner's theorem, and bound their error pointwise with Hoeffding's inequality and uniformly with Rahimi and Recht's theorem.
- Explain how many random features learning needs, the double descent of random-features regression, and what fixed random features cannot learn efficiently in high dimension.
Explicit feature maps and their cost
A feature map turns any linear method into a nonlinear one: fit least squares, ridge or logistic regression to instead of . Lifting data into more dimensions makes linear separation easy. Cover's function-counting theorem (1965) says that points in general position in can be split by a hyperplane through the origin in exactly
of the possible ways: all of them when , and exactly half when . With enough features, every labeling is linearly separable, the meaningful ones and the noise alike.
A monomial of degree at most is a vector of exponents with . Add a slack exponent to make the total exactly :
Placing identical units into bins is a stars-and-bars count:
For a image () and that is 80,931,145 features. Ridge regression on explicit features costs time, and the variance argument of Basis Functions & Generalized Linear Models charges before any regularization.
A model uses all monomials of degree at most 3 in inputs, the constant included. How many features is that?
Show the answer
1771 features
: 1 constant, 20 linear terms, quadratic and cubic monomials. With 100 inputs it would be 176,851. Polynomial expansions are affordable only for small or small .
Learning needs only inner products
Ridge regression on features has a dual form (Ridge Regression in Depth): with the feature matrix,
where and with . The features appear only through their inner products. If can be computed without building , the cost is memory and time whatever is, even infinite: the kernel trick. Which functions are inner products of some feature map, and why the solution always has this form, are the subjects of Reproducing Kernel Hilbert Spaces.
Expand the degree-2 polynomial kernel in dimensions:
It is the inner product of two explicit six-dimensional feature vectors, one feature per monomial of degree at most 2, which is :
In general, the multinomial theorem gives over : all monomials with fixed weights, computed in operations instead of .
The Gaussian (RBF) kernel factors into a product of normalizations and an exponential of , whose Taylor series is a sum of polynomial kernels of every degree: an infinite-dimensional feature map with weights decaying like .
Think first When is it cheaper to build the features explicitly than to use the kernel?
Explicit ridge costs about and the kernel form about . With few features and many examples (, say points and quadratic features of inputs, ), build the features. With many features and few examples, or infinitely many features as for the Gaussian kernel, use the kernel. When both and are large, neither works, which is the problem random features solve.
Random Fourier features
Draw and an independent phase . The product-to-sum identity splits the product of two cosines:
Averaging over the phase kills the second term, and averaging over turns the first into the kernel, by Bochner:
Average independent copies. The map below is a -dimensional explicit feature map whose inner products are unbiased estimates of the kernel:
For the Gaussian kernel the spectral distribution is itself Gaussian; for the Laplacian kernel it is a product of Cauchy distributions:
How good is the approximation? Each term lies in , so Hoeffding's inequality gives, for each fixed pair of points,
an error of order that does not depend on the dimension . The error is also small uniformly over a region. Rahimi and Recht's Claim 1 proves this for the paired map ( features from frequencies, the map of their Algorithm 1): for a compact set ,
For the random-phase map above, Sutherland and Schneider (2015) prove a bound of the same form with larger constants. Either way, of order features give uniform error with constant probability. Using the pair instead of a random phase removes the second term of the identity above, and for the Gaussian kernel this has lower variance even for the same total number of features.
Using the pointwise Hoeffding bound , how many random features guarantee error at most for a given pair of points with probability at least ?
Show the answer
16955 features
. Accurate kernel approximation is expensive because Monte Carlo error falls only like . Learning turns out to need far fewer features than approximating the kernel this accurately, as the next step shows.
import numpy as np
def rff(X, D, lengthscale, rng):
"""Random Fourier features for k(x, z) = exp(-||x - z||^2 / (2 l^2))."""
W = rng.normal(scale=1.0 / lengthscale, size=(X.shape[1], D)) # omega ~ N(0, I / l^2)
b = rng.uniform(0.0, 2 * np.pi, size=D) # random phases
return lambda A: np.sqrt(2.0 / D) * np.cos(A @ W + b)
rng = np.random.default_rng(0)
phi = rff(X_train, D=2000, lengthscale=1.0, rng=rng)
Z = phi(X_train) # n x D features instead of an n x n Gram matrix
lam = 0.1
w = np.linalg.solve(Z.T @ Z + lam * np.eye(Z.shape[1]), Z.T @ y_train) # O(n D^2 + D^3)
y_pred = phi(X_test) @ w # approximates kernel ridge regressionRidge regression on random Fourier features. scikit-learn's RBFSampler(gamma, n_components) builds the same features for the kernel , that is .
How many features does learning need?
Approximating the kernel to accuracy everywhere is more than learning requires. Rudi & Rosasco (2017) showed that ridge regression with about random features already attains the learning bound of exact kernel ridge regression in the basic setting; faster rates can need more features, unless the features are sampled from a problem-dependent distribution. The cost drops from for exact kernel ridge regression to , and the memory from to . Scaling Kernel Methods compares this with the Nyström method.
Random features are also a neural network: with features (the above, in the notation of the double-descent literature), is a two-layer network whose first layer is random and frozen, with here or a ReLU in other versions, and only the output weights trained. That makes it the simplest model in which to study overparameterization exactly.
What random features cannot do. Fixed features pay for not adapting to the target. Ghorbani, Mei, Misiakiewicz & Montanari (2021) studied inputs uniform on a high-dimensional sphere: with features between and (and unlimited data), a random-features model can effectively fit only polynomials of degree in the inputs; with unlimited features, kernel methods trained on samples in the same range fit at most degree- polynomials. Even a cubic function of a single direction, , then needs of order random features or samples. Networks that train their first layer can, in principle, align their features with the relevant direction, one theoretical account of why learned features beat fixed ones (Infinite Width: NTK & Mean-Field Limits).
Key takeaways
- There are monomials of degree at most in variables, about 81 million cubic features for a image; by Cover's count, enough features make any labeling separable.
- Ridge on features needs only inner products: . is an inner product of weighted monomials computed in , and the Gaussian kernel's feature map is infinite.
- Bochner: shift-invariant positive definite kernels are expectations ; gives unbiased random features with error , uniformly over compact sets with .
- Learning needs fewer features than approximation: about match kernel ridge regression's basic bound at cost .
- Random features are two-layer networks with a frozen first layer; their minimum-norm fit shows double descent with a peak at , and in high dimension they need about features to fit degree- polynomials.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
How many monomials of degree at most 3 are there in variables, the constant included?
- 5,151
- 176,851
- 1,000,000
- 161,700
Show the answer
B. 176,851
. The count grows like , so a cubic expansion of a few hundred inputs is already out of reach, while the cubic polynomial kernel costs per evaluation.
What does Bochner's theorem say about a continuous shift-invariant function ?
- It is a positive definite kernel if and only if is the Fourier transform of a nonnegative measure
- Every such function is a valid kernel
- It is a positive definite kernel if and only if everywhere
- Only the Gaussian kernel can be approximated by random features
Show the answer
A. It is a positive definite kernel if and only if is the Fourier transform of a nonnegative measure
Positive definiteness of a shift-invariant kernel is equivalent to a nonnegative spectrum. Normalized, that spectrum is a probability distribution, and sampling frequencies from it gives random Fourier features for any such kernel: Gaussian, Laplacian, Cauchy, Matérn.
Why do random Fourier features use with a uniformly random phase ?
- So that the features are nonnegative
- To center the data before the projection
- So that the cross term averages to zero, making the inner product an unbiased estimate of
- To make the features bounded
Show the answer
C. So that the cross term averages to zero, making the inner product an unbiased estimate of
. Only the first term depends on ; the uniform phase makes the second vanish on average. Using both and of removes it exactly.
With training examples, roughly how expensive is exact kernel ridge regression compared with ridge regression on random features?
- About the same: both scale with
- Random features are more expensive because is large
- Exact: about operations; random features: about
- Exact: about operations and stored entries; random features: about operations and entries
Show the answer
D. Exact: about operations and stored entries; random features: about operations and entries
Kernel ridge regression builds and solves an system. With features, forming costs and solving it , so the total is about : ten thousand times cheaper, and the feature matrix fits where an Gram matrix would not.
Further reading
- A. Rahimi & B. Recht, "Random features for large-scale kernel machines," NeurIPS (2007).
- D. J. Sutherland & J. Schneider, "On the error of random Fourier features," UAI (2015).
- T. M. Cover, "Geometrical and statistical properties of systems of linear inequalities with applications in pattern recognition," IEEE Transactions on Electronic Computers EC-14, 326–334 (1965).
- A. Rudi & L. Rosasco, "Generalization properties of learning with random features," NeurIPS (2017).
- S. Mei & A. Montanari, "The generalization error of random features regression: precise asymptotics and the double descent curve," Communications on Pure and Applied Mathematics 75(4), 667–766 (2022).
- B. Schölkopf & A. J. Smola, Learning with Kernels (MIT Press, 2002).