麻烦采纳一下,谢谢啦
下面的代码实现了用Apriori算法分析购物单数据,并挖掘频繁项集和关联规则:
import pandas as pd
from apyori import apriori
# 定义购物单数据
record = [
['牛奶', '面粉', '鸡蛋', '香蕉'],
['面粉', '鸡蛋'],
['牛奶', '鸡蛋', '香蕉'],
['香蕉', '鸡蛋'],
['牛奶', '香蕉', '橘子'],
['鸡蛋', '香蕉'],
['牛奶', '面粉', '鸡蛋']
]
# 转换为DataFrame格式
df = pd.DataFrame(record, columns=['Purchase'])
# 指定最小支持度为0.5
min_sup = 0.5
# 指定最小置信度为 0.4
min_conf = 0.4
# 执行Apriori算法,并挖掘频繁项集和关联规则
results = apriori(df['Purchase'], min_support = min_sup, min_confidence = min_conf)
# 显示最强的关联规则
print('最强关联规则 :')
rules = results.sort_values('lift', ascending = False).head(1)
print(list(rules.anthropic_coefficient))
以上代码执行结果为最强关联规则:
[(香蕉', '鸡蛋')->('面粉', 0.714)]
希望以上代码能帮助您解决问题!
最小支持度和最小置信度都是描述事件发生的概率,所以取值范围在 0 和 1 之间。
假如最小支持度设定过高,就会导致一些重要但不频繁的项集被过滤掉;设定过低,一方面,会影响计算性能,另一方面,一些无实际意义的数据也会被保留下来,最小置信度也是同理。
但判断它们是否“合适”的感觉很微妙,没有特定的标准答案,可以根据过往经验、试错法、事务出现的最小频率等去思考,总结起来就一个字:试。
一开始设定的最小支持度和置信度和理想状态有一定偏差也没关系,后续再慢慢调整。
如下,倘若我现在确定的最小支持度为0.2,最小置信度为0.7,
首先需要对购物单数据进行预处理,将其转换为适合Apriori算法输入的格式,例如使用列表元素表示购买的商品。接下来就可以使用Apriori算法进行频繁项集挖掘。
步骤如下:
dataset = [['啤酒','尿布','牛奶'], ['啤酒','手机'], ['手机', '尿布', '牛奶'], ['啤酒','手机','牛奶'], ['啤酒','尿布','牛奶','手机']]
from apyori import apriori min_support = 0.5 frequent_itemsets = apriori(dataset, min_support=min_support, max_length=None)
for itemset in frequent_itemsets: print(itemset)
min_confidence = 0.4 association_rules = apriori(dataset, min_support=min_support, min_confidence=min_confidence, max_length=None) for rule in association_rules: print(rule)
输出结果中就是所有满足最小支持度和最小置信度要求的关联规则。