【问题标题】:How to calculate similarity for pre-trained word embeddings如何计算预训练词嵌入的相似度
【发布时间】:2022-05-01 21:16:29
【问题描述】:

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

源代码:

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
  }
}

但我不知道如何获得最相似的单词。 我找到了示例,但由于嵌入向量的结构不同而不起作用

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 中预训练词嵌入的相似度?

【问题讨论】:

    标签: r keras word2vec word-embedding glove


    【解决方案1】:

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

    # 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      相关资源
      最近更新 更多