简体   繁体   中英

How to calculate pairwise cosine distance of matrix using broadcasting in python

I have a matrix like this where each row is a vector and need to calculate pairwise cosine distance between the vectors (in this example, as a 2x2 matrix) without using loops? I understand for cartesian distance one can pad up a dimension but don't know the best method here.

m = np.array([[1, 3, 5],[2,6,10]])

This type of question will get you berated with "Stack isn't for homework" but I guess you could just do this...

from numpy import linalg as LA
import numpy as np
m = np.array([[1, 3, 5],[2,6,10]])
cos = float(sum(m[0]*m[1]))/float(LA.norm(m[0])*LA.norm(m[1]))

of course if you wanted to avoid using linlag

float(sum(m[0]*m[1]))/(float(sum(m[0]*m[0]))**0.5*float(sum(m[1]*m[1]))**0.5)

See link -> https://en.wikipedia.org/wiki/Cosine_similarity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM