Python 在找到余弦相似性后重新构建数组
我有一个数据框架,其中包含工作职业作为主要变量,对于每个职业,它是构成一份工作的一系列技能。我试图用余弦作为距离度量来找出作业之间的余弦相似性。到目前为止,我设法得到了余弦矩阵/数组,但是我无法将此数组作为包含职业之间相似性的数据帧返回。请看下面的数据集示例,我到目前为止一直在使用的代码,以及我希望得到的预期结果 数据集Python 在找到余弦相似性后重新构建数组,python,pandas,trigonometry,Python,Pandas,Trigonometry,我有一个数据框架,其中包含工作职业作为主要变量,对于每个职业,它是构成一份工作的一系列技能。我试图用余弦作为距离度量来找出作业之间的余弦相似性。到目前为止,我设法得到了余弦矩阵/数组,但是我无法将此数组作为包含职业之间相似性的数据帧返回。请看下面的数据集示例,我到目前为止一直在使用的代码,以及我希望得到的预期结果 数据集 INDEX 3D studio Accountancy Cooking 3d modeling 1
INDEX 3D studio Accountancy Cooking
3d modeling 1 0 0
IC auditor 0 1 0
Chef 0 1 0
应用余弦相似
结果以数组的形式出现
0 1 2 3
1 1 0 0
2 0 1 0.65
3 0 0.65 1
如何将其转换为成对比较格式,我曾尝试使用concat和Reforme,但失败了
理想的结果是:
注意-矩阵非常大,这个余弦分数是虚构的。我认为需要
DataFrame
构造函数,指定列和索引,然后通过以下方式重塑:
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
你能不能再确认一下你的例子,厨师在3d建模方面的得分是0.65?从生成的数组中,我猜它是0,在这种情况下,您只需读取行/列即可获得所需的结果。@Eulenfuchswiesel,hi和tks以获得快速回复。。。分数是虚构的,有2950种不同的可能技能类型。我得到了一个数组float64作为余弦的结果,我想把真正的变量名作为一对,tks很多。。。由于数据的性质,我不得不做一些小改动。
Occ_s Occ_T Score
3d modeling 3d modeling 1
3d modeling IC auditor 0
3d modeling Chef 0.65
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
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