0

I have a matrix X of dimensions 942*50. I want to create an affinity matrix with the Gaussian RBF Kernel. ie, for every pair of rows in the X matrix, I want to compute exp(-sigma*norm(x_i-x_j)^2) where x_i and x_j are rows of the X matrix and i,j vary from 1:nrow(X). I am writing the code in R. The piece of R code below throws up an error:

library('kernlab')
rbf <- rbfdot(sigma=15.0563)
func <- function(i,j){return(rbf(X[i,],X[j,]))}
rows <- cols <- 1:nrow(X)
outer(rows,cols,FUN=func)

I get the following error: Error in outer(rows, cols, FUN = fun) : dims [product 887364] do not match the length of object [2500]

user2878729
  • 61
  • 1
  • 5

1 Answers1

3

Outer expects a vectorized function (see ?outer). Hence your code should be:

library('kernlab')
rbf<-rbfdot(sigma=15.0563)
func<-Vectorize(function(i,j){return(rbf(X[i,],X[j,]))})
rows<-1:nrow(X)
cols<-1:nrow(X)
outer(rows,cols,FUN=func)
user3794498
  • 184
  • 3