Kernel SVM Decision Function and Predict
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `kernel_matrix`, `decision_function` and `predict` for a trained kernel SVM. The decision value for row `x` is `f(x) = Σᵢ alphas[i] * sv_labels[i] * K(sv_i, x) + intercept`. `predict` returns an int array of `+1`/`-1` labels.
```python
def kernel_matrix(A, B, kernel="rbf", gamma=1.0, degree=3, coef0=0.0): ...
def decision_function(X, support_vectors, sv_labels, alphas, intercept,
kernel="rbf", gamma=1.0, degree=3, coef0=0.0): ...
def predict(X, support_vectors, sv_labels, alphas, intercept,
kernel="rbf", gamma=1.0, degree=3, coef0=0.0): ...
```
Kernels:
- `"linear"`: `a·b`
- `"poly"`: `(gamma * a·b + coef0) ** degree`
- `"sigmoid"`: `tanh(gamma * a·b + coef0)`
- `"rbf"`: `exp(-gamma * ||a - b||²)`
- Any other name: raise `ValueError`.
Example:
```python
support_vectors = [[1, 0], [0, 1]]
sv_labels = [1, -1]
alphas = [0.5, 0.5]
intercept = 0.1
X = [[2, 0], [0, 2], [1, 1]]
decision_function(X, support_vectors, sv_labels, alphas, intercept, kernel="linear")
# -> [1.1, -0.9, 0.1]
predict(X, support_vectors, sv_labels, alphas, intercept, kernel="linear")
# -> [1, -1, 1]
```
```hint RBF without a loop
The squared distance can be written with dot products, which lets you reuse `A @ B.T`. Check the sign of very small results after the subtraction.
```
### Constraints & Assumptions
- `kernel_matrix(A, B)` returns shape `(len(A), len(B))` and must match scikit-learn's pairwise kernels.
- `sv_labels` are in `{-1, +1}` and `alphas` are non-negative, both aligned with `support_vectors`.
- A decision value of exactly `0` predicts `+1`.
- Results must match `SVC.decision_function` to `rtol=1e-6`.
### What a Strong Answer Covers
- A vectorized `kernel_matrix` with the four formulas, the `(len(A), len(B))` output shape, and a `ValueError` for unknown kernel names.
- An RBF squared distance that cannot go negative from floating-point round-off.
- `decision_function` as one product of `alphas * sv_labels` with the support-vector-by-query kernel matrix, plus the intercept, consistent with `SVC.decision_function`.
- `predict` returning an int array with a decision value of exactly 0 mapped to +1.
- Time and memory cost in terms of the number of support vectors, query rows and features.
### Follow-up Questions
- How do you avoid negative squared distances in the vectorized RBF kernel?
- Why does prediction cost scale with the number of support vectors?
Overview: Implement the kernel matrix, decision function and predict step of a trained kernel SVM from its support vectors, labels, dual coefficients and intercept, for linear, polynomial, sigmoid and RBF kernels. It tests the dual form of the SVM and numerically safe vectorized kernel code.