找到余弦相似度后

时间:2018-08-06 07:58:17

标签: python pandas cosine

我有一个数据框,其中包含工作职业作为主要变量,每个职业都是一整套构成工作的技能。我试图使用余弦作为距离度量来找到作业之间的余弦相似度。到目前为止,我设法达到了余弦矩阵/数组,但是我无法将此数组作为包含职业之间相似性的数据框返回。请在下面查看数据集示例,到目前为止我一直在使用的代码以及我希望获得的预期结果。

数据集

INDEX           3D studio      Accountancy       Cooking      

3d modeling         1               0               0
IC auditor          0               1               0
Chef                0               1               0

应用余弦相似度

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

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

结果采用数组形式

 0    1       2       3 
 1    1       0       0
 2    0       1       0.65
 3    0       0.65    1

如何将其转换为成对比较格式,我曾尝试使用concat和reshape,但失败了。

理想的结果是:

Occ_s          Occ_T            Score
3d modeling    3d modeling        1
3d modeling    IC auditor         0 
3d modeling    Chef               0.65

注意-矩阵很大,这个余弦分数是虚拟的。

1 个答案:

答案 0 :(得分:1)

我认为需要DataFrame构造函数并指定列和索引,然后通过stack进行整形:

dist_out = 1-pairwise_distances(data_k_T, metric="cosine")
print (dist_out)
[[1. 0. 0.]
 [0. 1. 1.]
 [0. 1. 1.]]

df = pd.DataFrame(dist_out, index=data_k_T.index, columns=data_k_T.columns)
print (df)
             3Dstudio  Accountancy  Cooking
3d modeling       1.0          0.0      0.0
IC auditor        0.0          1.0      1.0
Chef              0.0          1.0      1.0

out = df.stack(0).reset_index()
out.columns = ['Occ_s','Occ_T','Score']
print (out)
         Occ_s        Occ_T  Score
0  3d modeling     3Dstudio    1.0
1  3d modeling  Accountancy    0.0
2  3d modeling      Cooking    0.0
3   IC auditor     3Dstudio    0.0
4   IC auditor  Accountancy    1.0
5   IC auditor      Cooking    1.0
6         Chef     3Dstudio    0.0
7         Chef  Accountancy    1.0
8         Chef      Cooking    1.0

Numpy解决方案:

a = np.repeat(data_k_T.index, len(data_k_T.columns))
b = np.tile(data_k_T.columns, len(data_k_T))
c = dist_out.ravel()

out = pd.DataFrame({'Occ_s':a, 'Occ_T':b, 'Score':c})
print (out)
         Occ_s        Occ_T  Score
0  3d modeling     3Dstudio    1.0
1  3d modeling  Accountancy    0.0
2  3d modeling      Cooking    0.0
3   IC auditor     3Dstudio    0.0
4   IC auditor  Accountancy    1.0
5   IC auditor      Cooking    1.0
6         Chef     3Dstudio    0.0
7         Chef  Accountancy    1.0
8         Chef      Cooking    1.0
相关问题