我想使用宽松的单词移动距离来计算文本相似度。我有两个不同的数据集(语料库)。见下文。
A <- data.frame(name = c(
"X-ray right leg arteries",
"consultation of gynecologist",
"x-ray leg arteries",
"x-ray leg with 20km distance",
"x-ray left hand"
), stringsAsFactors = F)
B <- data.frame(name = c(
"X-ray left leg arteries",
"consultation (inspection) of gynecalogist",
"MRI right leg arteries",
"X-ray right leg arteries with special care"
), stringsAsFactors = F)
我在 R 中使用 text2vec 包。
library(text2vec)
library(stringr)
prep_fun = function(x) {
x %>%
# make text lower case
str_to_lower %>%
# remove non-alphanumeric symbols
str_replace_all("[^[:alnum:]]", " ") %>%
# collapse multiple spaces
str_replace_all("\\s+", " ")
}
Combine both datasets
C = rbind(A, B)
C$name = prep_fun(C$name)
it = itoken(C$name, progressbar = FALSE)
v = create_vocabulary(it) %>% prune_vocabulary()
vectorizer = vocab_vectorizer(v)
dtm = create_dtm(it, vectorizer)
tcm = create_tcm(it, vectorizer, skip_grams_window = 3)
glove_model = GloVe$new(word_vectors_size = 10, vocabulary = v, x_max = 3)
wv = glove_model$fit_transform(tcm, n_iter = 10)
# get average of main and context vectors as proposed in GloVe paper
wv = wv + t(glove_model$components)
rwmd_model = RWMD$new(wv)
rwmd_dist = dist2(dtm[1:nrow(A), ], dtm[nrow(A)+1:nrow(C), ], method = rwmd_model, norm = 'none')
head(rwmd_dist)
[,1] [,2] [,3] [,4]
[1,] 0.1220713 0.7905035 0.3085216 0.4182328
[2,] 0.7043127 0.1883473 0.8031200 0.7038919
[3,] 0.1220713 0.7905035 0.3856520 0.4836772
[4,] 0.5340587 0.6259011 0.7146630 0.2513135
[5,] 0.3403019 0.5575993 0.7568583 0.5124514
skip_grams_window = 3
在代码中是否tcm = create_tcm(it, vectorizer, skip_grams_window = 3)
意味着在创建共现矩阵时向右检查 3 个单词?例如,文本 'X-ray right leg arteries' 将变成矢量 - target :'X-ray'
right leg arteries
1 1 1
有什么用word_vectors_size
?我读过手套的算法,但不明白这个函数的用法。
glove_model = GloVe$new(word_vectors_size = 10, 词汇 = v, x_max = 3)