我想通过使用余弦相似度与 R 编程语言对文档语料库进行层次聚类,但出现以下错误:
if (is.na(n) || n > 65536L) stop("大小不能为 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("大小不能为 NA 或
超过 65536") :需要 TRUE/FALSE 时缺少值
有2个问题:
1: cosine_dist = 1-crossprod(tf_idf) /(sqrt(colSums(tf_idf^2)%*%t(colSums(tf_idf^2))))
因为除以 0,所以会产生 NaN。
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)