'How to calculate similarity for pre-trained word embeddings
I want to know the most similar words to another from a pretrained embedding vectors in R. E.g: words similar to "beer". For this, I download the pretrained embedding vectors on http://nlp.stanford.edu/data/glove.twitter.27B.zip and applied the code below:
Source code:
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
}
}
But I do not how to get the words most similar. I found the examples but doesn't work because the structure of embeddings vectors are different
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)
How to calculate similarity for pre-trained word embeddings in R?
Solution 1:[1]
One solution might be to use the 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gorp |