Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])

0.37997836

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

0.62002164

Why are these different?

like image 824
Nick Lothian Avatar asked Feb 09 '16 00:02

Nick Lothian


2 Answers

From source code documentation:

Cosine distance is defined as 1.0 minus the cosine similarity.

So your result make sense.

like image 156
Farseer Avatar answered Sep 20 '22 02:09

Farseer


pairwise distance provide distance between two array.so more pairwise distance means less similarity.while cosine similarity is 1-pairwise_distance so more cosine similarity means more similarity between two arrays.

like image 27
Utsav Patel Avatar answered Sep 19 '22 02:09

Utsav Patel