Cosine Similarity

user238384 picture user238384 · Jan 4, 2010 · Viewed 15.9k times · Source

I calculated tf/idf values of two documents. The following are the tf/idf values:

1.txt
0.0
0.5
2.txt
0.0
0.5

The documents are like:

1.txt = > dog cat
2.txt = > cat elephant

How can I use these values to calculate cosine similarity?

I know that I should calculate the dot product, then find distance and divide dot product by it. How can I calculate this using my values?

One more question: Is it important that both documents should have same number of words?

Answer

Yin Zhu picture Yin Zhu · Jan 4, 2010
            a * b
sim(a,b) =--------
           |a|*|b|

a*b is dot product

some details:

def dot(a,b):
  n = length(a)
  sum = 0
  for i in xrange(n):
    sum += a[i] * b[i];
  return sum

def norm(a):
  n = length(a)
  for i in xrange(n):
    sum += a[i] * a[i]
  return math.sqrt(sum)

def cossim(a,b):
  return dot(a,b) / (norm(a) * norm(b))

yes. to some extent, a and b must have the same length. but a and b usually have sparse representation, you only need to store non-zero entries and you can calculate norm and dot more fast.