Guest User

Untitled

a guest
Feb 25th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. # Function to calculate cosine dissimilarity matrix
  2. # Thanks to: https://stats.stackexchange.com/a/149865/121489
  3. cos.sim <- function(ma, mb) {
  4. mat <- tcrossprod(ma, mb);
  5. t1 <- sqrt(apply(ma, 1, crossprod));
  6. t2 <- sqrt(apply(mb, 1, crossprod));
  7. return(mat / outer(t1, t2));
  8. }
  9.  
  10. # Generate sample data
  11. set.seed(2017);
  12. x1 <- matrix(rnorm(45), ncol = 5);
  13.  
  14. # Calculate the cosine dissimilarity matrix
  15. m <- cos.sim(x1, x1);
  16.  
  17. # Show heatmap
  18. library(tidyverse);
  19. m %>%
  20. as_tibble() %>%
  21. rownames_to_column("x1") %>%
  22. gather(x2, value, 2:10) %>%
  23. mutate(x2 = gsub("V", "", x2)) %>%
  24. ggplot(aes(x1, x2)) + geom_tile(aes(fill = value));
Add Comment
Please, Sign In to add comment