celestialgod

LOOCV with Rcpp (R file)

Dec 31st, 2016
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.92 KB | None | 0 0
  1. Rcpp::sourceCpp("RcppLOOCV.cpp")
  2.  
  3. N <- 600L
  4. p <- 150L
  5. X <- matrix(rnorm(N*p), N)
  6. b <- rnorm(p, rnorm(2L), rgamma(2L,3,7))
  7. y <- 1.5 + as.vector(X %*% b) + rnorm(N)
  8.  
  9. system.time({
  10.   out <- sapply(1L:N, function(i){
  11.     idx <- setdiff(1L:N, i)
  12.     b <- coef(lm(y[idx] ~ X[idx , ]))
  13.     return((y[i] - crossprod(c(1, X[i, ]), b))**2)
  14.   })
  15. })
  16. #  user  system elapsed
  17. #  8.83    0.28    9.20
  18.  
  19. # check results
  20. for (i in 1L:5L) stopifnot(abs(mean(out) - arma_fastLOOCV1(y, X)) < 1e-8)
  21. for (i in 1L:5L) stopifnot(abs(mean(out) - arma_fastLOOCV2(y, X)) < 1e-8)
  22. for (i in 1L:5L) stopifnot(abs(mean(out) - eigen_fastLOOCV1(y, X)) < 1e-8)
  23. for (i in 1L:5L) stopifnot(abs(mean(out) - eigen_fastLOOCV2(y, X)) < 1e-8)
  24. for (i in 1L:5L) stopifnot(abs(mean(out) - eigen_fastLOOCV3(y, X)) < 1e-8)
  25. for (i in 1L:5L) stopifnot(abs(mean(out) - eigen_fastLOOCV4(y, X)) < 1e-8)
  26.  
  27. library(microbenchmark)
  28. microbenchmark(
  29.   arma_fastLOOCV1(y, X),  # RcppArmadillo with RcppPrallel
  30.   arma_fastLOOCV2(y, X),  # RcppArmadillo with openmp
  31.   eigen_fastLOOCV1(y, X), # RcppEigen with RcppPrallel (Reduce)
  32.   eigen_fastLOOCV2(y, X), # RcppEigen with RcppPrallel (For)
  33.   eigen_fastLOOCV3(y, X), # RcppEigen with openmp
  34.   eigen_fastLOOCV4(y, X), # RcppEigen without parallism
  35.   times = 30L
  36. )
  37. # Unit: milliseconds
  38. #                    expr       min        lq      mean    median        uq       max neval
  39. #   arma_fastLOOCV1(y, X) 1009.9239 1037.4614 1052.9272 1045.9733 1068.5668 1101.5399    30
  40. #   arma_fastLOOCV2(y, X) 1020.5068 1033.6180 1051.7171 1046.8751 1064.4512 1139.6371    30
  41. #  eigen_fastLOOCV1(y, X)  623.7900  628.0837  639.1062  635.0657  644.8178  716.8571    30
  42. #  eigen_fastLOOCV2(y, X)  620.1337  624.2227  634.4193  630.3217  641.1066  682.0993    30
  43. #  eigen_fastLOOCV3(y, X)  620.0021  630.6396  643.2877  638.7085  655.9284  706.5759    30
  44. #  eigen_fastLOOCV4(y, X) 2627.1159 2648.5870 2657.8932 2654.8032 2663.2681 2707.9168    30
Advertisement
Add Comment
Please, Sign In to add comment