如何从 pandas 数据帧计算 jaccard 相似度

2023-12-24

我有一个数据框如下:框架的形状是(1510, 1399)。列代表产品,行代表用户为给定产品分配的值(0 或 1)。我怎样才能计算jaccard_similarity_scores?

我创建了一个占位符数据框,列出了产品与产品

data_ibs = pd.DataFrame(index=data_g.columns,columns=data_g.columns)

我不确定如何迭代数据磅来计算相似性。

for i in range(0,len(data_ibs.columns)) :
    # Loop through the columns for each column
    for j in range(0,len(data_ibs.columns)) :
        .........

Use pairwise_distances计算距离并用 1 减去该距离即可找到相似度得分:

from sklearn.metrics.pairwise import pairwise_distances
1 - pairwise_distances(df.T.to_numpy(), metric='jaccard')

解释:

在较新版本的 scikit learn 中,定义jaccard_score类似于 Jaccard 相似系数定义维基百科 https://en.wikipedia.org/wiki/Jaccard_index:

where

  • M11 represents the total number of attributes where A and B both have a value of 1.
  • M01 represents the total number of attributes where the attribute of A is 0 and the attribute of B is 1.
  • M10 represents the total number of attributes where the attribute of A is 1 and the attribute of B is 0.
  • M00 represents the total number of attributes where A and B both have a value of 0.

让我们创建一个示例数据集来查看结果是否匹配:

from pandas import DataFrame, crosstab
from numpy.random import default_rng
rng = default_rng(0)

# Create a dataframe of 40 rows and 5 columns (named A, B, C, D, E)
# Each cell in the DataFrame is either 0 or 1 with 50% probability
df = DataFrame(rng.binomial(1, 0.5, size=(40, 5)), columns=list('ABCDE'))

这将为 A 列和 B 列生成以下交叉表:

A/B 0 1
0 10 7
1 14 9

根据定义,Jaccard 相似度得分为:

M00 = (df['A'].eq(0) & df['B'].eq(0)).sum()  # 10
M01 = (df['A'].eq(0) & df['B'].eq(1)).sum()  # 7
M10 = (df['A'].eq(1) & df['B'].eq(0)).sum()  # 14
M11 = (df['A'].eq(1) & df['B'].eq(1)).sum()  # 9


print(M11 / (M01 + M10 + M11))  # 0.3

这就是你会得到的jaccard_score:

from sklearn.metrics import jaccard_score
print(jaccard_score(df['A'], df['B']))  # 0.3

问题与jaccard_score功能是它不是矢量化的。您必须循环所有列才能计算每个相应列的相似度得分。为了避免这种情况,您可以使用矢量化距离版本。但是,由于它是“距离”而不是“相似度”,因此您需要从 1 中减去该值:

from sklearn.metrics.pairwise import pairwise_distances
print(1 - pairwise_distances(df.T.to_numpy(), metric='jaccard'))

# [[1.         0.3        0.45714286 0.34285714 0.46666667]
#  [0.3        1.         0.29411765 0.33333333 0.23333333]
#  [0.45714286 0.29411765 1.         0.40540541 0.44117647]
#  [0.34285714 0.33333333 0.40540541 1.         0.36363636]
#  [0.46666667 0.23333333 0.44117647 0.36363636 1.        ]]

或者,您可以将其转换回 DataFrame:

jac_sim = 1 - pairwise_distances(df.T.to_numpy(), metric='jaccard')
jac_sim_df = DataFrame(
    1 - pairwise_distances(df.T.to_numpy(), metric='jaccard'), 
    index=df.columns, columns=df.columns,
)

#           A         B         C         D         E
#  A  1.000000  0.300000  0.457143  0.342857  0.466667
#  B  0.300000  1.000000  0.294118  0.333333  0.233333
#  C  0.457143  0.294118  1.000000  0.405405  0.441176
#  D  0.342857  0.333333  0.405405  1.000000  0.363636
#  E  0.466667  0.233333  0.441176  0.363636  1.000000

Note: In the previous version of this answer, the calculations used the hamming metric with pairwise_distances because in earlier versions of scikit-learn, jaccard_score was calculated similar to the accuracy score (i.e. (M00 + M11) / (M00 + M01 + M10 + M11)). That is no longer the case so the answer was updated to use the jaccard metric instead of hamming.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从 pandas 数据帧计算 jaccard 相似度 的相关文章

随机推荐

  • 在函数内部定义全局变量

    像python一样可以在函数内定义全局变量吗 例如 在Python中 def testFunc global testVar testVar 1 有没有办法在函数内的 javascript 中定义 testvar 全局 简单地忽略var关键
  • 在 Imagemagick 中创建空白图像

    如何通过命令行在 Imagemagick 中创建空白的新图像 Using background不起作用 convert size 800x800 background white x png convert no images define
  • Seaborn 头衔位置

    我的图表标题的位置在这方面很糟糕jointplot 我试过移动loc left right and center但它不会从它所在的位置移动 我也尝试过类似的方法ax title set position 3 15 基于该网站的其他建议 但这
  • 为什么 qsort 中的排序方法改变了我的数组?

    https phaxis org 2012 07 12 get sorted index orderting of an array https phoxis org 2012 07 12 get sorted index ordertin
  • 使用 Spring 解码主体参数

    我正在使用 Spring 为 Slack 应用程序开发 REST API 后端 我能够从 Slack 接收消息 斜线命令 但无法正确接收组件交互 按钮单击 The 官方文档 https api slack com docs message
  • 批量回显 URL

    编辑 变量没有正确定义 我不知道为什么 但我找到了解决方法 只需要 6 页 我创建了第 7 页 它将立即返回到第 1 页 因此不再需要 HTMLNxtpg 变量 我正在尝试创建一个批处理文件 它将生成一个 HTML 文件 这样用户就不需要任
  • 寻找干净的 C# WinForms MVC 教程 [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 如何创建丰富的用户界面 Windows 应用程序 例如 Photo Shop 我正在寻找使用 C 的 WinForms 的干净 MVC 教
  • 哪个最适合数据存储结构/类?

    我们在 SO 中看到了很多关于 c 中的类与结构的讨论 大多以结论说它是一个结束堆 栈内存分配 并建议在中使用结构小数据结构 现在我面临着在这两个选择中决定简单数据存储的情况 目前 在我们的应用程序中 我们有数千个类 仅充当简单的数据存储
  • CodeIgniter 辅助函数可以使用数据库函数吗?

    我的 CodeIgniter 控制器函数之一需要调用递归函数作为其功能的一部分 如果我将函数调用放在控制器类中 函数调用就会阻塞 并且它无法访问数据库函数 this gt db gt get 如果我把它放在课堂之外 让它成为辅助函数可以解决
  • 在 UISlider 下添加数字

    我有一个用它实现的 UISliderJQuery UI 我想在显示数字的滑块下添加一个图例 我跟着这个答案 https stackoverflow com a 16877678 4861207它展示了如何实现这一点 然后将数字与百分比值一起
  • Rails:在任何来源中都找不到 minitest-4.7.5

    这里有一个麻烦 在我的远程服务器命令上gem list shows some gems minitest 4 7 5 bundle show minitest命令显示 var lib gems 1 9 1 gems minitest 4 7
  • Javascript:如何重用创建子实例的方法而不创建循环依赖项

    abstract class Fruit private content Fruit addChild Pick one at random using this as an example instead of the actual cr
  • 使用 jquery 从 获取复选框值

    http ghinda net css toggle switch bootstrap html http ghinda net css toggle switch bootstrap html 我使用上面的 css 文件和代码来制作切换开
  • Keras - 历元相关损失函数

    我正在使用 Keras 框架 我想实现一个与纪元相关的损失函数 即每个纪元的损失函数都不相同 你会怎么做 您能否添加一个示例 例如基于keras VAE 教程 https github com fchollet keras blob mas
  • iOS 设备 UDID 区分大小写吗?

    这是关于将设备添加到配置门户以进行临时测试 一个客户给我发了一个带有大写字符的 UDID 我没有检查就愚蠢地添加了它 无线部署不起作用 我想知道这是否是原因 但我想在用完我的 100 个分配之一之前先检查一下 Yes UDIDs区分大小写
  • 为什么 linq-2-sql 会创建额外的不必要的对象?

    我在数据库中有一个简单的父子表 如下所示 CREATE TABLE Parent Id int IDENTITY 1 1 NOT NULL Name nvarchar 256 NOT NULL ALTER TABLE Parent ADD
  • 使用 C# 突出显示 Docx 中的文本

    我需要突出显示 docx 文件中的一个句子 我有这段代码 并且它对于许多文档都可以正常工作 但我注意到对于某些文档 文档中的文本是逐字设置的 而不是整个句子 我的意思是每个单词它自己的Run 所以当搜索该句子时 找不到它 因为它在docx中
  • 使用 Eclipse 部署到 AppEngine 时出错

    每当我尝试将 Web 应用程序部署到 Google App Engine 时 无论女巫应用程序如何 甚至是演示应用程序 我都会遇到此问题 当我尝试部署时立即发生错误 错误是这样说的 部署到 AppEngine 时出错 部署到 App Eng
  • 如何在 Windows 上通过命令行以全屏视图打开 pdf?

    我可以使用以下命令通过命令行打开 pdf 文档 start test pdf 但我想通过命令行以全屏模式打开它 有人知道该怎么做吗 这应该可以做到 start max c nameofpdf pdf 这样做的优点是 如果用户使用非 adob
  • 如何从 pandas 数据帧计算 jaccard 相似度

    我有一个数据框如下 框架的形状是 1510 1399 列代表产品 行代表用户为给定产品分配的值 0 或 1 我怎样才能计算jaccard similarity scores 我创建了一个占位符数据框 列出了产品与产品 data ibs pd