DM-exp-2/code/5-6_cal_apriori.py
fly6516 6298c14f78 perf(code): 添加算法运行时间计时并更换数据集
- 在 Apriori 和 FP-Growth算法运行前后添加时间计时代码
- 将输入数据集从 menu_orders.xls 更改为 iris.csv
- 更新数据读取方式以适应 CSV 文件格式
-保留算法结果并输出运行时间
2025-03-14 11:40:29 +08:00

30 lines
1.3 KiB
Python
Raw Permalink 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函数
import time # 导入time模块用于计时
inputfile = '../data/iris.csv'
outputfile = '../tmp/apriori_rules.xlsx' #结果文件,保留 .xlsx 格式
data = pd.read_csv(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
start_time = time.time() # 记录开始时间
result = find_rule(data, support, confidence, ms)
end_time = time.time() # 记录结束时间
print(f'\nApriori算法运行时间: {end_time - start_time}')
result.to_excel(outputfile, engine='openpyxl') #保存结果,指定 engine='openpyxl'