Home Ask Login Register

Developers Planet

Your answer is one click away!

Nick Lothian February 2016

scikit cosine_similarity vs pairwise_distances

What is the difference between Scikit-learn's sklearn.metrics.pairwise.cosine_similarity and sklearn.metrics.pairwise.pairwise_distances(.. metric="cosine")?

from sklearn.feature_extraction.text import TfidfVectorizer

documents = (
    "Macbook Pro 15' Silver Gray with Nvidia GPU",
    "Macbook GPU"    

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(documents)

from sklearn.metrics.pairwise import cosine_similarity
print(cosine_similarity(tfidf_matrix[0:1], tfidf_matrix)[0,1])


from sklearn.metrics.pairwise import pairwise_distances
print(pairwise_distances(tfidf_matrix[0:1], tfidf_matrix, metric='cosine')[0,1])


Why are these different?


Farseer February 2016

From source code documentation:

Cosine distance is defined as 1.0 minus the cosine similarity.

So your result make sense.

Post Status

Asked in February 2016
Viewed 2,825 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life