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

标签 python numpy cosine-similarity

例如给定矩阵

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/

相关文章:

python - Wheel是对其他Python的引用

python - 使用 psycopg2 创建 postgresql 数据库

Python NumPy : replace values in one array with corresponding values in another array

python - ValueError : operands could not be broadcast together with remapped shapes [original->remapped]: (2, 2) 和请求的形状 (3,2)

python - 方程 latex 代码的余弦相似度

nlp - 使用潜在语义分析来测量段落相似度

python - 值错误 : Too many values to unpack Django

python - 如何使用 simplejson 验证 JSON

python - Python中微分方程的并行求解

python - 在 Tensorflow 中计算两组向量的余弦相似度