Calculate cosine similarity of two matrices

Nilani Algiriyage picture Nilani Algiriyage · Feb 24, 2014 · Viewed 16.4k times · Source

I have defined two matrices like following:

from scipy import linalg, mat, dot
a = mat([-0.711,0.730])
b = mat([-1.099,0.124])

Now, I want to calculate the cosine similarity of these two matrices. What is the wrong with following code. It gives me an error of objects are not aligned

c = dot(a,b)/np.linalg.norm(a)/np.linalg.norm(b)

Answer

lejlot picture lejlot · Feb 24, 2014

You cannot multiply 1x2 matrix by 1x2 matrix. In order to calculate dot product between their rows the second one has to be transposed.

from scipy import linalg, mat, dot
a = mat([-0.711,0.730])
b = mat([-1.099,0.124])

c = dot(a,b.T)/linalg.norm(a)/linalg.norm(b)