创建余弦相似矩阵numpy

时间:2017-01-28 00:13:46

标签: python numpy matrix cosine-similarity

假设我有一个如下所示的numpy矩阵:

array([array([ 0.0072427 ,  0.00669255,  0.00785213,  0.00845336,  0.01042869]),
   array([ 0.00710799,  0.00668831,  0.00772334,  0.00777796,  0.01049965]),
   array([ 0.00741872,  0.00650899,  0.00772273,  0.00729002,  0.00919407]),
   array([ 0.00717589,  0.00627021,  0.0069514 ,  0.0079332 ,  0.01069545]),
   array([ 0.00617369,  0.00590539,  0.00738468,  0.00761699,  0.00886915])], dtype=object)

如何生成一个5 x 5矩阵,其中矩阵的每个索引都是我原始矩阵中两个相应行的余弦相似度?

e.g。第0行第2列的值将是原始矩阵中第1行和第3行之间的余弦相似度。

这是我尝试过的:

from sklearn.metrics import pairwise_distances
from scipy.spatial.distance import cosine
import numpy as np

#features is a column in my artist_meta data frame
#where each value is a numpy array of 5 floating point values, similar to the
#form of the matrix referenced above but larger in volume

items_mat = np.array(artist_meta['features'].values)

dist_out = 1-pairwise_distances(items_mat, metric="cosine")

上面的代码给出了以下错误:

ValueError:使用序列设置数组元素。

我不知道为什么我得到这个,因为每个数组都有相同的长度(5),我已经验证了。

2 个答案:

答案 0 :(得分:4)

m成为数组

m = np.array([
        [ 0.0072427 ,  0.00669255,  0.00785213,  0.00845336,  0.01042869],
        [ 0.00710799,  0.00668831,  0.00772334,  0.00777796,  0.01049965],
        [ 0.00741872,  0.00650899,  0.00772273,  0.00729002,  0.00919407],
        [ 0.00717589,  0.00627021,  0.0069514 ,  0.0079332 ,  0.01069545],
        [ 0.00617369,  0.00590539,  0.00738468,  0.00761699,  0.00886915]
    ])

per wikipedia: Cosine_Similarity
enter image description here

我们可以用

计算分子
d = m.T @ m

我们的‖A‖

norm = (m * m).sum(0, keepdims=True) ** .5

然后是相似之处

d / norm / norm.T

[[ 1.      0.9994  0.9979  0.9973  0.9977]
 [ 0.9994  1.      0.9993  0.9985  0.9981]
 [ 0.9979  0.9993  1.      0.998   0.9958]
 [ 0.9973  0.9985  0.998   1.      0.9985]
 [ 0.9977  0.9981  0.9958  0.9985  1.    ]]

距离

1 - d / norm / norm.T

[[ 0.      0.0006  0.0021  0.0027  0.0023]
 [ 0.0006  0.      0.0007  0.0015  0.0019]
 [ 0.0021  0.0007  0.      0.002   0.0042]
 [ 0.0027  0.0015  0.002   0.      0.0015]
 [ 0.0023  0.0019  0.0042  0.0015  0.    ]]

答案 1 :(得分:1)

x成为您的数组

from scipy.spatial.distance import cosine

m, n = x.shape
distances = np.zeros((m,n))
for i in range(m):
    for j in range(n):
        distances[i,j] = cosine(x[i,:],x[:,j])