我想通过使用余弦相似度和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的值
答案 0 :(得分:1)
有2个问题:
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)