RBF Kernel PCA With Pre-Image Reconstruction
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement RBF kernel PCA with pre-image reconstruction using only NumPy and SciPy. Use it to show that RBF kernel PCA separates two concentric circles along its first component where linear PCA cannot, and to reconstruct inputs from component scores.
Implement these pieces:
- `rbf_kernel(X, Y, gamma)` returns the matrix of `exp(-gamma * ||x - y||^2)` with shape `(n_X, n_Y)`.
- `center_kernel(K)` returns `H K H` with `H = I - ones(n, n) / n`.
- `linear_pca_scores(X, n_components)` returns the centred projections of `X` onto its top principal axes, using the sample covariance (divide by `n - 1`) of mean-centred `X`.
- A class `KernelPCA(n_components=2, gamma=1.0, alpha=1.0)` with `fit(X)`, `fit_transform(X)`, `transform(X)` and `inverse_transform(Z)`.
- `best_threshold_accuracy(z, y)` returns the best accuracy a single cut on the scores `z` achieves for binary labels `y`.
- `select_gamma(X, y, gammas)` returns `(best_gamma, accs)`.
Requirements:
- In `linear_pca_scores` and `KernelPCA.fit`, sort eigenpairs by descending eigenvalue and flip each eigenvector's sign so that its largest-magnitude entry is positive. `KernelPCA` clips its eigenvalues at `0` and stores them in `eigenvalues_`.
- `fit_transform` returns `eigenvectors * sqrt(eigenvalues)`. `transform` centres new kernel rows with the training statistics and must match scikit-learn's `KernelPCA` with the RBF kernel.
- `inverse_transform(Z)` uses kernel ridge regression (RBF kernel, the same `gamma`, ridge `alpha`) fitted from the training scores to the training `X`, matching scikit-learn's `fit_inverse_transform=True`.
- `best_threshold_accuracy` only places cuts between distinct values of `z` (a cut below or above every value, which predicts one class for all points, also counts) and accepts either polarity.
- `select_gamma` scores each `gamma` with `best_threshold_accuracy` on the first component of a 1-component `KernelPCA` with the default `alpha`. `accs` is an ndarray in the order of `gammas`, and the first maximum wins ties.
Example:
```python
best_threshold_accuracy([1, 2, 3, 4], [0, 1, 0, 1]) # 0.75
best_threshold_accuracy([1, 1, 2, 2], [0, 1, 0, 1]) # 0.5 (no cut inside ties)
linear_pca_scores([[1, 1], [2, 2], [3, 3]], 1)[:, 0] # [-√2, 0, √2]
X, y = make_circles(400, factor=0.2, noise=0.1, random_state=123)
select_gamma(X, y, [0.001, 0.01, 15.0]) # best == 15.0, accs[2] >= 0.95
```
```hint Centring a new point's kernel row
Write the centred feature-space inner product between a new point and a training point, then expand it. Note which of the means come from the training kernel and which come from the new row.
```
```hint Scoring every cut at once
After sorting by score, the number of correct predictions for a cut at each position can be read off a running count of one label. Then decide which positions are legal cuts when scores repeat.
```
```hint The pre-image map
Treat reconstruction as a supervised regression with training scores as inputs and training rows of `X` as targets, and look at its closed-form dual solution.
```
### Constraints & Assumptions
- The implementation uses only NumPy and SciPy. scikit-learn's `make_circles` only generates the demo data, and scikit-learn's `KernelPCA` is the reference for checking results.
- `X` has shape `(n, d)` with `n ≥ 2`, `1 ≤ n_components ≤ n`, `gamma > 0` and `alpha > 0`.
- Labels `y` take the values 0 and 1.
### What a Strong Answer Covers
- A kernel, centring and eigendecomposition that follow the stated ordering, clipping and sign conventions, with training scores equal to the eigenvectors times the square roots of the eigenvalues.
- Correct centring of new kernel rows in `transform`, and safe handling of components whose eigenvalue is zero.
- The pre-image map as kernel ridge regression from training scores back to training inputs, fitted in the right direction with the same `gamma`.
- A single-cut accuracy in $O(n \log n)$ that respects tied scores and both polarities, plus a gamma search with a deterministic tie rule.
- Why the first RBF component separates the circles while linear PCA cannot, and what fitting costs.
### Follow-up Questions
- Why does the RBF pre-image need a learned regression instead of an exact inverse?
- What does `alpha` trade off in the pre-image regression, and how would you set it?
- How would you scale this to 100k samples?
- How would you pick `gamma` without labels?
Overview: Implement RBF kernel PCA with NumPy and SciPy, including projection of new points and a kernel ridge pre-image map, then pick gamma by how well the first component separates concentric circles. Tests kernel centring, matching scikit-learn's conventions and tie-aware threshold scoring.