我需要通过比较文档的条款来建立一个相似度矩阵。因此,例如,如果 Document1 和 Document2 有 2 个相同的术语,我需要在我的相似度矩阵中的 m[1, 2] 处写一个 2。我的相似度矩阵现在看起来像这样:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 0 NA NA NA NA NA NA NA NA
[2,] 0 0 NA NA NA NA NA NA NA
[3,] 0 0 0 NA NA NA NA NA NA
[4,] 0 0 0 0 NA NA NA NA NA
[5,] 0 0 0 0 0 NA NA NA NA
[6,] 0 0 0 0 0 0 NA NA NA
[7,] 0 0 0 0 0 0 0 NA NA
[8,] 0 0 0 0 0 0 0 0 NA
文档和术语位于文档术语矩阵中。现在我必须通过比较所有文档及其在相似度矩阵中表示为 NA 的术语来填充相似度矩阵。对于文档对中的每个 Term 匹配,我必须计算 +1 并将最终值注入矩阵中的正确位置。
我的问题是,我似乎无法访问文档术语矩阵中的单个文档及其术语。有没有其他方法可以执行此操作,或者我错过了什么?这里的代码:
install.packages("tm")
install.packages("openNLP")
install.packages("openNLPmodels.en")
Sys.setenv(NOAWT=TRUE)
library(tm)
library(openNLP)
library(openNLPmodels.en)
sample = c(
"count eagle alien",
"dis bound eagle",
"bound count eagle dis",
"count eagle dis alien",
"bound eagle",
"count dis alien",
"bound count alien",
"bound count",
"count eagle dis"
)
print(sample)
corpus <- Corpus(VectorSource(sample))
inspect(corpus)
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, tolower)
corpus <- tm_map(corpus, removeWords, stopwords("english"))
corpus <- tm_map(corpus, stemDocument,language="english")
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, tmTagPOS)
inspect(corpus)
dtm <- DocumentTermMatrix(corpus)
inspect(dtm)
# need to create similarity matrix here
#dist(dtm, method = "manhattan", diag = FALSE, upper = TRUE)
rowCount <- nrow(dtm)
similMatrix = matrix(nrow = rowCount - 1, ncol = rowCount)
show(similMatrix)
similMatrix[ row(similMatrix) >= col(similMatrix) ] <- 0
for(i in 1:(rowCount - 1)){ # rows
for (j in i+1:rowCount){ # cols
# need to compare document i and j here and write
# the value into similarity matrix
}
}
show(similMatrix)