Python计算余弦相似度

import numpy as np


def cosine_similarity(a, b):
    """
    计算向量a和向量b的余弦相似度
    """
    dot_product = np.dot(a, b)  # 向量点积
    norm_a = np.linalg.norm(a)  # 向量a的范数
    norm_b = np.linalg.norm(b)  # 向量b的范数
    return dot_product / (norm_a * norm_b)


def cosine_similarity_multi(a, b_multi):
    """
    计算向量a和多个向量的余弦相似度
    """
    b_multi = np.array(b_multi)
    similarities = np.dot(b_multi, a) / (np.linalg.norm(b_multi, axis=1) * np.linalg.norm(a))
    return similarities.tolist()


if __name__ == '__main__':
    a = np.array([1, 2, 3])
    b_multi = [np.array([3, 4, 5]), np.array([-1, -2, -3]), np.array([2, 4, 6])]
    similarities = cosine_similarity_multi(a, b_multi)
    print(similarities)

你可能感兴趣的:(python,python,numpy)