Created
May 27, 2017 20:26
-
-
Save pgolding/fdf74a3e8e797fad0391befd5a906ddb to your computer and use it in GitHub Desktop.
Cosine Similarity Python Scikit Learn
This file contains 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
# http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html | |
import numpy as np | |
from sklearn.metrics.pairwise import cosine_similarity | |
# The usual creation of arrays produces wrong format (as cosine_similarity works on matrices) | |
x = np.array([2,3,1,0]) | |
y = np.array([2,3,0,0]) | |
# Need to reshape these | |
x = x.reshape(1,-1) | |
y = y.reshape(1,-1) | |
# Or just create as a single row matrix | |
z = np.array([[1,1,1,1]]) | |
# Now we can compute similarities | |
cosine_similarity(x,y) # = array([[ 0.96362411]]), most similar | |
cosine_similarity(x,z) # = array([[ 0.80178373]]), next most similar | |
cosine_similarity(y,z) # = array([[ 0.69337525]]), least similar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hay,
There is another way you can do the same without reshaping the dataset.
Say I take three sentences
sentence_m = “Mason really loves food”
sentence_h = “Hannah loves food too”
sentence_w = “The whale is food”
sentence_m: Mason=1, really=1, loves=1, food=1, too=0, Hannah=0, The=0, whale=0, is=0
sentence_h: Mason=0, really=0, loves=1, food=1, too=1, Hannah=1, The=0, whale=0, is=0
sentence_w: Mason=0, really=0, loves=0, food=1, too=0, Hannah=0, The=1, whale=1, is=1