0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonでコサイン類似性(Cosine Similarity)計算のまとめ

Last updated at Posted at 2024-11-15

scikit-learn

from sklearn.metrics.pairwise import cosine_similarity 
import numpy as np 

a = [2, 15, 3, 25] 
b = [5, 25, 8, 28] 

array_1 = np.array([a]) 
array_2 = np.array([b]) 
cos_sim = cosine_similarity(array_1 , array_2) 
print(cos_sim) 
# 結果: 
# [[0.9753719]] 

NumPy

from numpy import dot 
from numpy.linalg import norm 

a = [2, 15, 3, 25] 
b = [5, 25, 8, 28] 

cos_sim = dot(a, b) / (norm(a) * norm(b)) 
print(cos_sim) 
# 結果: 
# 0.9753719044721808 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?