1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| library(kernlab) library(Rcpp) library(RcppArmadillo)
sourceCpp(code = ' // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> using namespace Rcpp; using namespace arma;
// [[Rcpp::export]] NumericMatrix kernelMatrix_cpp2(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); }')
N = 10000 p = 1000 b = 3000 X = matrix(rnorm(N*p), ncol = p) center = X[sample(1:N, b),] sigma = 3 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), cpp2 = kernelMatrix_cpp2(X, center, sigma), kernlab = kernelMatrix(rbfdot(sigma=1/(2*sigma^2)), X, center), columns=c("test", "replications","elapsed", "relative"), replications=10, order="relative")
N = 1000 p = 100 b = 300 X = matrix(rnorm(N*p), ncol = p) center = X[sample(1:N, b),] sigma = 3 benchmark(cpp = kernelMatrix_cpp(X, center, sigma), cpp2 = kernelMatrix_cpp2(X, center, sigma), kernlab = kernelMatrix(rbfdot(sigma=1/(2*sigma^2)), X, center), columns=c("test", "replications","elapsed", "relative"), replications=10, order="relative")
|