我试图从对角线1的距离矩阵制作热图。实际上,距离矩阵是余弦相似度。我用“factoextra”R包中的fviz_dist绘制了这个矩阵。我想出了这个情节。
如您所见,对角线表示值0.但在余弦相似度中,对角线为1,这意味着它们更相似。如何在图中将值更改为1?
答案 0 :(得分:0)
对于以后的帖子,请了解how to ask个好问题,并始终提供包含示例数据的minimal reproducible example/attempt。
case class Relationship(name: String, opposite:Relationship)
def relationshipFactory(nameA:String, nameB:String): Relationship = {
lazy val x:Relationship = Relationship(nameA, Relationship(nameB, x))
x
}
val ns = relationshipFactory("North", "South")
ns // North
ns.opposite // South
ns.opposite.opposite // North
ns.opposite.opposite.opposite // South
注意热图中# 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));
的1对角线。