方法一:
def cos(vector1,vector2):
dot_product = 0.0
normA = 0.0
normB = 0.0
for a,b in zip(vector1,vector2):
dot_product += a*b
normA += a**2
normB += b**2
if normA == 0.0 or normB==0.0:
return None
else:
return 0.5 + 0.5 * dot_product / ((normA*normB)**0.5) #归一化 <span style="font-family: Arial, Helvetica, sans-serif;">从[-1,1]到[0,1]</span>
方法二:
num = float(A.T * B) #若为行向量则 A * B.T
denom = linalg.norm(A) * linalg.norm(B)
cos = num / denom #余弦值
sim = 0.5 + 0.5 * cos #归一化 从[-1,1]到[0,1]
来源:
http://www.tuicool.com/articles/yaeiUj
个人觉得方法一较为简洁易懂,方法二不清楚A.T是什么含义