Created
June 9, 2012 23:29
-
-
Save bobthecat/2903031 to your computer and use it in GitHub Desktop.
Rcpp cosine similarity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require(inline) | |
require(RcppArmadillo) | |
## extract cosine similarity between columns | |
cosine <- function(x) { | |
y <- t(x) %*% x | |
res <- 1 - y / (sqrt(diag(y)) %*% t(sqrt(diag(y)))) | |
return(res) | |
} | |
cosineRcpp <- cxxfunction( | |
signature(Xs = "matrix"), | |
plugin = c("RcppArmadillo"), | |
body=' | |
Rcpp::NumericMatrix Xr(Xs); // creates Rcpp matrix from SEXP | |
int n = Xr.nrow(), k = Xr.ncol(); | |
arma::mat X(Xr.begin(), n, k, false); // reuses memory and avoids extra copy | |
arma::mat Y = arma::trans(X) * X; // matrix product | |
arma::mat res = (1 - Y / (arma::sqrt(arma::diagvec(Y)) * arma::trans(arma::sqrt(arma::diagvec(Y))))); | |
return Rcpp::wrap(res); | |
') | |
mat <- matrix(rnorm(100000), ncol=1000) | |
x <- cosine(mat) | |
y <- cosineRcpp(mat) | |
identical(x, y) | |
[1] TRUE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment