SOCR ≫ TCIU Website ≫ TCIU GitHub ≫

Hilbert space embeddings of distributions, or kernel mean embeddings, map distributions into reproducing kernel Hilbert spaces (RKHS’s) where kernel methods are extended to probability measures. Kernel mean embedding methods have many applications in probabilistic modeling of complex phenomena, statistical inference based on high-dimensional data, and artificial intelligence. In this TCIU Reproducing Kernel Hilbert Spaces and Temporal Distribution Dynamics (TDD) Section we explore the relations between RKHS, kime-phase distributions, and temporal distribution dynamics.

Specifically, in this section we explore repeated spatiotemporal sampling, where \(\forall\ n\), we observe \(K\) (longitudinal or spatiotemporal) sample means \(\{\bar{X}_{n1},\bar{X}_{n2},\cdots, \bar{X}_{nK}\}\). In this case, \(\forall\ 1\leq k_o\leq K\) each IID sample \(\{X_{1k_o},X_{2k_o},\cdots ,X_{nk_o}\}\sim F_X\) (across the kime-phase space) allows us to compute the \(k_o^{th}\) sample mean \(\bar{X}_{nk_o}\).

Computing \(\bar{X}_{nk_o}\) from the \(k_o^{th}\) sample \(\{X_{1k_o},\cdots ,X_{nk_o}\}\) is identical to directly sampling \(\bar{X}_{nk_o}\) from the sampling distribution of the mean \(F_{\bar{X}_n}\). Kime-phase sampling, at a fixed spatiotemporal index \(k=k_o\) samples from the kime-phase distribution, \(\{X_{1k_o},\cdots , X_{nk_o}\}\). The complementary spatiotemporal sampling reflects the varying \(k\) index, where the kime-phase variability is annihilated by using a kime-phase aggregator, in this case sample-averages, to generate a sample \(\{\bar{X}_{n1},\cdots , \bar{X}_{nK} \}\).

Prior to data acquisition, \(\bar{X}_{nk_o}\) is a random variable, once the observed data values are plugged in, it’s a constant. Hence, the sample mean random variable (a sum of \(n\) \(\sim F_X\) variables) \(\bar{X}_{nk_o}\) based on \(\{X_{1k_o},\cdots , X_{nk_o}\}\sim F_X\), and the (single!) random variable \(Y\sim F_{\bar{X}_{nk_o}}\) represent exactly the same random variable.

There is a kime-phase connection to quantum fluctuations, statistical inference, and artificial intelligence. This is related to random drawing of a second-order tensor \(X_{n\times K}\) (a random matrix) representing \(K\) (spatiotemporal or longitudinal) samples of \(n\) IID observations \(\{X_{1k_o},\cdots , X_{nk_o}\}_{k_o}\sim F_X\). Computing the \(K\) corresponding means \(\bar{X}_{nk_o}=\frac{1}{n}\sum_{i=1}^n{X_{ik_o}}\) is equivalent to randomly drawing \(K\) samples (a random vector) directly from the sampling distribution of the mean \(F_{\bar{X}_{nk_o}}\).

1 Kernels

Kernel functions are positive definite operators that arise as a way to perform inner products \(\langle \cdot, \cdot \rangle\) in high-dimensional feature spaces \(\mathcal{F}\) given observed data points \(x, y \in \mathcal{X}\). These kernel functions guarantee the existence of mappings from the native state spaces of observed data \(\mathcal{X}\) to dot product feature spaces \(\mathcal{F}\), \(\phi: \mathcal{X} \to \mathcal{F}\), such that the kernel inner product \(\kappa(x, y) = \langle \phi(x), \phi(y)\rangle\) can be computed without the need for explicit calculation of the enigmatic feature mapping \(\phi\).

Kernel methods are used by machine learning (ML) algorithms and artificial intelligence (AI) techniques to replace the native space inner products \(\langle x, y\rangle_{\mathcal{X}}\) with other, possibly nonlinear, distance or similarity measures computed in the higher dimensional feature space representing the range (output) of nonlinear transformations \(\phi: \mathcal{X} \to \mathcal{F}\), which map the native space (domain, \(\mathcal{X}\)) into a higher-dimensional feature space \(\mathcal{F}\). Each feature map \(\phi\) transforms the native space inner product distance calculations \(\langle x, y\rangle_{\mathcal{X}}: \mathcal{X}\times \mathcal{X}\to \mathbb{R}\) with kernel function calculations \(\kappa(x, y) = \langle \phi(x), \phi(y)\rangle_{\mathcal{F}}: \mathcal{F}\times \mathcal{F}\to \mathbb{R}\) on the feature space \(\mathcal{F}\). As most of the time the elements of the inner product are clearly identifiable, we can skip the space-designating subscript and write \(\langle \cdot, \cdot\rangle\) for \(\langle \cdot, \cdot\rangle_{\mathcal{X}}\) and \(\langle \cdot, \cdot\rangle_{\mathcal{F}}\).

In other words, we interpret \(\kappa(x, y)\) as a nonlinear similarity measure between the sets \(x\) and \(y\). Many ML/AI algorithms that depend only on the inner product (distances) between state space data points, i.e., on \(\langle x, y\rangle\). Hence, this kernel-trick allows us to obtain nonlinear extensions of such algorithms by simply substituting the kernel distance measures \(\kappa(x, y) = \langle \phi(x), \phi(y)\rangle_{\mathcal{F}}\) for the corresponding native space distances, \(\langle x, y\rangle\) without altering the algorithm learning, training, and validation steps. For instance, consider a polynomial feature map \(\phi:\mathbb{R}^2\to \mathbb{R}^3\)

\[\phi(x) = (x^2_1,\ x^2_2,\ \sqrt{2}\ x_1 x_2),\ \forall\ x=(x_1,x_2)\in\mathbb{R}^2\ ,\]

which transforms the calculations of the native-space inner product to another feature-space inner product as follows

\[\underbrace{\langle x, y\rangle_{\mathcal{X}} \equiv x_1 y_1 + x_2 y_2}_{\text{native space similarity, }\mathcal{X}} \longrightarrow \underbrace{\kappa(x, y) = \langle \phi(x), \phi(y)\rangle_{\mathcal{F}}\equiv x_1^2 y_1^2 + x_2^2 y_2^2 + 2x_1 x_2 y_1 y_2}_{\text{(corresponding) RKHS space similarity, }\mathcal{F}}\equiv \langle x, y\rangle_{\mathcal{X}}^2 \ .\]

In this case, the kernel trick suggests that the \(\phi\)-transformed similarity measure, \(\langle \phi(x), \phi(y)\rangle_{\mathcal{F}}\), is just the square of the inner product in the native space \(\mathcal{X}\),i.e., \(\langle x, y\rangle ^2\).

The more general \(d\)-degree polynomial kernel relies on a map \(\phi(x):\mathcal{X}\equiv\mathbb{R}^n \to \mathcal{F}\), where \(\phi(x)\) represent all possible \(d^{th}\) degree ordered products of the observable data \(x,y\in\mathbb{R}^n\)

\[\kappa(x, y) = \langle \phi(x), \phi(y)\rangle_{\mathcal{F}} = \langle x, y\rangle_{\mathcal{X}} ^d\ .\]

In DSPA Chapter 6 we show several types of kernels commonly used in support vector machines (SVM) and other ML methods. Here are some kernel examples.

  • The linear kernel represents the simplest kernel, which is just the dot product of the features.

\[\kappa(x, y)=\langle x,\ y \rangle\ .\]

  • The polynomial kernel of degree d transform the data by adding a simple non-linear transformation of the data.

\[\kappa(x, y) = \langle x, y\rangle ^d=(x\cdot y+1)^d \ .\]

  • The sigmoid kernel is used in neural networks utilizing the sigmoid activation function with scale \(s\) and offset \(o\) parameters.

\[\kappa(x, y)=\tanh(s\ \langle x, y\rangle + o).\]

  • The Gaussian radial basis function (RBF) kernel.

\[\kappa(x, y)=e^{- \left (\frac{\lVert x-y\rVert^2}{2\sigma^2}\right )} .\]

  • The hyperbolic tangent kernel, for some given scale \(s\) and offset \(o\) parameters is the same as the sigmoid kernel, since the \(\tanh(\cdot)\) function is a scaled and shifted version of the sigmoid function \(\sigma(x)=\frac{1}{1+e^{-x}}\equiv 1-\sigma(-x)\in [0,1)\) and the hyperbolic tangent

\[\tanh(x)\equiv\frac{e^x-e^{-x}}{e^x+e^{-x}} = \frac{1-e^{-2x}}{1+e^{-2x}}=\frac{2-(1+e^{-2x})}{1+e^{-2x}} = \frac{2}{1+e^{-2x}}-1 = 2\sigma(2x)-1\in(-1,1)\]

\[\kappa(x, y)=\tanh(s\langle x, y\rangle + o)\ .\]

  • The Laplacian kernel with width parameter \(\sigma\)

\[\kappa(x, y) = e^{-\left (\frac{\lVert x-y\rVert}{\sigma}\right )} \ . \]

  • The Matern kernel provides an interpolation between Laplacian kernel and Gaussian kernel parameterized by the smoothness parameter \(\nu\)

\[\kappa_{\nu} (x,y)=\sigma^2 \frac{2^{1-\nu}}{\Gamma(\nu)}\left (\sqrt{2\nu}\frac{\|x-y\|}{\rho}\right )^{\nu} K_{\nu}\left (\sqrt{2\nu}\frac{\|x-y\|}{\rho} \right )\ ,\]

where \(\sigma^2\) is the variance parameter and \(\rho\) controls the kernel scale (width).

When \(\nu=\frac{1}{2}\), \[\kappa_{\frac{1}{2}}(x,y)=\sigma^2\sqrt{\frac{2}{\pi}\frac{\|x-y\|}{\rho}} \underbrace{K_{\frac{1}{2}}\left (\frac{\|x-y\|}{\rho}\right )}_{\left (2\frac{\|x-y\|}{\rho\pi}\right )^{-1/2} \exp\left (-\frac{\|x-y\|}{\rho}\right )}= \sigma^2 \exp\left (-\frac{\|x-y\|}{\rho}\right )\ .\]

As \(\nu\to\infty\), the Matern kernel transforms into the Gaussian kernel,

\[\lim_{\nu\to\infty}\kappa_{\nu}(x,y)=\sigma^2\exp \left (-\frac{\|x-y\|^2}{\rho}\right )\]

where the Laplace method may be used to approximate the asymptotic convergence of the kernel as\(\nu\to\infty\)

\[K_{\nu}(x)\to \sqrt{\frac{\pi}{2\nu}}e^{-\nu}(2\nu/x)^{\nu},\ \Gamma(\nu)\to \sqrt{2\pi}\nu^{\nu-1/2}e^{-\nu}\ ,\]

\[K_{\nu}(\sqrt{v}x)\to \sqrt{\frac{\pi}{2\nu}}e^{-\nu}\left (2\frac{\sqrt{\nu}}{x}\right )^{\nu}\exp(x^2)\ ,\]

and \(\sqrt{\nu x^2+\nu^2}\sim \nu+\frac{x^2}{2},\ \nu\to \infty\).

This unique interpolation of the Matern kernel between Gaussian and Laplacian kernels is effectively a 1-parameter kernel homotopy, just like the t-distribution is a 1-parameter (probability distribution) homotopy between Cauchy distribution and Gaussian distribution.

Also, Matern kernels generate classical Sobolev spaces, indicating that reproducing-kernel Hilbert spaces (RKHS) associated with the Green function can be embedded into or are equivalent to a generalized Sobolev space.

Here are the Matern kernels for a couple of \(\nu\in \left \{\frac{3}{2}, \frac{5}{2} \right \}\) parameters:

\[\kappa_{\frac{3}{2}}(x,y)=\sigma^2\left (1+\frac{\sqrt{3}\|x-y\|}{\rho}\right ) \exp\left (-\frac{\sqrt{3}\|x-y\|}{\rho}\right)\]

\[\kappa_{\frac{5}{2}}(x,y)=\sigma^2\left (1+\frac{\sqrt{5}\|x-y\|}{\rho}+\frac{5(x-y)^2}{3\rho^2}\right ) \exp \left (-\frac{\sqrt{3}\|x-y\|}{\rho}\right ).\]

Below are plots of the shapes of several Matern kernels.

library(GPBayes)
besselk_nu <- function(nu) {
  return(function(x) {
    return(GPBayes::BesselK(nu, x))
  })
}
maternkernel <- function(sigma,nu,rho,x){
  scaled_x = sqrt(2*nu)*x/rho
  return (sapply(scaled_x,besselk_nu(nu))*scaled_x**nu*sigma**2*2**(1-nu)/gamma(nu))
}

library(plotly)
p <- plot_ly(type="scatter", mode="lines")
x_values = seq(from = -5, to = 5, by = 0.01)
p <- p %>%add_trace(x=~x_values, y=~maternkernel(1,1/8,1,abs(x_values)), 
                    name = ~paste("nu=", 1/4), mode="lines")
p <- p %>%add_trace( x = ~x_values, y = ~maternkernel(1,1/2,1,abs(x_values)), 
                     name = ~paste("nu=", 1/2), mode="lines")
p <- p %>%add_trace( x = ~x_values, y = ~maternkernel(1,1,1,abs(x_values)), 
                     name = ~paste("nu=", 1), mode="lines")
p <- p %>%add_trace( x = ~x_values, y = ~maternkernel(1,5,1,abs(x_values)),
                     name = ~paste("nu=", 5), mode="lines")
p <- p %>%add_trace(x = ~x_values, y = ~maternkernel(1,50,1,abs(x_values)), 
                    name = ~paste("nu=", 50), mode="lines")
p = layout(p, title = "Matern kernels for different parameter values",
          xaxis = list(title="X values"), yaxis = list(title="Y values"))
p
  • The Bessel kernel uses the modified Bessel functions, \(Bessel_{\nu +1}^{n}(u)\), or the Bessel function of first kind is defined by the contour integral, \(J_{n}(z)\),

\[J_{n}(z)=\frac{1}{2\pi i} \oint e^{\frac{z}{2}(t-\frac{1}{t})} t^{-n-1}dt\ ,\] \[Bessel_{\nu +1}^{n}(u) = \frac{1}{(4 \pi)^{(\nu +1)/2}\Gamma ((\nu +1)/2)} \int_0^{\infty} {\frac{e^{-\left (\frac{\pi \vert u \vert^2}{s}+\frac{s}{4 \pi}\right )}} {s^{1 + \frac{n - (\nu + 1)}{2}}}\,\mathrm{d}s}\ , \forall\ u\in\mathbb{R}^n\setminus\{0\} ,\]

\[\kappa(x, y) = -Bessel_{\nu +1}^{n} \left ( \sigma ||x-y||^2 \right ) \equiv \frac{J_{\nu +1}(\sigma ||x-y||^2)}{||x-y||^{-n(\nu + 1)}}\ .\]

  • The Spline kernel is defined as a special case of a piecewise cubic polynomial

\[\kappa(x, y) = \prod_{i=1}^n\left (1+ x_i y_i (1+\min(x_i,y_i))- \frac{(x_i+y_i)\min^2(x_i,y_i)}{2} +\frac{\min^3(x_i,y_i)}{3}\right )\ .\]

The R implementations of all kernlab kernels are available here.

In general, for each pair of observations \(x,y\in\mathcal{X}\), evaluating the kernel \(\kappa(x, y)\) involves two computationally expensive steps:

  • First, compute the feature maps \(\phi(x)\) and \(\phi(y)\).
  • Second, compute the feature space inner-product \(\mathcal{F}\), \(\kappa(x, y) = \langle \phi(x), \phi(y)\rangle _{\mathcal{F}}\).

Note that there is a simplified alternative way to compute directly the kernel inner product (second step) \(\langle \phi(x), \phi(y)\rangle _{\mathcal{F}}\) without explicitly computing the feature maps (step one). This requires an explicit relation, like the (quadratic and \(d^{th}\) degree) polynomial kernel relations we saw earlier, e.g., \(\kappa(x, y) = \langle x, y\rangle_{\mathcal{F}}^2\) or \(\kappa(x, y) = \langle x, y\rangle_{\mathcal{F}}^d\).

It turns out that for each positive definite kernel \(\kappa(x, y)\), there always exists a feature map \(\phi: \mathcal{X} \to \mathcal{F}\) so \(\kappa(x, y) = \langle \phi(x), \phi(y)\rangle _{\mathcal{F}}\). And since feature space inner product \(\langle \cdot, \cdot\rangle _{\mathcal{F}}\) is positive definite, it implies that \(\kappa(x, y) = \langle \phi(x), \phi(y)\rangle _{\mathcal{F}}\) is positive definite \(\forall\ \phi:\mathcal{X} \to \mathcal{F}\).

Definition: A reproducing kernel Hilbert space (RKHS) \(\mathcal{H}\) is defined as the space of feature functions \(\phi:\mathcal{X} \to \mathcal{F}\), corresponding to reproducing positive semi-definite and symmetric kernels \(\kappa\)

\[\kappa: \mathcal{X}\times \mathcal{X} \longrightarrow \mathbb{C}\ \ ({\text{or }} \mathbb{R})\ ,\]

\[\text{Reproducing}: f(x)=\langle \kappa(x,\cdot),f(\cdot)\rangle_{\mathcal{H}} \forall f\in\mathcal{H}\] \[\text{Positive semi-definiteness}:\sum_{i,j=1}^n {c_i^*\ c_j\ \kappa(x_i,x_j)}\geq 0,\ \forall\ n\in\mathbb{N},\ \forall\ \{x_i\}_i \in \mathcal{X}, \forall\ \{c_i\}_i \in \mathbb{C} \ . \]

Two important RKHS properties are:

  • \(\forall\ x \in \mathcal{X}\), the function \(\kappa(x,\cdot ): \mathcal{X} \to \mathbb{C}\) defined by \(\kappa(x,\cdot ): y\in \mathcal{X} \to \kappa(x,y) \in \mathbb{C}\) is an element of the RKHS \(\mathcal{H}\). The feature space \(\mathcal{F}\) is the RKHS \(\mathcal{H}\) associated with this kernel \(\kappa\) and the canonical feature map \(\kappa\left (\underbrace{\_}_{arg},\cdot \right ): \mathcal{X} \to \mathcal{H} \subseteq \mathcal{V}_{\mathcal{X}\to \mathbb{C}}\), \(x\mapsto \kappa(x,\cdot )\), where \(\mathcal{V}_{\mathcal{X}\to \mathbb{C}}\) is the vector space of functions \(\mathcal{X}\to \mathbb{C}\).
  • \(\forall\ f \in \mathcal{H}\) and \(\forall\ x \in \mathcal{X}\), the kernel \(\kappa(\cdot ,\cdot )\) represents point evaluation, \(f (x) = \langle f, \kappa (x, \cdot )\rangle_{\mathcal{H}}\). If \(\exists\ x_o\in \mathcal{X}\) such that \(f(x_o) = \langle f, \kappa (x_o, \cdot )\rangle_{\mathcal{H}}\), the reproducing property is guaranteed

\[\langle \kappa (x, \cdot ),\ \kappa (x_o, \cdot )\rangle_{\mathcal{H}}\equiv \kappa (x, x_o)\ .\]

Thus, we do not need to explicate the feature map \(\phi_x = \kappa(x, \cdot )\) as it can be derived directly from the kernel \(\kappa\) by the above reproducing relation.

Note: Below we will demonstrate several examples of using kernel/RKHS approaches for regularized linear modeling of data (Ridge and LASSO regression) and show the notion of LASSO shrinkage on features (identification of salient variables associated with predicting a specific outcome of interest) and shrinkage on cases (selection of observation instances, i.e., participants, that play the most influential role in deriving model-based predictions of the outcome).

2 Examples of Regression Modeling using Reproducing Kernel Hilbert Spaces

Let’s look at some hands-on parameter estimation examples of RKHS including a regularized linear model fitting (Ridge and LASSO) and simulation cases.

2.1 Ridge Regression Example

Let’s consider the DSPA amyotrophic lateral sclerosis (ALS) case-study, which consists of \(2,223\) observations and \(131\) numeric variables. We select ALSFRS slope as our outcome variable, as it captures the patients’ clinical decline over a year. In this simple demonstration, we’ll only use \(5\) covariates \(\{x_i\}_{i=1}^5\), \(x_1=\)Age_mean, \(x_2=\)Albumin_max, \(x_3=\)Albumin_median, \(x_4=\)Albumin_min, \(x_5=\)Albumin_range, to predict the outcome \(Y=ALSFRS\_slope\). This ALS case-study is intentionally chosen as it represents a tough modeling, prediction, and classification AI challenge.

2.1.1 Data ingestion and preprocessing

We start by importing the raw data and identifying the design matrix \(X\) and the clinical outcome of interest, \(Y=ALSFRS\_slope\).

library(tidyverse)
# devtools::install_github("kupietz/kableExtra")
# See: https://stackoverflow.com/questions/76118194/error-when-loading-kableextra-in-markdown-file-after-updating-to-r-4-3-0
library(kableExtra)

ALS.train <- read.csv("https://umich.instructure.com/files/1789624/download?download_frd=1")
# summary(ALS.train); colnames(ALS.train)

y = ALS.train$ALSFRS_slope
X = as.matrix(ALS.train[ , 2:6])
X = apply(X, 2, scales::rescale, to = c(0, 1))

2.1.2 Matrix inversion function

To avoid potential computationally singular results, we define a new function inverse(), which will be used in place of the more commonly used base::solve().

inverse <- function(X, eps = 1e-9) {
  eig.X = eigen(X, symmetric = TRUE)
  P = eig.X[[2]] 
  lambda = eig.X[[1]]
  # to avoid singularities, identify the indices of all eigenvalues > epsilon
  ind = lambda > eps
  
  lambda[ind]  = 1/lambda[ind] 
  lambda[!ind] = 0
  
  P %*% diag(lambda) %*% t(P)
}

2.1.3 Reproducing Kernel

Define a bivariate reproducing linear kernel operator, rk(), \(\kappa(s,t) = rk(s,t)=s'\cdot t=\langle s, t \rangle\), in this case a simple inner-product.

rk <- function(s, t) {
  init_len = length(s)
  rk = 0
  for (i in 1:init_len) { rk = s[i]*t[i] + rk }
  return(rk)
} 

2.1.4 Gram matrix

For a set of vectors \(S = \{x_1,x_2,\cdots, x_n\}\) representing an observed sample of \(n\) multivariable data points \(\{x_i\}\), the Gram matrix is defined as the kernel-matrix

\[G_{n\times n}=\left (G_{ij} \equiv \langle \phi(x_i), \phi(x_j) \rangle \equiv \underbrace{\kappa (x_i, x_j )}_{kernel} \right )\ ,\]

where the kernel function \(\kappa(\cdot,\cdot)\) computes the inner products in the feature-space based on the feature map \(\phi(\cdot)\). Note that \(G_{ij}\equiv G_{ji},\ \forall\ 1\leq i,j\leq n\) and the symmetric Gram matrix, \(G'\equiv G\), contains all the information needed to compute the pairwise distances within the dataset. Indeed, the Gram matrix is a lossy representation of the complete original dataset (set of features). Despite the fact that the Gram matrix loses some information about the original dataset it has some desirable properties:

  • The Gram matrix of inner products is invariant w.r.t. rotations about the origin.
  • The Gram representation loses information about the alignment between the points and the axes, since the Gram matrix is rotationally invariant. Yet, any rotation of the coordinate system will leave the Gram matrix of inner products unchanged.

The power of the Gram matrix comes from its preservation of all pairwise distances between the observed data points, i.e., the vectors \(\{x_i\}_{i=1}^n\), and their \(\phi\)-transformed counterparts, \(\{\phi(x_i)\}_{i=1}^n\).

In our examples, the gram(X,RK) function will represent an alternative of the standard (square transposed cross-product matrix) \(tcrossprod(X)=tcrossprod(X,Y\equiv X)= X\times Y'\) function, which takes the (transposed) cross-product of a matrix with its transpose, i.e., \(X\times X'\). The gram() operator allows us to generalize tcrossprod(), so that it can be used with alternative kernels (RK) provided as arguments to gram().

gram <- function(X, rkfunc = rk) { # compute the `crossprod` using the specified RK
  apply(X, 1, function(Row) 
    apply(X, 1, function(tRow) rkfunc(Row, tRow)) # specifies the Reproducing Kernel
  )  
}

2.1.5 Generalized Cross-Validation (GCV) Measure

Given a linear model \(Y=X\beta +\varepsilon\) and a value of the regularization hyperparameter, \(\lambda\), the GCV statistic is

\[V(λ)=\frac{\frac{1}{n}||(I-A(\lambda))y||^2}{ \left (\frac{1}{n}\cdot Tr(I-A(\lambda))\right )^2}\ ,\]

where \(n\) is the number of observations, \(H(\lambda)=X(X^TX)^{-1} X^T\) is the hat matrix, and \(A(\lambda)=X(X^TX+n\lambda I)^{-1} X^T\) is a smoothed hat matrix, and fitted values of the linear least-squares regression model are \(\hat{y}=X\beta = X(X^TX)^{-1} X^T = Hy\).

Recall the two alternative forms of the generalized cross-validation (GCV) score defined in terms of the root sum-square (RSS) error or the deviance

\[GCV_{RSS} = \frac{RSS/n}{(1 -Tr(H(\lambda))/n)^2}\] \[GCV_{Deviance} = -2\frac{LogLikelihood/n}{(1 -Tr(H(\lambda))/n)^2} \ .\]

Here we will define the ridge(X, y, lambda) function, which computes the Gram matrix \(G_{n\times n}\), formulates a non-singular design matrix \(Q\) (with an intercept first column), computes the inverse of the cross-product matrix, \(M\), estimates the ridge parameters, and calculates the GCV measure.

The R package glmnet already provides an efficient method for fitting elastic net regularized linear models. We will define a de novo ridge() method that demonstrates RKHS approaches using the Gram matrix to fit a Ridge regularized linear model for estimating the parameters (effect sizes).

Recall that if \(X\) is the design matrix of observed values of predicting-covariates and \(Y\) is the observed outcome vector, the linear model predictions (fitted-values) are expressed as

\[\underbrace{\hat{Y}}_{fitted\ values}=X\hat{\beta}=X(X'X)^{-1}X'Y\ , \]

where the effect-size estimates \(\hat{\beta}=\{\beta_i\}_i\) for all covariates \(\{x_i\}_i\) correspond to the specific objective (cost/loss) function used in the optimization process

  • Least squares loss (classical unregularized linear model): \(\hat{\beta}^{OLS} = (X' X)^{-1} X' Y\).
  • Ridge loss: \(\hat{\beta}_j^{(Ridge)} = (1 + N \lambda )^{-1}\hat{\beta}^{OLS}_j\).
  • LASSO loss: \(\hat{\beta}_j^{(LASSO)} = S_{N \lambda}(\hat{\beta}^\text{OLS}_j ) = \hat{\beta}^\text{OLS}_j \max \left( 0, 1 - \frac{ N \lambda }{ |\hat{\beta}^{OLS}_j| } \right)\).

We implement the kernelized ridge regression as follows (Some additional details See appendix 5.3):

2.1.6 Ridge regression

ridge <- function(X, y, lambda,kernel=rk) {
  K = gram(X,kernel)                            #assumed X to be n*d where observations stacked on the rows, GramMatrix (nxn) XTX (already phi^Tphi)
  rows = dim(X)[1]
  n = length(y)                                   
  #Q = cbind(1, GramMatrix) no need for intercept as the kernel already captures this
  #S = rbind(0, cbind(0, GramMatrix))
  
  M = K + lambda*diag(dim(K)[1])                     # (singularity protection)K+lambda I)^{-1}
  M_inv = inverse(M)                              # invert M
  
  omega_tilde = M_inv %*% y
  f_hat = K %*% omega_tilde 
  
  A = K %*% M_inv  # Hat matrix maps response to fitted values
  tr_A = sum(diag(A))                             # trace of hat matrix
  
  rss  = crossprod(y - f_hat)                     # residual sum of squares
  gcv  = n*rss / (n - tr_A)^2                     # compute GCV score
  
  return(list(f_hat = f_hat, omega_tilde = omega_tilde, gcv = gcv, rss=rss))
}

2.1.7 Optimal Hyper-Parameter Estimation

Using the ALS dataset, we will implement a direct search for the GCV optimal ridge regularization parameter \(\lambda\) to predict the clinical outcome ALSFRS_slope. We will use the R package furrr and request multiple cores (\(workers = 8\)) in the call to furrr::future_map(). Using multicore processing will significantly expedite this massive search calculation.

We use LASSO (alpha = 1) regularization on the same ALS test case with a Laplacian reproducing kernel operator, rk()

\[\kappa(s,t) = rk(s,t)= e^{-\left (\frac{\lVert s - t\rVert}{\sigma}\right )}\ .\]

rk_Laplace <- function(s, t, sigma=1) {
  if (sigma <= 0) sigma=1  # avoid singularities
  init_len = length(s)
  rk_Lap = 0
  for (i in 1:init_len) { rk_Lap = (s[i] - t[i])^2 + rk_Lap }
  rk_Lap = exp(-(sqrt(rk_Lap))/sigma)
  return(rk_Lap)
} 

Next we fit the Ridge model and plot the trajectories of the parameter estimates across \(\lambda\).

lambda = 10^seq(-6, 2, by = 0.5)
library(furrr)

# For classical sequential parameter search use: 
# gcv_search = map(lambda, function(lam) ridge(X, y, lam))

#  For multicore execution use:
plan(multisession,  workers = 8)
gcv_search <- future_map(lambda, function(lam) ridge(X, y, lam,rk_Laplace))

V = map_dbl(gcv_search, function(x) x$gcv)

ridge_coefs = map_df(gcv_search, function(x) {
    data.frame(value = x$omega_tilde, coef =as.character(1:2223))
  }, 
  .id = 'iter') %>% 
  mutate(lambda = lambda[as.integer(iter)])
library(patchwork)
library(plotly)

# gcv_plot = qplot(lambda, V, geom='line', main='GCV score (log scale)', ylab='GCV') +
#   scale_x_log10()

plot_ly(x=lambda, y=V, type="scatter", mode="lines") %>%
  layout(title="(Ridge) GCV vs. Log10(Lambda)", 
         xaxis = list(title="log10(Lambda)", type = "log"))
# beta_plot = ridge_coefs %>% 
#   ggplot(aes(x = lambda, y = value, color = coef)) +
#   geom_line() +
#   scale_x_log10() +
#   scico::scale_color_scico_d(end = 0.8) +
#   labs(title = 'Model Effects (Betas) Across Lambda')
# ggplotly(gcv_plot + beta_plot)

plot_ly(data=ridge_coefs[as.numeric(ridge_coefs$coef)<20,], x=~lambda, y=~value, 
        type="scatter", mode="lines", color=~coef, name=~coef) %>%
  layout(title="(Ridge Estimates) Effects (Beta's) vs. log10(Lambda)", 
         xaxis = list(title="", type = "log"), # title="log10(Lambda)", 
         legend = list(title="Predicting Covariates", orientation = 'h'))

The plot allows manual zoom in to confirm that instances (case observations) \(4\) and \(18\) appear to be most dominating in estimating the case-contribution weights in the linear regularized model, among the first \(20\) participants. By zooming in or deselecting these two instances \(\{4,18\}\), we can explore the canonical regularization path trajectories.

2.1.8 RSS for different kernels and kernel-parameters

The following example uses small numbers to reduce the extreme computational burden and expedite the computational estimates in compiling the HTML output from the Rmd source. In practice, larger numbers will provide more precise estimates. The resulting RSS are reported in tables.

# Matern kernel function
maternkernel <- function(sigma,nu,rho,x){
  scaled_x = sqrt(2*nu)*x/rho
  return (sapply(scaled_x,besselk_nu(nu))*scaled_x**nu*sigma**2*2**(1-nu)/gamma(nu))
}
rk_Matern <- function(s, t, nu=0.5) {
  # if (sigma <= 0) sigma=1  # avoid singularities
  init_len = length(s)
  rk_dist = 0
  for (i in 1:init_len) { rk_dist = (s[i] - t[i])^2 + rk_dist }
  rk_Mat = maternkernel(1,nu,1, rk_dist+1e-6)
  return(rk_Mat)
} 
maternkernel_nu_mod <- function(nu) {
  return(function(s, t) {
    # if (sigma <= 0) sigma=1  # avoid singularities
    init_len = length(s)
    rk_dist = 0
    for (i in 1:init_len) { rk_dist = (s[i] - t[i])^2 + rk_dist }
    rk_Mat = maternkernel(1,nu,1, sqrt(rk_dist)+1e-6)
    return(rk_Mat)
  } )
}
rk_Matern <- function(s, t, nu=0.5) {
  # if (sigma <= 0) sigma=1  # avoid singularities
  init_len = length(s)
  rk_dist = 0
  for (i in 1:init_len) { rk_dist = (s[i] - t[i])^2 + rk_dist }
  rk_Mat = maternkernel(1,nu,1, sqrt(rk_dist)+1e-6)
  return(rk_Mat)
} 
poly_d_mod <- function(d) {
  return(function(s, t) {
    init_len = length(s)
    rk = 1
    for (i in 1:init_len) { rk = s[i]*t[i] + rk }
    return(rk**d)
  } )
}

Next, we will expand the previous standard Ridge model by using a RKHS and specifying alternative kernels in the estimation of the model coefficients.

2.1.8.1 Linear Ridge Kernel

For \(\lambda\in \{0.01, 0.1, 1, 10\}\).

#Hyperparameter set 1 - Linear Kernel
library(foreach)
library(doParallel)
registerDoParallel(8)
# fitted_ridge1<- ridge(X,y,lambda=10)
# fitted_ridge2<- ridge(X,y,lambda=1)
# fitted_ridge3<- ridge(X,y,lambda=0.1)
# fitted_ridge4<- ridge(X,y,lambda=0.01)

lambda <- c(0.001, 0.01, 0.05, 0.1, 0.5, 1, 2, 10)
fitted_ridge <- vector()
fitted_ridge <- foreach (param = 1:length(lambda), .combine = 'c') %dopar% {
  ridge(X,y,lambda=lambda[param])
}
stopImplicitCluster()
df <- as.data.frame(fitted_ridge)

df_tbl <- rbind(c(df$gcv[1], df$gcv.1[1], df$gcv.2[1], df$gcv.3[1],
                  df$gcv.4[1], df$gcv.5[1], df$gcv.6[1], df$gcv.7[1]),
                c(df$rss[1], df$rss.1[1], df$rss.2[1], df$rss.3[1]))
colnames(df_tbl) <- c(paste0("lambda=", lambda[1]), paste0("lambda=", lambda[2]), 
                      paste0("lambda=", lambda[3]), paste0("lambda=", lambda[4]),
                      paste0("lambda=", lambda[5]), paste0("lambda=", lambda[6]), 
                      paste0("lambda=", lambda[7]), paste0("lambda=", lambda[8]))
rownames(df_tbl) <- c("GCV", "RSS")

library(DT)
datatable(df_tbl, caption="Linear Ridge Kernel (parameter estimates)")

# fitted_ridge1$rss
# fitted_ridge2$rss
# fitted_ridge3$rss
# fitted_ridge4$rss

2.1.8.2 Matern Ridge Kernel

For \(\lambda=0.1\) and \(\nu\in \{0.01, 0.1, 0.5, 1, 1.5, 2, 2.5, 10\}\).

# Hyperparameter set 2 - Matern kernel
# matern1 <- ridge(X,y,lambda=0.1,kernel=rk_Matern)
# matern2 <- ridge(X,y,lambda=0.1,kernel=maternkernel_nu_mod(1))
# matern3 <- ridge(X,y,lambda=0.1,kernel=maternkernel_nu_mod(0.01))
# matern4 <- ridge(X,y,lambda=0.1,kernel=maternkernel_nu_mod(1.5))
# matern5 <- ridge(X,y,lambda=0.1,kernel=maternkernel_nu_mod(2.5))
# matern6 <- ridge(X,y,lambda=0.1,kernel=maternkernel_nu_mod(10))
# matern7 <- ridge(X,y,lambda=0.1,kernel=maternkernel_nu_mod(0.5))

registerDoParallel(8)
nu <- c(0.01, 0.1, 0.5, 1, 1.5, 2, 2.5, 10)
fitted_ridgeMatern <- vector()
fitted_ridgeMatern <- 
  foreach (param = 1:(length(nu)+1), .combine = 'c') %dopar% {
    besselk_nu <- function(nu) { 
      return(function(x) { return(GPBayes::BesselK(nu, x)) }) }
    if (param==1) ridge(X, y, lambda=0.1, kernel=rk_Matern)
    else ridge(X, y, lambda=0.1, kernel=maternkernel_nu_mod(nu[param-1]))
  }
stopImplicitCluster()

df <- as.data.frame(fitted_ridgeMatern)

df_tbl <- rbind(c(df$gcv[1], df$gcv.1[1], df$gcv.2[1], df$gcv.3[1], df$gcv.4[1],
                  df$gcv.5[1], df$gcv.6[1], df$gcv.7[1], df$gcv.8[1], df$gcv.9[1]),
                c(df$rss[1], df$rss.1[1], df$rss.2[1], df$rss.3[1], df$rss.4[1],
                  df$rss.5[1], df$rss.6[1], df$rss.7[1], df$rss.8[1], df$rss.9[1]))
colnames(df_tbl) <- c(paste0("nu=", 0.5), paste0("nu=", nu[1]), paste0("nu=", nu[2]), 
                      paste0("nu=", nu[3]), paste0("nu=", nu[4]),
                      paste0("nu=", nu[5]), paste0("nu=", nu[6]),
                      paste0("nu=", nu[7]), paste0("nu=", nu[8]))
rownames(df_tbl) <- c("GCV", "RSS")

library(DT)
datatable(df_tbl, caption="Matern Ridge Kernel (parameter estimates)")

We can also use any of the other kernels (e.g., polynomial) to fit RKHS Ridge models and compare their performance across different kernels, and hyperparameters (e.g., \(\nu\), \(d\)).

#Hyperparameter set 3 - Polynomial Kernel kernel
# poly1 <- ridge(X,y,lambda=0.1,kernel=poly_d_mod(3/2))
# poly2 <- ridge(X,y,lambda=0.1,kernel=poly_d_mod(1))
# poly3 <- ridge(X,y,lambda=0.1,kernel=poly_d_mod(0.9))
# poly4 <- ridge(X,y,lambda=0.1,kernel=poly_d_mod(0.7))
# poly5 <- ridge(X,y,lambda=0.1,kernel=poly_d_mod(0.5))
# poly6 <- ridge(X,y,lambda=0.1,kernel=poly_d_mod(0.3))

registerDoParallel(7)
poly_d <- c(0.3, 0.5, 0.7, 0.9, 1.5, 2.5, 10)
fitted_ridgePoly <- vector()
fitted_ridgePoly <- 
  foreach (param = 1:length(poly_d), .combine = 'c') %dopar% {
    ridge(X, y, lambda=0.1, kernel=poly_d_mod(poly_d[param]))
  }
stopImplicitCluster()

df <- as.data.frame(fitted_ridgePoly)

df_tbl <- rbind(c(df$gcv[1], df$gcv.1[1], df$gcv.2[1], df$gcv.3[1], df$gcv.4[1],
                  df$gcv.5[1], df$gcv.6[1]),
                c(df$rss[1], df$rss.1[1], df$rss.2[1], df$rss.3[1], df$rss.4[1],
                  df$rss.5[1], df$rss.6[1]))
colnames(df_tbl) <- c(paste0("d=", poly_d[1]), paste0("d=", poly_d[2]), 
                      paste0("d=", poly_d[3]), paste0("d=", poly_d[4]),
                      paste0("d=", poly_d[5]), paste0("d=", poly_d[6]),
                      paste0("d=", poly_d[7]))
rownames(df_tbl) <- c("GCV", "RSS")

library(DT)
datatable(df_tbl, caption="Polynomial Ridge Kernel (parameter estimates)")

Finally, we can select the best model corresponding to the optimal regularization parameter \(\lambda=\lambda_{[which.min(V)]}\) associated with minimization of the GCV search and obtain the corresponding effect size estimates \(\beta\)’s, for example, by refitting the Ridge model with a linear kernel.

plan(multisession,  workers = 8)
X_augmented <- cbind(1, X) # augmented design matrix
gcv_search <- future_map(lambda, function(lam) ridge(X_augmented, y, lam))

V = map_dbl(gcv_search, function(x) x$gcv)

ridge_coefs = map_df(gcv_search, function(x) {
    data.frame(value = x$omega_tilde, coef =as.character(1:2223))
  }, 
  .id = 'iter') %>% mutate(lambda = lambda[as.integer(iter)])

fit_ridge <- ridge(X_augmented, y, lambda[which.min(V)])  # fit optimal model

omega_tilde <- fit_ridge$omega_tilde
beta_hat    <- crossprod(omega_tilde, X)       # slope and noise term coefficients

2.1.9 Comparison of manual RKHS-Ridge and traditional GLM-Net parameter estimates

Next, we will compare our manual ridge-regularized linear model parameter estimation strategy (using RKHS) against the classical glmnet() gold standard. Recall that setting the glmnet hyperparameter alpha = 0 and alpha = 1 correspond to ridge (\(L_2\)) and LASSO (\(L_1\)) regression, respectively.

library(glmnet)
# c(beta_0, beta_hat)
fit_glmnet = glmnet(X, y, alpha = 0, lambda=lambda, standardize = FALSE)

The following table contrasts the manual RKHS-Ridge and the automated GLM-Net Ridge regression effect size estimates for all \(5\) covariate predictors of the outcome ALSFRS_slope. Theoretically, the manual estimates are not expected to match the GLM-Net Ridge estimates, as \(X^TX\neq I\).

kable_df = function(..., digits =3, full_width = FALSE) 
  kable(..., digits=digits) %>% kable_styling(full_width = full_width)

rbind(RKHS_Ridge  = c(beta_hat),   # -1 to skip over the intercept estimation
  GLMNet_Ridge = (coef(fit_glmnet)[, which.max(fit_glmnet$dev.ratio)])[-1]) %>% 
  kable_df()
Age_mean Albumin_max Albumin_median Albumin_min Albumin_range
RKHS_Ridge 0.042 1.277 -0.313 -0.246 -4.674
GLMNet_Ridge 0.042 1.304 -0.319 -0.261 -4.747

2.2 LASSO Regression Example

Again, we will define a manual lasso() method de novo using RKHS modeling, the Gram matrix, and fitting a LASSO regularized linear model for estimating the parameters (effect sizes). To see the theoretical derivation for kernelized LASSO regression (See appendix 5.4).

There is a distinction of shrinking on observations and shrinking on features. We run some experiments showing a possible way of implementing kernelized LASSO with shrinkage on the features or on the instances. Then, we will compare the results with the classical glmnet approach for efficient elastic net regularized linear modeling.

2.2.1 Shrinkage on the instances (cases)

To demonstrate participant selection, i.e., instance or case shrinkage, we’ll use the following linear kernel implementation.

library(MASS)
# observation shrinkage
lasso_observation <- function(X, y, lambda=0.1, kernel=rk) { 
  K = gram(X,kernel)                            
  # assumed X to be n*d where observations stacked on the rows, 
  # GramMatrix (nxn) XTX (already phi^Tphi)
  
  n = length(y)                                   
  #Q = cbind(1, GramMatrix) no need for intercept as the kernel already captures this
  #S = rbind(0, cbind(0, GramMatrix))
  alpha_hat = inverse(K) %*% y

  for (j in 1:n) { # The explicit formula for LASSO loss
    alpha_hat[j] =  alpha_hat[j]*max(0,1-length( alpha_hat)*lambda/abs( alpha_hat[j]))
  }
  
  M = K%*%K + lambda*ginv(diag(as.list(abs(alpha_hat))))  # X^TX+lambda W-
  
  M_inv = inverse(M)                              # invert M

  f_hat = K %*% alpha_hat 
  
  A = K %*% M_inv %*% K  # Hat matrix X(X^XX+lambda W-)^_1 X^T
  tr_A = sum(diag(A))                             # trace of hat matrix
  
  rss  = crossprod(y - f_hat)                     # residual sum of squares
  gcv  = n*rss / (n - tr_A)^2                     # compute GCV score
  
  return(list(f_hat = f_hat, alpha_hat = alpha_hat, gcv = gcv, rss=rss))
}

The prediction procedure is essentially \[\hat{y}=K S_{\lambda}(K^{-1}y)\ .\] Notice that when \(\lambda=0\), this degenerates into a perfect reconstruction. As a benchmark, the resulting RSS and GCV values are \(34.57\) and \(11.71\), respectively.

# when lambda is 0
fitted_lambda0 <- lasso_observation(X, y, 0,rk_Laplace)
fitted_lambda0$gcv
fitted_lambda0$rss

Next, we run over the grid space of the \(\lambda\) parameter.

lambda = 10^seq(-9, 2, by = 0.5)
library(furrr)

# For classical sequential parameter search use: 
# gcv_search = map(lambda, function(lam) ridge(X, y, lam))

#  For multicore execution use:
plan(multisession,  workers = 12)
gcv_search <- future_map(lambda, function(lam) lasso_observation(X, y, lam,rk_Laplace))

V_lasso = map_dbl(gcv_search, function(x) x$gcv)

lasso_coefs = map_df(gcv_search, function(x) {
    data.frame(value = x$alpha_hat, coef =as.character(1:2223))
  }, 
  .id = 'iter') %>% mutate(lambda = lambda[as.integer(iter)])

We observe that initially, the GCV score decreases, since \(GCV(lambda=0)= 11.71\)), and then alternates between increases and decreases.

library(patchwork)
library(plotly)

RSS_lasso = map_dbl(gcv_search, function(x) x$rss)
plot_ly(x=lambda, y=RSS_lasso, type="scatter", mode="lines") %>%
  layout(title="(LASSO) RSS (Observation) vs. Log10(Lambda)", 
         xaxis = list(title="log10(Lambda)", type = "log"))
# gcv_plot = qplot(lambda, V, geom='line', main='GCV score (log scale)', ylab='GCV') +
#   scale_x_log10()

plot_ly(x=lambda, y=V_lasso, type="scatter", mode="lines") %>%
  layout(title="(LASSO) GCV (Observation) vs. Log10(Lambda)", 
         xaxis = list(title="log10(Lambda)", type = "log"))
# beta_plot = ridge_coefs %>% 
#   ggplot(aes(x = lambda, y = value, color = coef)) +
#   geom_line() +
#   scale_x_log10() +
#   scico::scale_color_scico_d(end = 0.8) +
#   labs(title = 'Model Effects (Betas) Across Lambda')
# ggplotly(gcv_plot + beta_plot)

plot_ly(data=lasso_coefs[as.numeric(lasso_coefs$coef)<20,], x=~lambda, y=~value, 
        type="scatter", mode="lines", color=~coef, name=~coef) %>%
  layout(title="LASSO Effect Estimates (Beta's) vs. log10(Lambda)", 
         xaxis = list(title="", type = "log"), # title="log10(Lambda)", 
         legend = list(title="Predicting Covariates", orientation = 'h'))
index <- 1
meta_matrix <- matrix(0,nrow=2223,ncol=length(lambda)) # 2223 is the number of rows
for (i in lambda){
  meta_matrix[,index] <- (lasso_coefs[lasso_coefs$lambda==i,]$value ==0)
    index <- index + 1
}
library(DT)

# image(t(meta_matrix),xlab="Lambda values", yaxt="n",xaxt="n")
# axis(3, at=seq(0,1, length=length(lambda)), labels=as.character(signif(lambda,2)))
plot_ly(z=t(meta_matrix), type="heatmap") %>%
  layout(title="Lambda values (x-axis) vs. LASSO Coefficient Estimates (y-axis)",
         xaxis = list(tickvals = seq(0, dim(meta_matrix)[1], length=length(lambda)),
                      ticktext = c(as.character(signif(lambda,2)))))