Calculate cosine similarity of two matrices
Asked Answered
E

2

5

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)
Electrosurgery answered 24/2, 2014 at 6:42 Comment(0)
L
9

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)
Loden answered 24/2, 2014 at 6:55 Comment(2)
Thanks lejlot! I'm new to this angle computation. Is it(cosine angle) just a single value?Electrosurgery
Cosine similarity is simply the cosine of an angle between two given vectors, so it is a number between -1 and 1. If you, however, use it on matrices (as above) and a and b have more than 1 rows, then you will get a matrix of all possible cosines (between each pair of rows between these matrices).Loden
U
6

also:

import numpy as np
import scipy.spatial.distance as distance
a = np.array([0.1, 0.2])
b = np.array([0.3,0.4])
c = 1 - distance.cosine(a, b)

see: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cosine.html#scipy.spatial.distance.cosine

Unasked answered 17/5, 2017 at 7:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.