Skip to main content

4. Kernel

Similarity between samples, bandwidth tuning, and the kernel eigenfunctions

The kernel block of the NLSA Python toolkit: Euclidean and cone distances, the variable-bandwidth function, automatic bandwidth tuning, diffusion-maps and bistochastic normalizations, eigensolvers, and the out-of-sample (Nyström) extension of the kernel eigenfunctions.

The kernel measures how similar two samples (delay windows) are. Its eigenfunctions are smooth functions on the set of samples, ordered from the slowest-varying to the most rapidly varying, and they are the basis in which the later blocks represent forecasts and the Koopman operator. The background is explained under Data-driven methods.

The block has five steps:

  1. a distance between samples, Euclidean or “cone”;
  2. optionally, a variable bandwidth function that adapts the kernel to the density of the samples;
  3. bandwidth tuning, which chooses the width of the kernel automatically;
  4. the kernel itself and its normalization;
  5. the eigendecomposition, whose eigenfunctions can then be evaluated at new samples by the Nyström extension.

In the example scripts the steps read:

shape_func = jnp.exp                                  # Gaussian kernel

# 2. variable bandwidth function, tuned on the distance between states (velocities ignored)
bw_tune_info = knl.tune_bandwidth(pars.train.bw_tune, impl_l2, shape_func, bw_sqdist, train_data)
bandwidth_func = knl.make_data_driven_bandwidth_function(impl_l2, shape_func, bw_sqdist,
                                                         bw_tune_info)
# 1. distance: cone (or dst.sqeuclidean), scaled by the bandwidth function
sqdist = dst.make_sqcone(pars.train.cone.zeta, pars.train.cone.threshold)
sqdist = knl.make_data_driven_scaled_sqdist(scl_r, sqdist, bandwidth_func)

# 3. bandwidth of the kernel
tune_info = knl.tune_bandwidth(pars.train.tune, impl_l2, shape_func, sqdist, train_data)

# 4-5. kernel, normalization and eigendecomposition
kernel = knl.make_data_driven_rbf_kernel(scl_r, shape_func, sqdist, tune_info.bandwidth)
kernel_eigen = knl.compute_eigen(pars.train.kernel, impl_l2, kernel, train_data,
                                 tune_info.bandwidth, pars.train.data.num_samples,
                                 jax_env.real_dtype)

Distance: Euclidean or cone

The Euclidean distance (dst.sqeuclidean) compares two delay windows entry by entry: \(d^2(x, x') = \lVert x - x' \rVert^2\), summed over all delays and predictor columns.

The cone distance (Giannakis 2015) (dst.make_sqcone(zeta, threshold)) also uses the velocities \(v\), \(v'\) of the two samples. With \(s = x - x'\),

\[ d_\zeta^2(x, x') = \sqrt{a\, a' + \delta} - \sqrt{\delta}, \]

\[ a = \lVert s\rVert^2 - \zeta\, \frac{(s\cdot v)^2}{\lVert v\rVert^2}, \]

\[ a' = \lVert s\rVert^2 - \zeta\, \frac{(s\cdot v')^2}{\lVert v'\rVert^2}, \]

where δ is threshold.

Displacements along the direction of motion count less than displacements across it, so samples on the same stretch of trajectory are treated as closer. This makes the kernel eigenfunctions better aligned with the dynamics, which helps both forecasting and Koopman analysis. The cone distance needs velocity_covariate=True in the data (switched on together with CONE_KERNEL = True in the examples).

ConePars (nlsa.jax.kernels, defined in src/nlsa/kernels.py)
Option Type or values Default Description
zeta float required Anisotropy ζ of the cone kernel, between 0 and 1. With ζ = 0 the cone distance reduces to the ordinary distance; as ζ approaches 1, displacements along the direction of motion count less. The examples use 0.99.
threshold float 1e-12 Small constant added inside the square root of the cone distance, so that automatic differentiation is stable when two points coincide.

Variable bandwidth function

With a fixed bandwidth, a kernel is too wide where samples are dense and too narrow where they are sparse, for example in rare extreme states. A variable bandwidth function \(\sigma(x)\) widens the kernel where the samples are sparse (Berry and Harlim 2016). The distance is divided by it:

\[ d^2_\sigma(x, x') = \frac{d^2(x, x')}{\sigma(x)\, \sigma(x')}. \]

The toolkit estimates \(\sigma\) from the data in a first pass. A Gaussian kernel on the distance between states (without velocities) is tuned as described below, normalized, and summed over the samples, which gives a quantity \(\rho(x)\) proportional to the local density of samples. Then \(\sigma(x) = \big(c / \rho(x)\big)^{1/m}\), where \(m\) is the estimated dimension of the data and \(c\) a normalization constant (stored as vol and kernel_vol in TuneInfo). The bandwidth function is used when TrainPars.bw_tune is set; all the examples use it.

Functions for the variable bandwidth (nlsa.jax.kernels)
Function What it does
knl.make_data_driven_bandwidth_function Builds \(\sigma(x)\) from the tuning result of the first pass (arguments impl_l2, shape_func, sqdist, tune_info).
knl.make_data_driven_scaled_sqdist Divides a distance by \(\sigma(x)\sigma(x')\) (arguments scl, sqdist, bandwidth_func).

Bandwidth tuning

The kernel is Gaussian in the (scaled) distance, \(k_\varepsilon(x, x') = \exp\!\big(-d^2(x, x')/\varepsilon^2\big)\), and its bandwidth \(\varepsilon\) is chosen automatically (Coifman et al. 2008; Berry and Harlim 2016). For trial bandwidths spaced evenly in \(\log_{10}\varepsilon\), the code computes the average kernel value over all pairs of samples,

\[ S(\varepsilon) = \frac{1}{N^2} \sum_{n, n'} k_\varepsilon(x_n, x_{n'}), \]

and its logarithmic slope

\[ D(\varepsilon) = \frac{d \log S(\varepsilon)}{d \log \varepsilon}. \]

If the samples lie on an m-dimensional set, \(S(\varepsilon)\) grows like \(\varepsilon^m\) for bandwidths that are small but not too small, so \(D(\varepsilon)\) estimates the dimension. Too small a bandwidth isolates each sample (\(D \to 0\)), too large a bandwidth makes all samples look alike (\(D \to 0\) again). The code takes the bandwidth \(\varepsilon^*\) where \(D\) is largest (or, if manifold_dim is given, where \(D\) is closest to it) and multiplies it by bandwidth_scl. The derivative is computed in closed form or by automatic differentiation (switch KERNEL_TUNING_GRAD_METHOD); the two give the same result.

TunePars (nlsa.jax.kernels, defined in src/nlsa/kernels.py)
Option Type or values Default Description
num_bandwidths int 128 Number of trial bandwidths, spaced evenly in log10.
log10_bandwidth_lims tuple[int, int] (-3, 3) Range of the trial bandwidths, as powers of ten: (-3, 3) scans 10⁻³ to 10³.
manifold_dim float or None None If None, choose the bandwidth at which the estimated dimension is largest. If a number, choose the bandwidth whose estimated dimension is closest to it.
bandwidth_scl float 1 Factor that multiplies the selected bandwidth. Values above 1 give a wider, smoother kernel.
bandwidth_batch_size int or None None Evaluate the trial bandwidths in batches of this size, to reduce memory.

The examples tune twice with the same procedure: once for the bandwidth function (TrainPars.bw_tune) and once for the kernel (TrainPars.tune). They use 128 trial bandwidths from \(10^{-3}\) to \(10^{3}\) and a factor bandwidth_scl of 1 (Euclidean distance, KAF script), 1.5 (Euclidean distance, Koopman script) or 2 (cone distance). knl.plot_kernel_tuning plots \(D(\varepsilon)\) (plots "bandwidth_tuning" and "kernel_tuning").

The result of knl.tune_bandwidth is a TuneInfo:

TuneInfo (nlsa.jax.kernels, defined in src/nlsa/jax/kernels/_kernels.py)
Field Type Description
log10_bandwidths array The trial bandwidths (log10).
est_dims array Estimated dimension at each trial bandwidth (the tuning curve).
opt_bandwidth array Bandwidth selected by the tuning criterion.
opt_dim array Estimated dimension at the selected bandwidth.
i_opt array Index of the selected bandwidth among the trial bandwidths.
bandwidth array Bandwidth actually used: opt_bandwidth × bandwidth_scl.
dim array Estimated dimension at the bandwidth actually used.
vol array Estimated volume of the data manifold (used to normalize the bandwidth function).
kernel_vol array Normalization constant from the kernel integral (used with vol).

Normalization

The Gaussian kernel is normalized before its eigenfunctions are computed. The choice is made with the script switch KERNEL_NORMALIZATION, which selects the parameter class.

Diffusion maps (DmKernelPars)

Diffusion-maps normalization (Coifman and Lafon 2006) turns the kernel into a Markov (averaging) operator. With \(q(x) = \frac{1}{N}\sum_n k(x, x_n)\),

\[ k_\alpha(x, x') = \frac{k(x, x')}{q(x)^\alpha\, q(x')^\alpha}, \]

\[ p(x, x') = \frac{k_\alpha(x, x')}{\frac{1}{N}\sum_n k_\alpha(x, x_n)} . \]

normalization="laplace" sets α = 1, which removes the effect of the sampling density, so that the eigenfunctions approximate those of the Laplacian of the data set; "fokkerplanck" sets α = ½, which all the examples use; None uses the kernel without normalization. The eigenvalue problem is solved for the symmetric matrix conjugate to \(p\), and its eigenvectors are converted to eigenfunctions of \(p\).

DmKernelPars (nlsa.jax.kernels, defined in src/nlsa/kernels.py)
Option Type or values Default Description
normalization "laplace" or "fokkerplanck" or None required Diffusion-maps normalization: "laplace" (α = 1, removes the influence of the sampling density), "fokkerplanck" (α = ½), or None (use the kernel as it is).
eigensolver "eigh" or "eigsh" required "eigh": builds the full N × N matrix and computes all its eigenpairs (memory grows as N²). "eigsh": iterative solver (SciPy) that computes only num_eigs eigenpairs without storing the matrix; use it for large N.
num_eigs int required Number of eigenpairs kept. They form the data-driven basis used by the later blocks.
batch_size int or None None Build the kernel matrix in batches of this many columns ("eigh" only), to reduce peak memory.

Bistochastic (BsKernelPars)

The bistochastic normalization (Coifman and Hirn 2013) builds an asymmetric kernel \(k_{\mathrm{bs}}(x, x') = k(x, x') / \big(d(x)\sqrt{q_{\mathrm{bs}}(x')}\big)\), with \(d\) and \(q_{\mathrm{bs}}\) row sums of \(k\) and of \(k\) divided by \(d\), so that \(p = k_{\mathrm{bs}}\,k_{\mathrm{bs}}^{*}\) is symmetric and doubly stochastic. Its eigenfunctions are the left singular vectors of \(k_{\mathrm{bs}}\), and its eigenvalues the squared singular values.

BsKernelPars (nlsa.jax.kernels, defined in src/nlsa/kernels.py)
Option Type or values Default Description
eigensolver "svd" or "svds" required "svd": dense singular-value decomposition. "svds": iterative truncated decomposition that computes only num_eigs singular vectors.
num_eigs int required Number of eigenpairs kept.
batch_size int or None None Batch size for matrix products, to reduce peak memory.

Eigendecomposition

knl.compute_eigen(kernel_pars, impl_l2, kernel, data, bandwidth, num_samples, dtype) computes the leading num_eigs eigenvalues \(\lambda_j\), in decreasing order, and eigenfunctions \(\varphi_j\). For a normalized kernel, \(\lambda_0 = 1\) and \(\varphi_0\) is constant. The solver matters for large data sets:

Eigensolvers
Solver Class How it works Memory When to use
"eigh" DmKernelPars Builds the full N × N matrix and computes all its eigenpairs on the CPU or GPU, then keeps num_eigs Several times N² numbers Up to a few tens of thousands of samples; the Lorenz 63 examples use it for 16,384 samples on a 40 GB GPU
"eigsh" DmKernelPars SciPy’s iterative Lanczos solver; JAX computes the matrix–vector products without storing the matrix A few times N × num_eigs Large N, or when only a few hundred to a few thousand eigenfunctions are needed
"svd" BsKernelPars Full singular value decomposition Several times N² As "eigh"
"svds" BsKernelPars Iterative truncated SVD (SciPy) A few times N × num_eigs As "eigsh"

The result is a KernelEigen:

KernelEigen (nlsa.jax.kernels, defined in src/nlsa/jax/kernels/_kernels.py)
Field Type Description
evals array Kernel eigenvalues λ, in decreasing order. With a normalized kernel the first is 1 and belongs to the constant eigenfunction.
evecs array Kernel eigenvectors φ: the eigenfunctions evaluated on the training samples (one row per eigenfunction).
dual_evecs array Dual (left) eigenvectors, used to compute expansion coefficients by inner products.
weights array Sample weights that make the eigenvectors orthonormal (for diffusion maps, the invariant measure of the Markov kernel).
bandwidth array Bandwidth used, stored for converting λ to Laplace eigenvalues.

The eigenfunctions come with their duals \(\varphi'_j\), such that \(\langle \varphi'_i, \varphi_j\rangle = \delta_{ij}\) with the inner product \(\langle f, g\rangle = \frac{1}{N}\sum_n f(x_n)\, g(x_n)\). The coefficient of a function \(f\) along \(\varphi_j\) is therefore \(\langle \varphi'_j, f\rangle\), which is how the forecasting and Koopman blocks expand functions in this basis.

kernel_eigen.tabulate() prints the eigenvalues; knl.plot_laplacian_spectrum plots the corresponding Laplace eigenvalues (plot "laplacian_spec"), which measure the roughness of each eigenfunction. They are computed by knl.to_laplace_eigenvalues(evals, bandwidth, method):

Conversion of kernel eigenvalues to Laplace eigenvalues
method Laplace eigenvalue \(\eta_j\)
"log" \(-4 \ln \lambda_j / \varepsilon^2\) (used by the Koopman block)
"lin" \(4 (1 - \lambda_j) / \varepsilon^2\)
"inv" \((1/\lambda_j - 1) / (1/\lambda_1 - 1)\), so that \(\eta_1 = 1\)

Out-of-sample extension

Kernel eigenfunctions are computed on the training samples, but they are functions that can be evaluated anywhere, by the Nyström extension:

\[ \varphi_j(x) = \frac{1}{\lambda_j} \, \frac{1}{N}\sum_{n} p(x, x_n)\, \varphi_j(x_n). \]

This is how forecasts are made from test samples, and how the Koopman block differentiates the eigenfunctions along the trajectory. The extension is part of the eigenbasis object built by knl.make_data_driven_eigenbasis(kernel_pars, impl_l2, kernel, which_eigs), which provides the eigenfunctions (fn), their values on the samples (vec), expansion coefficients (anal) and the reconstruction of a function from coefficients (fn_synth).

Functions

Functions of the kernel block (nlsa.jax.kernels as knl, nlsa.jax.distance as dst)
Function Purpose
dst.sqeuclidean
dst.make_sqcone
Squared Euclidean and cone distances; the cone distance is made with make_sqcone(zeta, threshold)
knl.tune_bandwidth Bandwidth tuning; returns TuneInfo. Passing neg_grad_shape_func=jnp.exp selects the closed-form derivative
knl.make_data_driven_bandwidth_function
knl.make_data_driven_scaled_sqdist
Variable bandwidth
knl.make_data_driven_rbf_kernel The kernel: shape_func applied to \(-d^2(x, x')/\varepsilon^2\)
knl.compute_eigen Normalization and eigendecomposition; returns KernelEigen
knl.make_data_driven_eigenbasis Eigenbasis with the Nyström extension (arguments kernel_pars, impl_l2, kernel, which_eigs)
knl.to_laplace_eigenvalues Laplace eigenvalues (arguments evals, bandwidth, method)
knl.plot_kernel_tuning
knl.plot_laplacian_spectrum
clim.make_kernel_evecs_plotter
clim.plot_bandwidth_function
Plots

Script switches for this block

Kernel switches in the ENSO scripts
Switch Type or values Value in the scripts Description
CONE_KERNEL bool KAF: True
Koopman: False
Use the cone kernel. It also switches on the velocity covariates in the experiment settings.
KERNEL_TUNING_GRAD_METHOD "explicit" or "automatic" KAF: "automatic"
Koopman: "explicit"
How the tuning curve is differentiated: "explicit" (a closed-form gradient for the exponential shape function) or "automatic" (JAX automatic differentiation).
KERNEL_NORMALIZATION "diffusion_maps" or "bistochastic" "diffusion_maps" "diffusion_maps" (uses DmKernelPars) or "bistochastic" (uses BsKernelPars).

How to choose the number of eigenfunctions, the bandwidth factor and the other settings is discussed in Choosing hyperparameters.

References

Berry, T., and J. Harlim. 2016. “Variable Bandwidth Diffusion Kernels.” Applied and Computational Harmonic Analysis 40 (1): 68–96. https://doi.org/10.1016/j.acha.2015.01.001.
Coifman, R. R., and M. J. Hirn. 2013. “Bi-Stochastic Kernels via Asymmetric Affinity Functions.” Applied and Computational Harmonic Analysis 35 (1): 177–80. https://doi.org/10.1016/j.acha.2013.01.001.
Coifman, R. R., and S. Lafon. 2006. “Diffusion Maps.” Applied and Computational Harmonic Analysis 21 (1): 5–30. https://doi.org/10.1016/j.acha.2006.04.006.
Coifman, R. R., Y. Shkolnisky, F. J. Sigworth, and A. Singer. 2008. “Graph Laplacian Tomography from Unknown Random Projections.” IEEE Transactions on Image Processing 17 (10): 1891–99. https://doi.org/10.1109/TIP.2008.2002305.
Giannakis, D. 2015. “Dynamics-Adapted Cone Kernels.” SIAM Journal on Applied Dynamical Systems 14 (2): 556–608. https://doi.org/10.1137/140954544.