RBF Kernel Matrix (Vectorised)

easy
Unit 6 · Kernels0/3 to milestone

Kernel methods (SVMs, Gaussian processes, kernel ridge) compare every pair of points with a kernel. The most common is the RBF (Gaussian) kernel:

K(x,z)=exp⁡(−γ∥x−z∥2)K(x, z) = \exp\left(-\gamma \|x - z\|^2\right)

Implement rbf_kernel(X, Z, gamma=1.0) returning the (len(X), len(Z)) matrix without Python loops. Use the identity ∥x−z∥2=∥x∥2+∥z∥2−2 x⋅z\|x - z\|^2 = \|x\|^2 + \|z\|^2 - 2\,x \cdot z, and clip tiny negative values (from floating-point error) to 0.

Then implement kernel_ridge_predict(X_train, y_train, X_test, gamma=1.0, lam=1e-3): solve (K+λI)α=y(K + \lambda I)\alpha = y on the training data and predict Ktest,train αK_{test,train}\,\alpha.

#kernels#numpy#vectorization2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
RBF Kernel Matrix (Vectorised) · TechGradify