Chunked Gram Matrix for Kernel SVM Inference
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement three functions for evaluating a trained binary kernel SVM on a large test set without materialising the full `n × n_sv` Gram matrix. `kernel_matrix` returns the full kernel matrix, `iter_gram_chunks` lazily yields row blocks of it, and `chunked_decision_function` returns `K(X, SV) @ dual_coef + intercept` computed block by block.
```python
def kernel_matrix(X, Y, kernel="rbf", gamma=1.0, degree=3, coef0=0.0): ...
def iter_gram_chunks(X, support_vectors, chunk_size, kernel="rbf",
gamma=1.0, degree=3, coef0=0.0): ...
def chunked_decision_function(X, support_vectors, dual_coef, intercept, chunk_size,
kernel="rbf", gamma=1.0, degree=3, coef0=0.0): ...
```
Requirements:
- Kernels follow scikit-learn conventions: `linear` is `x·y`, `poly` is `(gamma·x·y + coef0)^degree`, `rbf` is `exp(-gamma·‖x−y‖²)`, and `sigmoid` is `tanh(gamma·x·y + coef0)`. An unknown kernel name raises `ValueError`.
- `iter_gram_chunks` returns a generator yielding `(start, stop, block)` in row order, with `block` of shape `(stop - start, n_sv)`. The last chunk may be short.
- A `chunk_size` that is not a positive integer raises `ValueError` from both chunked functions.
- `chunked_decision_function` returns a 1-D float array of shape `(n,)` with the same values for every `chunk_size` (up to floating-point rounding).
- For an empty `X` (0 rows), the generator yields nothing and the decision values have shape `(0,)`.
- The inputs may be attributes of a fitted binary scikit-learn `SVC` (`support_vectors_`, `dual_coef_[0]`, `intercept_[0]`). With the same kernel parameters, the results must match `SVC.decision_function`.
Example:
```python
SV = [[1, 0], [0, 1]]; dual_coef = [1, -1]; intercept = 0.5
X = [[2, 3], [1, 1], [-1, 4]]
chunked_decision_function(X, SV, dual_coef, intercept, 2, kernel="linear")
# -> array([-0.5, 0.5, -4.5])
SV3 = np.ones((2, 3))
[(s, e) for s, e, _ in iter_gram_chunks(np.zeros((7, 3)), SV3, 3)]
# -> [(0, 3), (3, 6), (6, 7)]
```
With the linear kernel, the first test row `[2, 3]` has kernel values `[2, 3]` against the two support vectors, so its decision value is `2 - 3 + 0.5 = -0.5`. Seven rows in chunks of 3 give two full chunks and a final chunk of one row.
```hint RBF from one matrix product
Expanding `‖x − y‖²` into squared norms and a dot product lets the RBF block reuse `X @ SV.T`. Rounding can push some of those distances slightly below zero.
```
```hint When a generator runs its code
A function whose body contains `yield` runs none of its code until the first `next()`. Think about where the argument checks must live for a bad `chunk_size` to fail at call time.
```
### Constraints & Assumptions
- `X` has shape `(n, d)`, `support_vectors` has shape `(n_sv, d)`, and `dual_coef` has length `n_sv`.
- `n` is large enough that the full `n × n_sv` float matrix should never be built. Extra memory should stay proportional to `chunk_size × n_sv`.
- `gamma`, `degree` and `coef0` are numbers, with defaults `1.0`, `3` and `0.0`. Only binary models are in scope.
- NumPy is available.
### Clarifying Questions to Ask
- Should a float such as `2.0`, or a boolean, count as a valid `chunk_size`?
- Will `gamma` always arrive as a number, or can it be the string `"scale"` that `SVC` uses by default?
- Can `X` arrive as a list of lists or a single 1-D row, or is it always a 2-D NumPy array?
### What a Strong Answer Covers
- Kernel formulas that match scikit-learn, including an RBF computed from norms and one matrix product, with negative squared distances clipped to zero.
- Argument checks that run when `iter_gram_chunks` is called, while the block computation itself stays lazy.
- Chunk boundaries that cover every row exactly once, a short last chunk, and the empty-input case.
- Why row chunking gives the same decision values for any chunk size, with the time cost and the peak memory.
- How to check the output against `SVC.decision_function`, including passing the gamma the fitted model actually used.
### Follow-up Questions
- Given a memory budget in bytes, how would you pick `chunk_size`?
- How would you extend this to a multiclass one-vs-one `SVC`, whose `dual_coef_` has shape `(n_classes - 1, n_sv)`?
- How would you spread the chunks across worker processes or a GPU and still return the values in row order?
Overview: Implement kernel SVM inference on a large test set by computing the Gram matrix against the support vectors in row chunks. Tests kernel formulas, lazy generators with eager argument checks, memory-bounded NumPy code, and matching the decision function of a fitted scikit-learn SVC.