我正在尝试从对角线为1的距离矩阵制作热图。实际上,距离矩阵是余弦相似度。我用“factoextra”R 包中的 fviz_dist 绘制了这个矩阵。我想出了这个情节。
如你所见,对角线表示值0。但在余弦相似度中,对角线为1,这意味着它们更相似。如何将图中的值更改为 1?
TBH,我不确定你在追求什么:这是否是关于如何绘制热图?或者如何“手动”计算余弦相异矩阵?无论哪种方式,这里都是一个使用一些示例数据的完整示例。
# Function to calculate cosine dissimilarity matrix
# Thanks to: https://stats.stackexchange.com/a/149865/121489
cos.sim <- function(ma, mb) {
mat <- tcrossprod(ma, mb);
t1 <- sqrt(apply(ma, 1, crossprod));
t2 <- sqrt(apply(mb, 1, crossprod));
return(mat / outer(t1, t2));
}
# Generate sample data
set.seed(2017);
x1 <- matrix(rnorm(45), ncol = 5);
# Calculate the cosine dissimilarity matrix
m <- cos.sim(x1, x1);
# Show heatmap
library(tidyverse);
m %>%
as_tibble() %>%
rownames_to_column("x1") %>%
gather(x2, value, 2:10) %>%
mutate(x2 = gsub("V", "", x2)) %>%
ggplot(aes(x1, x2)) + geom_tile(aes(fill = value));
注意热图中
m
的第 1 个对角线。