Custom Histogram Kernels for SVC: Intersection and Chi-Squared, Callable vs Precomputed
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement the histogram intersection and exponential chi-squared kernels, then train scikit-learn's `SVC` with them in two ways: as a callable kernel and via `kernel="precomputed"`. Both paths must return identical `(decision_values, predictions)` for the test rows.
Implement these functions:
- `histogram_intersection_kernel(X, Y=None)`: $K[i, j] = \sum_k \min(X_{ik}, Y_{jk})$, with `Y=None` meaning `Y = X`.
- `chi2_kernel(X, Y=None, gamma=1.0)`: $K[i, j] = \exp\left(-\gamma \sum_k \frac{(x_k - y_k)^2}{x_k + y_k}\right)$, where 0/0 terms count as 0. Negative features raise `ValueError`.
- `compute_gram(X, Y, kernel, gamma)` dispatches on `"intersection"` or `"chi2"` and returns shape `(len(X), len(Y))`. An unknown name or mismatched feature counts raise `ValueError`.
- `fit_predict_precomputed(X_train, y_train, X_test, kernel="intersection", C=1.0, gamma=1.0)` fits on the train×train Gram matrix and predicts with the test×train Gram matrix (rows are test samples, columns are training samples).
- `fit_predict_callable(X_train, y_train, X_test, kernel="intersection", C=1.0, gamma=1.0)` passes a kernel function to `SVC`.
Both fit functions use `SVC(C=C)` and return 1-D decision values of shape `(n_test,)` along with the predicted labels.
Example:
```python
X = [[1, 2, 0], [0, 1, 3]]
histogram_intersection_kernel(X, [[2, 0, 1]]) # [[1.], [1.]]
histogram_intersection_kernel(X) # [[3., 1.], [1., 4.]]
chi2_kernel(X, gamma=0.5) # off-diagonal = exp(-0.5 * (1 + 1/3 + 3))
```
```hint Vectorize the Gram matrix
Give `X` the shape `(n, 1, d)` and `Y` the shape `(1, m, d)`. One elementwise operation followed by a sum over the last axis gives the `(n, m)` matrix without Python loops.
```
```hint Empty bins
A bin that is zero in both histograms produces a 0/0 term. Make sure the division never runs on a zero denominator, or a NaN will reach the exponential.
```
### Constraints & Assumptions
- Features are histogram values. `chi2_kernel` must reject negative features with `ValueError`.
- Labels are binary, `-1` or `1`.
- Your `chi2_kernel` must match `sklearn.metrics.pairwise.chi2_kernel` numerically.
- Decision values are 1-D with shape `(n_test,)`.
### What a Strong Answer Covers
- Vectorized kernel functions that return shape `(len(X), len(Y))` and treat `Y=None` as `Y = X`.
- Correct handling of 0/0 bins and negative inputs in the chi-squared kernel, so the result matches scikit-learn.
- Validation of the kernel name and of the feature counts in `X` and `Y`.
- A precomputed path whose test matrix pairs test rows with training rows, and a reason the callable path produces the same numbers.
- The time and memory cost of building the Gram matrices.
### Follow-up Questions
- Why must the test Gram matrix be computed against training rows, not test rows?
- How do you verify a custom kernel is valid (Mercer) for `SVC`?
- When would you prefer a precomputed kernel over a callable one?
Overview: Implement the histogram intersection and exponential chi-squared kernels in NumPy, then train a scikit-learn SVC with them both as a callable kernel and as a precomputed Gram matrix. It tests vectorized kernel code, handling of empty bins, input validation, and the shape of the test kernel matrix an SVM expects.