Core ML2007intermediate12 min read
Random Features for Large-Scale Kernel Machines
السِّمات العشوائية لآلات النواة واسعة النِّطاق
Rahimi, A. · Recht, B. — NeurIPS
The problem
Kernel methods like SVMs learn nonlinear decision boundaries by implicitly mapping data into a high-dimensional (even infinite) via the . But the kernel matrix grows as N×N with size, making storage and computation prohibitive for datasets with hundreds of thousands of points. By 2007, training an SVM on half a million examples could take days.
The contribution
Instead of using the kernel trick implicitly, map data explicitly into a low-dimensional randomized feature space z(x) ∈ ℝᴰ so that z(x)ᵀz(y) ≈ k(x,y). Two such maps are proposed: (cosines sampled from the kernel's spectral ) for smooth interpolation kernels, and Random Binning Features (randomly shifted grids) for L1-based kernels. Both come with uniform guarantees. After the transform, any fast linear learner can be used, achieving accuracy comparable to exact kernel machines at a fraction of the cost.
The impact
Random Fourier Features became one of the most cited tools in scalable kernel methods and directly inspired the theoretical framework connecting kernels to neural networks — the Neural Tangent Kernel. The paper won the NeurIPS Test of Time Award in 2017 and opened the door to applying kernel-quality nonlinear learning at scales previously reserved for linear methods.
Imagine a detective who must compare every pair of fingerprints in a city of a million people — that's a trillion comparisons. Kernel machines face the same explosion: to learn complex patterns they must compare every training example against every other.
Random Features offer a shortcut stamp pad: instead of comparing raw fingerprints, each person presses their finger onto a special ink pad that captures just a few random strokes. Two stamps that look similar mean the originals were similar too — but now comparisons take microseconds instead of minutes.
The mathematical ink pad is a set of random cosine functions. The surprising result: a few hundred random strokes approximate the full fingerprint match almost perfectly.
The bottleneck: kernel machines don't scale
Support Machines and other kernel methods are powerful because they can learn any decision boundary, given enough data. The kernel trick lets you work in a potentially infinite-dimensional feature space without ever computing the coordinates — you only need the between every pair of points, packaged in a kernel matrix where .
The catch: that matrix has entries. Storing it for takes about 1 TB of RAM; computing it takes time. Decomposition solvers like SMO or SVMlight nibble at this matrix iteratively, but they still don't scale past a few hundred thousand points. Meanwhile, linear SVMs — which simply find a hyperplane — run in time, but they can only draw straight decision boundaries.
The question this paper asks: can we get kernel-quality nonlinearity at linear-method speed?
The core idea: approximate the kernel with random projections
The kernel trick says for some (often infinite-dimensional) lifting . Rahimi and Recht flip this: instead of working implicitly in the huge -space, build a short explicit map (with ) so that:
Once every training point is transformed to , you store an matrix instead of . Any linear learner — ridge , linear SVM, logistic regression — now solves the problem in time rather than .
The key insight is that for shift-invariant kernels — kernels that depend only on the difference , such as the Gaussian RBF — Bochner's theorem from harmonic analysis tells us exactly how to build .
Bochner's theorem and Random Fourier Features
A depends only on the displacement: . Bochner's theorem (1933) says that any such continuous positive-definite kernel is the Fourier transform of a non-negative measure. If is properly scaled so that , its Fourier transform is a proper distribution.
This means we can write the kernel as an expectation:
Since both and are real, the imaginary parts cancel, and we can replace the complex exponential with a cosine. Drawing from and uniformly from , the scalar function satisfies:
Each random cosine is an unbiased estimator of the kernel evaluation. Stack of them into a vector, normalize by , and the inner product becomes a low- approximation. Hoeffding's inequality guarantees exponentially fast convergence in .
Think of it as a frequency scanner: each random cosine projects the input onto a randomly chosen line in the data space, then wraps that projection onto a circle. Two points that land near each other on many circles must have been close in the original kernel sense — the same way two radio stations that produce similar readings on many randomly tuned receivers must be broadcasting similar signals.
Kernel ↔ spectral distribution: the recipe
Bochner's theorem tells us that every shift-invariant kernel has a spectral distribution . The choice of kernel determines where the random frequencies come from:
- Gaussian RBF : draw from a Gaussian .
- Laplacian : draw each from a Cauchy distribution .
- Cauchy kernel : draw from a Laplacian (double-exponential) .
The pattern is elegant: kernels and their spectral distributions are Fourier duals. A narrow kernel (local influence) has a wide spectral distribution, and vice versa — exactly the uncertainty principle from signal processing.
The second weapon: Random Binning Features
Not all kernels are smooth. The Laplacian kernel and other L1-based kernels have sharp corners. For these, Rahimi and Recht propose a second map: Random Binning Features.
The idea is beautifully spatial: partition the input space with a randomly shifted grid at a randomly chosen resolution. Each point is encoded as a binary indicator vector marking which bin it lands in. If two points fall in the same bin, their is 1; otherwise 0. The grid resolution is sampled from a distribution derived from the kernel, so the probability of co-binning equals the kernel value: .
Stack independent random binnings and average — you get a low-variance, unbiased estimator of the kernel. Unlike Fourier features, binning is piecewise constant — it explicitly preserves locality, which makes it superior for non-smooth decision boundaries like the Forest Cover dataset where tens of thousands of are needed.
Fourier vs Binning: when to use which
The two feature maps have complementary strengths:
Random Fourier Features produce smooth, continuous maps well-suited for interpolation tasks — problems where the decision boundary is smooth and the kernel is differentiable (e.g., Gaussian RBF). They excel on the CPU and Census regression benchmarks.
Random Binning Features produce piecewise-constant maps that explicitly preserve locality. They shine on memorization tasks — problems that need many support vectors and have rough, complex boundaries. The Forest Cover dataset is the dramatic example: binning achieves 2.2% error (matching exact SVM), while Fourier features struggle at 11.6%.
A practical rule of thumb: if the exact SVM needs few support vectors, Fourier features will work well. If it needs many, prefer binning. And since the two can be mixed freely, you can concatenate both types of features for the best of both worlds.
Convergence: how many features are enough?
A natural concern: how good is this approximation? The paper provides uniform convergence bounds — not just for a single pair , but for all pairs simultaneously over a compact set .
For Random Fourier Features: with high probability, the worst-case approximation error across all pairs is bounded by when the number of features is , where is the second moment of the spectral distribution (the trace of the kernel's Hessian at the origin).
The key takeaway: depends on the data dimension and the desired accuracy , not on the number of training points . Even for a million training examples, a few hundred random features can achieve sub-percent approximation error on standard kernels.
The algorithm in code
Simplified to show the idea — not the real implementation.
import numpy as np
def random_fourier_features(X, kernel='rbf', gamma=1.0, D=300):
"""
Map data X (N, d) to random Fourier features Z (N, D).
Inner products Z @ Z.T ≈ kernel matrix K.
kernel: 'rbf' (Gaussian) or 'laplacian'
gamma: kernel bandwidth parameter
D: number of random features
"""
N, d = X.shape
# Step 1: Draw random frequencies from kernel's spectral distribution
if kernel == 'rbf':
# Gaussian kernel → Gaussian spectral distribution
W = np.random.randn(d, D) * np.sqrt(2 * gamma)
elif kernel == 'laplacian':
# Laplacian kernel → Cauchy spectral distribution
W = np.random.standard_cauchy(size=(d, D)) * gamma
# Step 2: Draw random phase shifts
b = np.random.uniform(0, 2 * np.pi, size=D)
# Step 3: Compute the feature map
Z = np.sqrt(2 / D) * np.cos(X @ W + b) # (N, D)
return Z
# Usage: approximate Gaussian RBF kernel
X_train = np.random.randn(10000, 50) # 10K points, 50 dims
Z = random_fourier_features(X_train, D=500)
# Now use any linear method on Z:
# w = ridge_regression(Z, y, lambda=0.01)
# prediction = Z_test @ wExperimental results
The paper evaluates Random Features + ridge regression against Core Vector Machines (CVM) and exact SVMs on five large-scale benchmarks. The results are striking:
- On CPU (6,500 instances, regression): Fourier features achieve 3.6% error in 20 seconds — exact SVM takes 31 seconds for 11% error.
- On Adult (32K instances, classification): 14.9% error in 9 seconds vs. SVMlight's 15.1% in 7 minutes.
- On Forest Cover (522K instances, classification): Binning features achieve 2.2% error in 25 minutes vs. libSVM's 2.2% in 44 hours.
Two additional findings stand out. First, accuracy keeps improving as the training set grows — doubling data reduces error by up to 40%, a luxury that exact kernel machines cannot afford. Second, good performance appears from a remarkably modest number of features: to for most datasets.
The full pipeline
The complete Random Features workflow is refreshingly simple:
- Choose your kernel — Gaussian RBF, Laplacian, or any shift-invariant kernel.
- Compute the spectral distribution — the Fourier transform of the kernel.
- Sample D random frequencies from and D phases from .
- Transform every data point: .
- Train a linear on the transformed data (ridge regression, linear SVM, etc.).
- Predict: — requires only operations.
The random frequencies are drawn once and reused for all data points. The entire pipeline replaces kernel computation with feature computation plus linear solving.
Why it changed the field
2007
Random Features (this paper)
Rahimi and Recht show that random cosine projections can approximate shift-invariant kernels, making kernel-quality learning accessible at scale.
2008
Uniform approximation extension
Rahimi and Recht extend the theory to uniform approximation of functions with random bases, strengthening the theoretical foundation.
2009
Kitchen sinks
"Weighted Sums of Random Kitchen Sinks" extends the idea to learn the optimal weighting of random features, further bridging random features and neural networks.
2017
NeurIPS Test of Time Award
The paper receives the Test of Time Award. In his acceptance speech, Rahimi calls for more rigorous empirical methodology in machine learning — the "alchemy" speech.
2018
Neural Tangent Kernel
Jacot et al. show that infinitely wide neural networks are equivalent to kernel machines — the NTK theory builds directly on the random features framework.
The bridge to neural networks
Look at the Random Fourier Feature map again: . This is exactly a one-hidden-layer with random, frozen weights and cosine activation — only the output layer is learned.
This observation is more than a coincidence. The Neural Tangent Kernel (NTK) theory (Jacot et al., 2018) shows that training an infinitely wide neural network with is equivalent to kernel regression with a specific kernel determined by the network architecture. Random Features are the finite-width, explicit-map version of this correspondence.
The Random Features paper planted the seed: kernel approximation via random projections is not just a computational trick — it reveals a deep structural connection between kernel methods and neural networks that reshaped how we think about both.
CitationRahimi, Recht. Random Features for Large-Scale Kernel Machines. NeurIPS, 2007.
Terms in this paper
- Kernel Trickخدعة النواة
- Support Vector Machineآلة ناقلات الدعم (SVM)
- Radial Basis Functionدالة الأساس الشعاعي
- Inner Productالضرب الداخلي
- Feature Spaceفضاء السمات
- Random Fourier Featuresسِمات فورييه العشوائية
- Shift-Invariant Kernelالنواة المنزاحة ثابتة التحويل
- Gaussian Distributionالتوزيع الغاوسي
- Dot Productالضرب النقطي
- Gram Matrixمصفوفة غرام
- Dimensionality Reductionاختزال وتقليص الأبعاد الحسابية
- Convergenceالتقارب الحسابي