Vectorized Kernel Gram Matrices and Mercer Check

Quick Overview

Implement vectorized Gram matrices for linear, polynomial and RBF kernels in NumPy, plus a check that a matrix is a valid Mercer kernel matrix. It tests broadcasting, floating-point cancellation in squared distances, and testing for positive semidefiniteness with eigenvalues.

Vectorized Kernel Gram Matrices and Mercer Check

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `Kernel.gram(X, Y=None)` returning the `(n, m)` Gram matrix between rows of `X` and `Y` (`Y=None` means `Y = X`) with no Python loops. Also implement `is_mercer(K, tol=1e-8)` returning a Python `bool`. The constructor is `Kernel(kernel="rbf", gamma=1.0, degree=3, coef0=1.0)`. The implementation must meet these requirements: - `linear`: `X @ Y.T`. `poly`: `(gamma * X @ Y.T + coef0) ** degree`. `rbf`: `exp(-gamma * ||x - y||²)`. - For `rbf` with `Y=None`, the result must be exactly symmetric with unit diagonal (clip negative squared distances to 0). - Unknown kernel name (raised in `__init__`) or mismatched feature counts → `ValueError`. - `is_mercer` returns `False` if `K` is non-square, non-finite, or has `max|K - K.T| > tol`. - Otherwise `True` iff the smallest eigenvalue of `K` is `≥ -tol`. Example: ```python X = [[0, 0], [1, 1]]; Y = [[1, 0], [2, -1]] Kernel("linear").gram(X, Y) # [[0, 0], [1, 1]] Kernel("poly", gamma=2, degree=2, coef0=1).gram(X, Y) # [[1, 1], [9, 9]] Kernel("rbf", gamma=0.5).gram(X, Y) # exp(-0.5 * [[1, 5], [1, 5]]) is_mercer([[0, 1], [1, 0]]) # False (eigenvalue -1) is_mercer([[2, 1], [1, 2]]) # True ``` ```hint Distances from one product Expand the squared distance between two rows into pieces you can get from per-row quantities and a single matrix product, then combine them with broadcasting. ``` ```hint Exact in algebra, not in floating point Work out what the expanded formula returns when two rows are almost identical, and what lands on the diagonal when `Y` is `X`. Then decide which fixes make the diagonal exactly 1 and the matrix exactly symmetric. ``` ### Constraints & Assumptions - Outputs must match `sklearn.metrics.pairwise` kernels within `rtol=1e-7` when given the same `gamma`, `degree` and `coef0`. - `kernel` ∈ {`"linear"`, `"poly"`, `"rbf"`}. Inputs are 2-D float arrays. ### What a Strong Answer Covers - Building all three Gram matrices from one matrix product plus broadcasting, with no Python loops. - Why the expanded squared distance can come out negative, and the cleanup steps that make the RBF self-Gram exactly symmetric with a unit diagonal. - Input validation: unknown kernel names at construction, mismatched feature counts at call time. - The order of checks in `is_mercer`, the right eigenvalue routine for a symmetric matrix, and why the test needs a tolerance. - Time and memory cost of the Gram matrix and of the eigenvalue check. ### Follow-up Questions - How would you compute an RBF Gram matrix for ${10^6}$ samples without running out of memory? - Why can the expanded squared-distance formula produce small negative values? - Is the sigmoid kernel `tanh(gamma·x·y + coef0)` Mercer-valid? - The tolerance in `is_mercer` is absolute. How would you make the check behave consistently for a Gram matrix whose entries are around ${10^6}$?

Overview: Implement vectorized Gram matrices for linear, polynomial and RBF kernels in NumPy, plus a check that a matrix is a valid Mercer kernel matrix. It tests broadcasting, floating-point cancellation in squared distances, and testing for positive semidefiniteness with eigenvalues.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement Kernel.gram(X, Y=None) returning the (n, m) Gram matrix between rows of X and Y (Y=None means Y = X) with no Python loops. Also implement is_mercer(K, tol=1e-8) returning a Python bool. The constructor is Kernel(kernel="rbf", gamma=1.0, degree=3, coef0=1.0).

The implementation must meet these requirements:

  • linear : X @ Y.T . poly : (gamma * X @ Y.T + coef0) ** degree . rbf : exp(-gamma * ||x - y||²) .
  • For rbf with Y=None , the result must be exactly symmetric with unit diagonal (clip negative squared distances to 0).
  • Unknown kernel name (raised in __init__ ) or mismatched feature counts → ValueError .
  • is_mercer returns False if K is non-square, non-finite, or has max|K - K.T| > tol .
  • Otherwise True iff the smallest eigenvalue of K is ≥ -tol .

Example:

X = [[0, 0], [1, 1]]; Y = [[1, 0], [2, -1]]
Kernel("linear").gram(X, Y)                           # [[0, 0], [1, 1]]
Kernel("poly", gamma=2, degree=2, coef0=1).gram(X, Y) # [[1, 1], [9, 9]]
Kernel("rbf", gamma=0.5).gram(X, Y)                   # exp(-0.5 * [[1, 5], [1, 5]])
is_mercer([[0, 1], [1, 0]])   # False (eigenvalue -1)
is_mercer([[2, 1], [1, 2]])   # True

Constraints & Assumptions

  • Outputs must match sklearn.metrics.pairwise kernels within rtol=1e-7 when given the same gamma , degree and coef0 .
  • kernel ∈ { "linear" , "poly" , "rbf" }. Inputs are 2-D float arrays.

What a Strong Answer Covers Guidance

  • Building all three Gram matrices from one matrix product plus broadcasting, with no Python loops.
  • Why the expanded squared distance can come out negative, and the cleanup steps that make the RBF self-Gram exactly symmetric with a unit diagonal.
  • Input validation: unknown kernel names at construction, mismatched feature counts at call time.
  • The order of checks in is_mercer , the right eigenvalue routine for a symmetric matrix, and why the test needs a tolerance.
  • Time and memory cost of the Gram matrix and of the eigenvalue check.

Follow-up Questions Guidance

  • How would you compute an RBF Gram matrix for 106{10^6} samples without running out of memory?
  • Why can the expanded squared-distance formula produce small negative values?
  • Is the sigmoid kernel tanh(gamma·x·y + coef0) Mercer-valid?
  • The tolerance in is_mercer is absolute. How would you make the check behave consistently for a Gram matrix whose entries are around 106{10^6} ?