gpt4 book ai didi

python - 创建一个函数来仅使用 numpy 计算二维矩阵中行向量的所有成对余弦相似度

转载 作者:行者123 更新时间:2023-12-04 08:16:31 26 4
gpt4 key购买 nike

例如给定矩阵

array([[ 0,  1,  2,  3,  4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])

它应该返回

array([[1.        , 0.91465912, 0.87845859],
[0.91465912, 1. , 0.99663684],
[0.87845859, 0.99663684, 1. ]])

其中结果的(i, j)项是行向量arr[i]和行向量arr[j之间的余弦相似度]: cos_sim[i, j] == CosSim(arr[i], arr[j]).

和往常一样,两个向量𝑥,𝑦之间的余弦相似度定义为: enter image description here

这个函数应该返回一个形状为 (arr.shape[0], arr.shape[0]) 的 np.ndarray

最佳答案

尝试:

from scipy.spatial.distance import cdist

1 - cdist(a, a, metric='cosine')

输出:

array([[1.        , 0.91465912, 0.87845859],
[0.91465912, 1. , 0.99663684],
[0.87845859, 0.99663684, 1. ]])

关于python - 创建一个函数来仅使用 numpy 计算二维矩阵中行向量的所有成对余弦相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65673687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com