如果您想要术语频率的相关性,假设您对每一行都有一个频率向量表示,那么您可以通过计算余弦相似度来计算任何两行之间的相似度。
以下是如何在 R 中做到这一点:
data_set <- c("the big bad dog",
"the small cat and the orange cat",
"the big big dog")
words <- strsplit(data_set, split = " ") #tokenize sentences
vec <- unique(unlist(words)) #vector representation of sentences
m <- matrix(nrow = length(data_set), ncol = length(vec))
for (i in 1:length(words)) { #iterate the index of tokenized sentences
tokens <- words[[i]]
vec_rep <- as.integer(sapply(vec, function(w){sum( w == tokens)})) #create binary word-feature vector
m[i,] <- vec_rep #update matrix
}
df <- data.frame(m, row.names = NULL)
names(df) <- vec
df
## the big bad dog small cat and orange
##1 1 1 1 1 0 0 0 0
##2 2 0 0 0 1 2 1 1
##3 1 2 0 1 0 0 0 0
cosineSimilarity <- function(df, row1, row2){
x <- as.numeric(df[row1,])
y <- as.numeric(df[row2,])
(x %*% y) / (sqrt(x%*%x * y%*%y))
}
cosineSimilarity(df,1,1) #1.00
cosineSimilarity(df,1,2) #0.30
cosineSimilarity(df,1,3) #0.82
如果您已标记训练数据,则可以为每个标签创建一个原型向量表示。然后在未标记数据的分类过程中,您只需计算目标文本和每个原型之间的余弦相似度,然后将标签分配给使相似度得分最大化的原型。