DM-exp-2/code/5-6_cal_apriori.py
fly6516 6e9c2a5f91 feat(code): 添加 Apriori 和 FP-Growth 算法实现
- 新增 Apriori算法挖掘关联规则的实现
- 新增 FP-Growth算法挖掘频繁项集的实现
- 添加相应的数据预处理和结果保存代码
- 优化代码结构,提高可读性和可维护性
2025-03-12 16:31:10 +08:00

24 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#-*- coding: utf-8 -*-
#使用Apriori算法挖掘菜品订单关联规则
from __future__ import print_function
import pandas as pd
from apriori import * #导入自行编写的apriori函数
inputfile = '../data/menu_orders.xls'
outputfile = '../tmp/apriori_rules.xlsx' #结果文件,保留 .xlsx 格式
data = pd.read_excel(inputfile, header = None)
print(u'\n转换原始数据至0-1矩阵...')
ct = lambda x : pd.Series(1, index = x[pd.notnull(x)]) #转换0-1矩阵的过渡函数
b = map(ct, data.iloc[:,:].values) #用map方式执行
data = pd.DataFrame(list(b)).fillna(0) #实现矩阵转换空值用0填充
print(u'\n转换完毕。')
del b #删除中间变量b节省内存
support = 0.2 #最小支持度
confidence = 0.5 #最小置信度
ms = '---' #连接符,默认'--'用来区分不同元素如A--B。需要保证原始表格中不含有该字符
# 提醒用户需要安装 openpyxl 库以支持 .xlsx 格式
# 如果未安装可以通过以下命令安装pip install openpyxl
find_rule(data, support, confidence, ms).to_excel(outputfile, engine='openpyxl') #保存结果,指定 engine='openpyxl'