Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
21
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@Qiitaman

【Python NumPy】コサイン類似度の求め方

算出式

download.png

具体例

X(vector) Y(vector)
属性値a 0.789 0.832
属性値b 0.515 0.555
属性値c 0.335 0
属性値d 0 0
cos(X, Y) = (0.789 × 0.832) + (0.515 × 0.555) + (0.335 × 0) + (0 × 0) ≒ 0.942

対応コード

関数

import numpy as np

def cos_sim(v1, v2):
    return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))

実行

X = np.array([0.789, 0.515, 0.335,0])
Y = np.array([0.832, 0.555,0,0])

# cos(X,Y) = (0.789×0.832)+(0.515×0.555)+(0.335×0)+(0×0)≒0.942
print(cos_sim(X, Y))  #=> 0.9421693704700748
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
21
Help us understand the problem. What are the problem?