Guest User

Kernel matrix via efficiency approach

a guest
Jul 19th, 2014
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. library(kernlab)
  2. library(Rcpp)
  3. library(RcppArmadillo)
  4. N = 10000
  5. p = 1000
  6. b = 3000
  7. X = matrix(rnorm(N*p), ncol = p)
  8. center = X[sample(1:N, b),]
  9. sigma = 3
  10. ## For windows user
  11. # library(inline)
  12. # settings <- getPlugin("Rcpp")
  13. # settings$env$PKG_CXXFLAGS <- paste('-fopenmp', settings$env$PKG_CXXFLAGS)
  14. # settings$env$PKG_LIBS <- paste('-fopenmp -lgomp', settings$env$PKG_LIBS)
  15. # do.call(Sys.setenv, settings$env)
  16. sourceCpp(code = '
  17. // [[Rcpp::depends(RcppArmadillo)]]
  18. #include <RcppArmadillo.h>
  19. using namespace Rcpp;
  20. using namespace arma;
  21.  
  22. // [[Rcpp::export]]
  23. NumericMatrix kernelMatrix_cpp(NumericMatrix Xr, NumericMatrix Centerr, double sigma) {
  24.  uword n = Xr.nrow(), b = Centerr.nrow(), row_index, col_index;
  25.  mat X(Xr.begin(), n, Xr.ncol(), false), Center(Centerr.begin(), b, Centerr.ncol(), false), KerX(X*Center.t());
  26.  colvec X_sq = sum(square(X), 1) / 2;
  27.  rowvec Center_sq = (sum(square(Center), 1)).t() / 2;
  28.  KerX.each_row() -= Center_sq;
  29.  KerX.each_col() -= X_sq;
  30.  KerX *= 1 / (sigma * sigma);
  31.  KerX = exp(KerX);
  32.  return wrap(KerX);
  33. }')
  34.  
  35. t1 = Sys.time()
  36. kernel_X_cpp = kernelMatrix_cpp2(X, center, sigma)
  37.  Sys.time() - t1
  38.  t1 = Sys.time()
  39. kernel_X <- kernelMatrix(rbfdot(sigma=1/(2*sigma^2)), X, center)
  40. Sys.time() - t1
  41. all.equal(kernel_X@.Data, kernel_X_cpp)
  42.  
  43. library(rbenchmark)
  44. benchmark(cpp = kernelMatrix_cpp(X, center, sigma), kernlab = kernelMatrix(rbfdot(sigma=1/(2*sigma^2)), X, center), columns=c("test", "replications","elapsed", "relative"), replications=10, order="relative")
Advertisement
Add Comment
Please, Sign In to add comment