math库实现
import numpy as np
import math
def cosine_similarity(vec1, vec2) -> float:
norm_vec1, norm_vec2 = 0, 0
dot_product = 0
for v1, v2 in zip(vec1, vec2):
dot_product += v1 * v2
norm_vec1 += v1 * v1
norm_vec2 += v2 * v2
norm_vec1 = math.sqrt(norm_vec1)
norm_vec2 = math.sqrt(norm_vec2)
return dot_product / (norm_vec1 * norm_vec2)
if __name__ == '__main__':
print(cosine_similarity([1, 2, 3], [-1, -2, -3]))
numpy实现
import numpy as np
def cosine_similarity(vec1, vec2) -> float:
norm_vec1 = np.linalg.norm(vec1)
norm_vec2 = np.linalg.norm(vec2)
return np.dot(vec1, vec2) / (norm_vec1 * norm_vec2)
if __name__ == '__main__':
print(cosine_similarity([1, 2, 3], [1, 2, 3]))
pytorch实现
import torch
import torch.nn.functional as F
vec1 = torch.FloatTensor([1, 2, 3, 4])
vec2 = torch.FloatTensor([5, 6, 7, 8])
cos_sim = F.cosine_similarity(vec1, vec2, dim=0)
print(cos_sim)