Search code examples
matlabword2vec

How to calculate the cosine similarity between two words (word2vec in matlab)?


I have this parameters form word2vec_matlab, and I want to calculate the cosine similarity distance

wordvecs_norm - Normalized word vectors
word2Index    - Map of words to indeces
input         - Input word (string)
k             - Number of words to return 

I tried

 word1 = ('king');
 word2 = ('queen');
 cosine = dot(wordvecs(word1)/ wordvecs_norm(word1), wordvecs(word2)/ wordvecs_norm(word2));        

Solution

  • Wikipedia gives this as formula: https://en.wikipedia.org/wiki/Cosine_similarity enter image description here

    I think this translates in MATLAB to:

    wv1 = wordvecs(word1) wv2 = wordvecs(word2) cosine = dot(wv1,wv2)/ (sqrt(dot(wv1,wv1))*sqrt(dot(wv2,wv2))) Let me know if it works!