首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算预训练词嵌入的相似度

如何计算预训练词嵌入的相似度
EN

Stack Overflow用户
提问于 2018-10-28 20:36:26
回答 1查看 301关注 0票数 2

我想知道R中预先训练过的嵌入向量中最相似的词。例如:类似于“啤酒”的词。为此,我在http://nlp.stanford.edu/data/glove.twitter.27B.zip上下载了预先训练过的嵌入向量,并应用了以下代码:

源代码:

代码语言:javascript
复制
glove_dir = "~/Downloads/glove.6B"
lines <- readLines(file.path(glove_dir, "glove.6B.100d.txt"))
embeddings_index <- new.env(hash = TRUE, parent = emptyenv())
for (i in 1:length(lines)) {
    line <- lines[[i]]
    values <- strsplit(line, " ")[[1]]
    word <- values[[1]]
    embeddings_index[[word]] <- as.double(values[-1])
}
cat("Found", length(embeddings_index), "word vectors.\n")

embedding_dim <- 100
embedding_matrix <- array(0, c(max_words, embedding_dim))
for (word in names(word_index)) {
  index <- word_index[[word]]
  if (index < max_words) {
    embedding_vector <- embeddings_index[[word]]
    if (!is.null(embedding_vector))
      embedding_matrix[index+1,] <- embedding_vector
  }
}

但我不知道如何得到最相似的词。我找到了示例,但没有工作,因为嵌入向量的结构是不同的

代码语言:javascript
复制
find_similar_words <- function(word, embedding_matrix, n = 5) {
    similarities <- embedding_matrix[word, , drop = FALSE] %>%
    sim2(embedding_matrix, y = ., method = "cosine")
    similarities[,1] %>% sort(decreasing = TRUE) %>% head(n)
}
find_similar_words("beer", embedding_matrix)

R中预训练词嵌入的相似度计算

EN

回答 1

Stack Overflow用户

发布于 2022-05-01 13:16:29

一种解决方案可能是使用text-package (www.r-text.org)。

代码语言:javascript
复制
# for installation guidelines see:  http://www.r-text.org/articles/Extended_Installation_Guide.html

library(text)
text_example <- c("beer wine nurse doctor")

text_example_embedding <- textEmbed(text_example, contexts = FALSE)

word_ss <- textSimilarityMatrix(text_example_embedding$singlewords_we)

# The order of the words has changed, so name them according to how they appear in the output. 
colnames(word_ss) <- text_example_embedding$singlewords_we$words
rownames(word_ss) <- text_example_embedding$singlewords_we$words
round(word_ss, 3)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53035839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档