【问题标题】:Compute cosine similarity between 3D numpy array and 2D numpy array计算 3D numpy 数组和 2D numpy 数组之间的余弦相似度
【发布时间】:2018-10-02 20:31:56
【问题描述】:

我有一个形状为 (m, n, 300) 的 3D numpy 数组 A 和一个形状为 (p, 300) 的 2D numpy 数组 B。

对于 3D 数组中的每个 m (n, 300) 个矩阵,我想用 2D numpy 数组计算其余弦相似度矩阵。目前,我正在执行以下操作:

result = []
for sub_matrix in A:
    result.append(sklearn.metrics.pairwise.cosine_similarity(sub_matrix, B)

sklearn cosine_similarity 函数不支持对 3D 数组的运算,那么有没有更有效的计算方法而不涉及使用 for 循环?

【问题讨论】:

  • 等一下,结果中你想要多少个输出。你能想出一个MCVE吗?如果你知道你在做什么,你可以绕过 sklearn 并自己实现它。

标签: python numpy scikit-learn similarity cosine-similarity


【解决方案1】:

你可以重塑为2D并使用相同的功能-

from sklearn.metrics.pairwise import cosine_similarity

m,n = A.shape[:2]
out = cosine_similarity(A.reshape(m*n,-1), B).reshape(m,n,-1)

最后reshape 后的输出将是3D,这是result 数组转换后的结果。

示例运行 -

In [336]: np.random.seed(0)
     ...: A = np.random.rand(5,4,3)
     ...: B = np.random.rand(2,3)
     ...: 
     ...: result = []
     ...: for sub_matrix in A:
     ...:     result.append(cosine_similarity(sub_matrix, B))
     ...: out_org = np.array(result)
     ...: 
     ...: from sklearn.metrics.pairwise import cosine_similarity
     ...: 
     ...: m,n = A.shape[:2]
     ...: out = cosine_similarity(A.reshape(m*n,-1), B).reshape(m,n,-1)
     ...: 
     ...: print np.allclose(out_org, out)
True

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 2018-08-19
    • 2015-08-04
    相关资源
    最近更新 更多