Random Fourier Features With Pegasos SVM
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement an exact RBF kernel, a `RandomFourierFeatures` map whose inner products approximate it, and a bias-free linear SVM trained with Pegasos on the mapped features. Fill in every function in the interface below. All randomness must follow the pinned draw order exactly.
```python
import numpy as np
def rbf_kernel(X, Y, gamma): ...
class RandomFourierFeatures:
def __init__(self, n_components, gamma, seed): ...
def fit(self, X): ... # returns self
def transform(self, X): ...
def fit_transform(self, X): ... # fit, then transform
def primal_objective(w, Z, y, lam): ...
def pegasos_train(Z, y, lam, epochs, seed): ...
def predict_labels(Z, w): ...
```
The requirements:
- `rbf_kernel(X, Y, gamma)`: returns an (n, m) matrix with `exp(-gamma * ||x - y||²)` (clip negative squared distances to 0).
- `fit`: `rng = np.random.default_rng(seed)`, then `weights_ = rng.normal(0, sqrt(2*gamma), (d, D))`, then `offset_ = rng.uniform(0, 2π, D)`. `transform` returns `sqrt(2/D) * cos(X @ weights_ + offset_)`.
- `primal_objective(w, Z, y, lam)`: returns `0.5*lam*||w||² + mean(max(0, 1 - y*(Z@w)))` as a `float`.
- `pegasos_train`: start at `w = 0`, one `default_rng(seed)`, each epoch visit `rng.permutation(n)`. Per step: `t += 1`, `eta = 1/(lam*t)`, margin from the old `w`, shrink by `(1 - eta*lam)`, add `eta*y_i*z_i` if margin < 1. No projection.
- `predict_labels(Z, w)`: int array, `1` if score ≥ 0 else `-1`.
For example:
```python
Z = np.array([[1.0, 0.0], [0.0, 1.0]]); y = np.array([1, -1])
pegasos_train(Z, y, lam=1.0, epochs=1, seed=0) # -> [0.5, -0.5]
primal_objective([0.5, 0.25], [[1,0],[0,2],[1,1]], [1,-1,-1], 0.1) # -> 1.265625
predict_labels([[1,1],[2,-1],[-1,0]], [1,-1]) # -> [1, 1, -1]
```
```hint Pairwise distances
Expand `||x - y||²` into row norms and one matrix product, and expect tiny negative values from round-off.
```
```hint Normal draws
Check whether the second argument of `rng.normal` is a variance or a standard deviation.
```
```hint Step counter
Decide where `t` is initialized. The step size depends on how many updates have happened in total, across epochs.
```
### Constraints & Assumptions
- Labels are in {-1, +1}. Inputs may be lists or NumPy arrays.
- D = `n_components`.
- The SVM has no bias term, and Pegasos runs without the projection step.
### What a Strong Answer Covers
- A vectorized exact kernel that clips negative squared distances before exponentiating.
- A feature map with the correct spectral scale, the pinned draw order from a single generator, and the `sqrt(2/D)` scaling, plus why its inner products approximate the kernel.
- A Pegasos loop with a global step counter, the margin taken on the old `w`, a strict `< 1` test, and a predictor that sends a score of 0 to `+1`.
- The time and memory cost of the exact kernel compared with the feature map plus linear training.
### Follow-up Questions
- Why does `Z @ Z.T` approximate the RBF Gram matrix, and how fast does the error shrink?
- When would you choose random Fourier features over an exact kernel SVM or Nyström?
- How would you add a bias term or the optional projection step to Pegasos?
Overview: Implement an exact RBF kernel, a random Fourier feature map that approximates it, and a bias-free linear SVM trained with Pegasos on the mapped features. It tests kernel approximation through Bochner's theorem, seeded reproducible sampling, stochastic subgradient updates and the cost trade-offs against exact kernel methods.