使用jaccard相似性的Python Pandas距离矩阵

时间:2016-02-25 22:21:00

标签: python pandas matrix scipy

我已经实现了一个使用jaccard相似性构建距离矩阵的函数:

import pandas as pd
entries = [
    {'id':'1', 'category1':'100', 'category2': '0', 'category3':'100'},
    {'id':'2', 'category1':'100', 'category2': '0', 'category3':'100'},
    {'id':'3', 'category1':'0', 'category2': '100', 'category3':'100'},
    {'id':'4', 'category1':'100', 'category2': '100', 'category3':'100'},
    {'id':'5', 'category1':'100', 'category2': '0', 'category3':'100'}
           ]
df = pd.DataFrame(entries)

和scipy的距离矩阵

from scipy.spatial.distance import squareform
from scipy.spatial.distance import pdist, jaccard

res = pdist(df[['category1','category2','category3']], 'jaccard')
squareform(res)
distance = pd.DataFrame(squareform(res), index=df.index, columns= df.index)

问题是我的结果看起来像是假的:

enter image description here

我缺少什么?例如,0和1的相似性必须是最大值,而其他值似乎也是错误的

1 个答案:

答案 0 :(得分:6)

查看文档,scipy.spatial.distancejaccard的实现是jaccard 不相似,而非相似性。这是使用jaccard作为度量时计算距离的常用方法。这样做的原因是,为了成为度量,相同点之间的距离必须为零。

在你的代码中,应该最小化0和1之间的相异性。其他值在不相似的背景下看起来也是正确的。

如果你想要相似性而不是相异性,只需从1中减去相似性。

res = 1 - pdist(df[['category1','category2','category3']], 'jaccard')
相关问题