首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >求出余弦相似性后对数组进行重构

求出余弦相似性后对数组进行重构
EN

Stack Overflow用户
提问于 2018-08-06 07:58:16
回答 1查看 87关注 0票数 1

我有一个包含工作职业作为主要变量的数据框架,对于每个职业来说,这是一组组成一份工作的技能。我试图用余弦作为距离度量来寻找工件之间的余弦相似性。到目前为止,我设法得到了余弦矩阵/数组,但是我不能把这个数组作为包含职业之间相似性的数据框架。请参见下面的数据集示例、我迄今使用的代码以及我希望得到的预期结果。

数据集

代码语言:javascript
复制
INDEX           3D studio      Accountancy       Cooking      

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

应用余弦相似

代码语言:javascript
复制
 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")

结果以数组的形式出现。

代码语言:javascript
复制
 0    1       2       3 
 1    1       0       0
 2    0       1       0.65
 3    0       0.65    1

如何把这个变成成对的比较格式,我试着使用连接和整形,但我失败了。

理想的结果是:

代码语言:javascript
复制
Occ_s          Occ_T            Score
3d modeling    3d modeling        1
3d modeling    IC auditor         0 
3d modeling    Chef               0.65

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-06 08:13:34

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

代码语言:javascript
复制
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解决方案:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51703019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档