Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(kernlab)
- library(Rcpp)
- library(RcppArmadillo)
- N = 10000
- p = 1000
- b = 3000
- X = matrix(rnorm(N*p), ncol = p)
- center = X[sample(1:N, b),]
- sigma = 3
- ## For windows user
- # library(inline)
- # settings <- getPlugin("Rcpp")
- # settings$env$PKG_CXXFLAGS <- paste('-fopenmp', settings$env$PKG_CXXFLAGS)
- # settings$env$PKG_LIBS <- paste('-fopenmp -lgomp', settings$env$PKG_LIBS)
- # do.call(Sys.setenv, settings$env)
- sourceCpp(code = '
- // [[Rcpp::depends(RcppArmadillo)]]
- #include <RcppArmadillo.h>
- using namespace Rcpp;
- using namespace arma;
- // [[Rcpp::export]]
- NumericMatrix kernelMatrix_cpp(NumericMatrix Xr, NumericMatrix Centerr, double sigma) {
- uword n = Xr.nrow(), b = Centerr.nrow(), row_index, col_index;
- mat X(Xr.begin(), n, Xr.ncol(), false), Center(Centerr.begin(), b, Centerr.ncol(), false), KerX(X*Center.t());
- colvec X_sq = sum(square(X), 1) / 2;
- rowvec Center_sq = (sum(square(Center), 1)).t() / 2;
- KerX.each_row() -= Center_sq;
- KerX.each_col() -= X_sq;
- KerX *= 1 / (sigma * sigma);
- KerX = exp(KerX);
- return wrap(KerX);
- }')
- t1 = Sys.time()
- kernel_X_cpp = kernelMatrix_cpp2(X, center, sigma)
- Sys.time() - t1
- t1 = Sys.time()
- kernel_X <- kernelMatrix(rbfdot(sigma=1/(2*sigma^2)), X, center)
- Sys.time() - t1
- all.equal(kernel_X@.Data, kernel_X_cpp)
- library(rbenchmark)
- 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