library(MASS) library(microbenchmark) library(tidyverse) Utility functions The kernel_matrix function calculates the kernel matrix with squared exponential in a vectorized way. This function is borrowed from the profiling portfolio.
kernel_matrix <- function(X, sigmasq, Y=NULL){ if (is.null(Y)){ Y <- X } n <- nrow(X) m <- nrow(Y) # Find three matrices above Xnorm <- matrix(apply(X^2, 1, sum), n, m) Ynorm <- matrix(apply(Y^2, 1, sum), n, m, byrow=TRUE) XY <- tcrossprod(X, Y) return(exp(-(Xnorm - 2*XY + Ynorm) / (2*sigmasq))) } The function make_flags takes a y vector of length n and containing K class labels 0, 1, , K-1 and returns a matrix with n rows and K columns, where each row is a one-hot encoding for the class corresponding to that observation.