By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,312 Members | 1,877 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,312 IT Pros & Developers. It's quick & easy.

Computation of cosine similarity over a list of values using python

P: 11
Below are my code lines for computing cosine similarity over a list of values. My goal is to compute the cosine similarity by comparing each value in the f-list( f=[[3492.6], [13756.2], [22442.1], [22361.9], [26896.4]]) with the rest values and output their similarity scores. However, for some reasons, I keep getting 1.0 as the cosine similarity even when I tested the code on other data sets. Obviously, [22361.9] is more similar to [22442.1] than [13756.2]. I just want take one value from the list and compute how close in terms of cosine distance the rest values in the list are from it. Hence the result should be five different similarity scores.

Expand|Select|Wrap|Line Numbers
  1. import numpy.linalg as LA
  2. import numpy as np
  3. import sys
  4. import os
  5. f=[[3492.6], [13756.2], [22442.1], [22361.9], [26896.4]]
  6. cx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 2)
  7. for c in f:
  8.      for i in f:
  9.         cosine=cx(c, i)
  10. print cosine
Any ideas?, many thanks.
Jul 29 '13 #1

✓ answered by bvdet

Apparently the calculations np.inner(a, b) and (LA.norm(a)*LA.norm(b)) are returning the same values.

Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
Apparently the calculations np.inner(a, b) and (LA.norm(a)*LA.norm(b)) are returning the same values.
Jul 29 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.