使用Python进行关联规则挖掘通常涉及以下步骤:
准备数据
使用`pandas`库加载数据,并将其转换为适合关联规则算法的格式,如List of Lists。
使用关联规则算法
可以使用`mlxtend`库中的`apriori`函数实现Apriori算法来找出频繁项集。
设置最小支持度(`min_support`)、最小置信度(`min_confidence`)等参数来过滤规则。
使用`association_rules`函数提取关联规则。
```python
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules
import pandas as pd
构建数据集
data = [['牛奶', '面包', '啤酒'],
['奶酪', '面包', '黄油'],
['牛奶', '面包', '黄油', '鸡蛋'],
['奶酪', '黄油', '鸡蛋'],
['面包', '啤酒']]
转换为算法可接受的模型(布尔值)
te = TransactionEncoder()
df_tf = te.fit_transform(data)
df = pd.DataFrame(df_tf, columns=te.columns_)
设置支持度求频繁项集
frequent_itemsets = apriori(df, min_support=0.6, use_colnames=True)
输出频繁项集
print(frequent_itemsets)
提取关联规则
rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.7)
输出关联规则
print(rules)
在这个示例中,我们首先定义了一个数据集,然后使用`apriori`函数挖掘频繁项集,并设置最小支持度为0.6。接着,我们使用`association_rules`函数提取关联规则,并设置最小置信度为0.7。
请根据您的具体数据集调整参数,并运行代码以查看关联规则的结果