方法1
from math import sqrt
import numpy as np
def similarity(v1, v2):
a=sqrt( np.dot(v1, v1))
b=sqrt ( np.dot(v2, v2))
if a==0 or b==0:
return -1
cos_dis=np.dot (v1, v2) / (b * a)
print('cos:',cos_dis)
return cos_dis
v1=np.array([1,2,3,4])
v2=np.array([1,2,2,3])
print(similarity(v1,v2))
方法2
import time
from sklearn.metrics.pairwise import cosine_similarity
a = [[1, 1], [1, 0.8]]
start = time.time()
#cosine_similarity 出来是对称矩阵,只需要取[0][1]就ok了
print("1111",time.time() - start, cosine_similarity([[1,2,3,4],[1,2,2,3]])[0][1])
方法3
def cos_sim(vector_a, vector_b):
"""
计算两个向量之间的余弦相似度
:param vector_a: 向量 a
:param vector_b: 向量 b
:return: sim
"""
vector_a = np.mat(vector_a)