St · Statistics & Probability

Inverting a Gaussian (RBF) Kernel Matrix Without Numerical Trouble

Published By the 9to5Science editorial team

At a glance

  1. 1. Build the kernel

    Compute Kᵢⱼ = exp(−‖xᵢ − xⱼ‖² / 2σ²) for your points.

  2. 2. Add a ridge term

    Use K + λI with a small λ (noise variance or jitter) to tame conditioning.

  3. 3. Factor with Cholesky

    Compute K + λI = LLᵀ instead of forming the inverse explicitly.

  4. 4. Solve, don't invert

    Get α = (K + λI)⁻¹y with two triangular solves, then predict with k(x, X)α.

Try it: Matrix calculator

The Gaussian (RBF) kernel matrix for points x1,…,xnx_1, \dots, x_n is

Kij=exp⁡ ⁣(−∥xi−xj∥22σ2).K_{ij} = \exp\!\left(-\frac{\lVert x_i - x_j \rVert^2}{2\sigma^2}\right).

You need its inverse, or more precisely K−1yK^{-1}y, in kernel ridge regression, Gaussian process regression and RBF interpolation. There are two separate questions: is KK invertible in theory, and can you invert it reliably in practice?

In theory: always invertible for distinct points

The Gaussian kernel is strictly positive definite. For any distinct points x1,…,xnx_1, \dots, x_n and any non-zero vector cc,

c⊤Kc=∑i,jcicj k(xi,xj)>0.c^\top K c = \sum_{i,j} c_i c_j \, k(x_i, x_j) > 0.

This follows from Bochner’s theorem: the Gaussian’s Fourier transform is again a Gaussian, which is positive everywhere. So KK is symmetric positive definite, all its eigenvalues are positive, and K−1K^{-1} exists. Duplicate points produce identical rows and make KK singular.

In practice: often numerically singular

The smallest eigenvalue of KK can be astronomically small. That happens when:

  • points are close together compared with σ\sigma, so nearby rows are nearly identical, or
  • σ\sigma is large compared with the spread of the data, so every entry is close to 1.

A condition number of 101610^{16} or more is common, at which point double-precision arithmetic can’t distinguish KK from a singular matrix.

Two-point example

With two points at distance dd, write k=e−d2/(2σ2)k = e^{-d^2/(2\sigma^2)}:

K=(1kk1),K−1=11−k2(1−k−k1).K = \begin{pmatrix} 1 & k \\ k & 1 \end{pmatrix}, \qquad K^{-1} = \frac{1}{1 - k^2}\begin{pmatrix} 1 & -k \\ -k & 1 \end{pmatrix}.

For d=σ=1d = \sigma = 1: k=e−1/2≈0.6065k = e^{-1/2} \approx 0.6065 and 1−k2=1−e−1≈0.63211 - k^2 = 1 - e^{-1} \approx 0.6321, so

K−1≈(1.582−0.960−0.9601.582).K^{-1} \approx \begin{pmatrix} 1.582 & -0.960 \\ -0.960 & 1.582 \end{pmatrix}.

As d→0d \to 0 (or σ→∞\sigma \to \infty), k→1k \to 1 and the entries of K−1K^{-1} blow up like 1/(1−k2)1/(1-k^2). The eigenvalues are 1±k1 \pm k, so the condition number is (1+k)/(1−k)(1+k)/(1-k). With nn points the effect compounds quickly.

What to do instead

1. Add a ridge (nugget, jitter) term. Replace KK by K+λIK + \lambda I with λ>0\lambda > 0. Every eigenvalue moves up by λ\lambda, so the condition number is at most (λmax⁡+λ)/λ(\lambda_{\max} + \lambda)/\lambda.

  • In kernel ridge regression and GP regression, λ\lambda is part of the model: the regularisation strength or the noise variance σn2\sigma_n^2.
  • For pure interpolation, use a tiny jitter such as 10−810^{-8} to 10−610^{-6} times the mean of the diagonal, accepting a tiny loss of exactness.

2. Solve, don’t invert. You almost never need K−1K^{-1} itself. Factor once with Cholesky, K+λI=LL⊤K + \lambda I = LL^\top, then solve two triangular systems:

import numpy as np
from scipy.linalg import cho_factor, cho_solve
from scipy.spatial.distance import cdist

def rbf_kernel(X, Y, sigma):
    return np.exp(-cdist(X, Y, "sqeuclidean") / (2 * sigma**2))

K = rbf_kernel(X, X, sigma)
c, low = cho_factor(K + lam * np.eye(len(X)))  # fails loudly if not positive definite
alpha = cho_solve((c, low), y)                 # alpha = (K + lam*I)^{-1} y
y_pred = rbf_kernel(X_new, X, sigma) @ alpha

Cholesky costs about n3/3n^3/3 operations, roughly half the cost of an LU factorisation. It is backward stable for positive definite matrices, and its diagonal gives you log⁡det⁡K=2∑ilog⁡Lii\log\det K = 2\sum_i \log L_{ii} for free (needed for GP marginal likelihoods).

3. Choose σ\sigma sensibly. A common starting point is the median pairwise distance (the “median heuristic”). Then tune σ\sigma and λ\lambda by cross-validation or by maximising the marginal likelihood.

4. For large nn, use low-rank approximations (Nyström, random Fourier features) or iterative solvers (conjugate gradients), which avoid the O(n3)O(n^3) factorisation.

Common mistakes

  • Calling np.linalg.inv(K) and multiplying. It is slower and less accurate than a solve, and it hides ill-conditioning.
  • Treating a Cholesky failure as a bug. It is a signal that KK is numerically singular. Increase λ\lambda or check for duplicate points.
  • Using the same λ\lambda after rescaling the data. The appropriate λ\lambda depends on the scale of KK and yy.

References

  1. Rasmussen, C. E. & Williams, C. K. I. (2006). Gaussian Processes for Machine Learning, Section 2.2 and Appendix A.4. MIT Press.
  2. Wendland, H. (2005). Scattered Data Approximation, Chapter 6 and Chapter 12. Cambridge University Press.

Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.