Python中的关联规则分析:Apriori算法和FP-Growth算法

作者:KAKAKA2024.02.16 20:36浏览量:38

简介:关联规则分析是一种用于发现数据集中项之间的有趣关系的强大工具。在Python中,我们可以使用`mlxtend`和`pyfpgrowth`库来执行关联规则分析。本文将介绍Apriori算法和FP-Growth算法,并通过示例代码展示如何在Python中使用它们。

千帆应用开发平台“智能体Pro”全新上线 限时免费体验

面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用

立即体验

关联规则分析是一种用于发现数据集中项之间的有趣关系的强大工具。在Python中,我们可以使用mlxtendpyfpgrowth库来执行关联规则分析。本文将介绍Apriori算法和FP-Growth算法,并通过示例代码展示如何在Python中使用它们。

Apriori算法是一种基于频繁项集的关联规则挖掘算法。它使用候选项集生成频繁项集,然后使用频繁项集生成关联规则。Apriori算法的主要思想是通过不断减少候选项集的数量来生成频繁项集。

首先,我们需要安装mlxtend库。可以通过以下命令使用pip安装:

  1. pip install mlxtend

然后,我们可以使用以下代码示例来演示如何在Python中使用Apriori算法:

  1. import pandas as pd
  2. from mlxtend.preprocessing import TransactionEncoder
  3. from mlxtend.frequent_patterns import apriori, association_rules
  4. # 示例数据集
  5. dataset = [['牛奶', '面包', '黄油'],
  6. ['牛奶', '面包', '果酱'],
  7. ['牛奶', '面包', '黄油', '果酱'],
  8. ['牛奶', '面包', '黄油', '鸡蛋'],
  9. ['牛奶', '面包', '果酱', '鸡蛋']]
  10. # 将数据集转换为矩阵格式
  11. te = TransactionEncoder()
  12. te_ary = te.fit(dataset).transform(dataset)
  13. df = pd.DataFrame(te_ary, columns=te.columns_)
  14. # 使用Apriori算法生成频繁项集
  15. frequent_itemsets = apriori(df, min_support=0.5, use_colnames=True)
  16. # 生成关联规则
  17. rules = association_rules(frequent_itemsets, metric='confidence', min_threshold=0.7)
  18. # 打印关联规则
  19. print(rules)

在上面的代码中,我们首先将数据集转换为矩阵格式,然后使用apriori函数生成频繁项集。我们可以通过调整min_support参数来控制频繁项集的最小支持度。然后,我们使用association_rules函数生成关联规则,并使用metricmin_threshold参数来控制关联规则的度量和阈值。最后,我们打印出关联规则。

除了Apriori算法,还有另一种流行的关联规则挖掘算法是FP-Growth算法。FP-Growth算法是一种更高效的方法,因为它使用了频繁模式树(FP-Tree)来存储频繁项集,从而避免了生成候选项集的过程。在Python中,我们可以使用pyfpgrowth库来实现FP-Growth算法。首先,我们需要安装该库。可以通过以下命令使用pip安装:

  1. pip install pyfpgrowth

然后,我们可以使用以下代码示例来演示如何在Python中使用FP-Growth算法:

```python
import pandas as pd
import pyfpgrowth

示例数据集

dataset = [[‘牛奶’, ‘面包’, ‘黄油’],
[‘牛奶’, ‘面包’, ‘果酱’],
[‘牛奶’, ‘面包’, ‘黄油’, ‘果酱’],
[‘牛奶’, ‘面包’, ‘黄油’, ‘鸡蛋’],
[‘牛奶’, ‘面包’, ‘果酱’, ‘鸡蛋’]]

将数据集转换为矩阵格式

items = set([item for sublist in dataset for item in sublist])
transactions = [[items.index(item) for item in sublist] for sublist in dataset]
df = pd.DataFrame(transactions, columns=[‘TransactionID’, ‘Items’])
df[‘Items’] = df[‘Items’].apply(lambda x: ‘,’.join(map(str, x))) # convert back to string representation for pyfpgrowth library to read it correctly (it reads string as individual items)
df[‘TransactionID’] = df[‘TransactionID’].astype(int) # convert TransactionID to integer type for pyfpgrowth library to read it correctly
dataset = df.values.tolist() # convert the DataFrame to a list of lists
support = 0.5 # minimum support threshold for an itemset to be considered frequent 0.

article bottom image

相关文章推荐

发表评论