Created
August 8, 2019 08:14
-
-
Save inkrement/2301f2403d85910ac4e2746adde7a858 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cosine_similarity <- function(a,b){ | |
# assuming unit vectors | |
# the cosine is just the dot-product | |
a %*% b | |
} | |
most_similar <- function(embeddings, ref_item, n_top = 10){ | |
# calculate cos similarity to ref_item for all elements | |
cos_sims <- eapply(embeddings, cosine_similarity, b = ref_item) | |
# only look at cos values smaller than 1 | |
# this will ignore the same element | |
cos_sims <- cos_sims[cos_sims < 1] | |
# return top elements | |
cos_sims[order(unlist(cos_sims),decreasing=TRUE)][1:n_top] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment