【问题标题】:Hierarchical clustering using cosine distance in R在 R 中使用余弦距离进行层次聚类
【发布时间】:2019-02-22 18:49:14
【问题描述】:

我想通过使用余弦相似度和 R 编程语言对文档语料库进行层次聚类,但出现以下错误:

if (is.na(n) || n > 65536L) stop("size 不能为 NA 或 超过 65536") : 需要 TRUE/FALSE 的缺失值

我该怎么办?

为了重现它,这里有一个例子:

library(tm)
doc <- c( "The sky is blue.", "The sun is bright today.", "The sun in the sky is bright.", "We can see the shining sun, the bright sun." )
doc_corpus <- Corpus( VectorSource(doc) )
control_list <- list(removePunctuation = TRUE, stopwords = TRUE, tolower = TRUE)
tdm <- TermDocumentMatrix(doc_corpus, control = control_list)



tf <- as.matrix(tdm)
( idf <- log( ncol(tf) / ( 1 + rowSums(tf != 0) ) ) )
( idf <- diag(idf) )
tf_idf <- crossprod(tf, idf)
colnames(tf_idf) <- rownames(tf)

tf_idf

cosine_dist = 1-crossprod(tf_idf) /(sqrt(colSums(tf_idf^2)%*%t(colSums(tf_idf^2))))
cluster1 <- hclust(cosine_dist, method = "ward.D")

然后我得到错误:

if (is.na(n) || n > 65536L) stop("size 不能为 NA 或 超过 65536") : 需要 TRUE/FALSE 的缺失值

【问题讨论】:

    标签: r tm hierarchical-clustering


    【解决方案1】:

    有两个问题:

    1:cosine_dist = 1-crossprod(tf_idf) /(sqrt(colSums(tf_idf^2)%*%t(colSums(tf_idf^2)))) 创建 NaN,因为你除以 0。

    2:hclust 需要一个 dist 对象,而不仅仅是一个矩阵。更多详情请见?hclust

    都可以用下面的代码解决:

    .....
    cosine_dist = 1-crossprod(tf_idf) /(sqrt(colSums(tf_idf^2)%*%t(colSums(tf_idf^2))))
    
    # remove NaN's by 0
    cosine_dist[is.na(cosine_dist)] <- 0
    
    # create dist object
    cosine_dist <- as.dist(cosine_dist)
    
    cluster1 <- hclust(cosine_dist, method = "ward.D")
    
    plot(cluster1)
    

    【讨论】:

      猜你喜欢
      • 2015-09-22
      • 2012-09-05
      • 1970-01-01
      • 2017-07-10
      • 2016-08-09
      • 2017-12-12
      • 2016-03-12
      • 2021-03-16
      • 2016-06-03
      相关资源
      最近更新 更多