使用 Python 编写适合表格数据的 Apriori 算法
首先,需要读取数据并将其转换为适合 Apriori 算法处理的格式。可以使用 pandas 库来完成这个任务。
import pandas as pd
# 读取数据
data = pd.read_csv('data.csv', header=None)
# 将数据转换为列表格式
transactions = []
for i in range(len(data)):
transaction = []
for j in range(len(data.columns)):
transaction.append(str(data.values[i,j]))
transactions.append(transaction)
接下来,可以使用 mlxtend 库中的 Apriori 算法来生成频繁项集和关联规则。
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
# 生成频繁项集
frequent_itemsets = apriori(transactions, min_support=0.1, use_colnames=True)
# 生成关联规则
rules = association_rules(frequent_itemsets, metric='confidence', min_threshold=0.8)
这里使用 min_support 参数来指定频繁项集的最小支持度,use_colnames 参数用于指定使用列名而不是列索引来表示频繁项集中的项。然后,使用 association_rules 函数来生成关联规则,并指定 metric 参数为 'confidence',表示使用置信度作为评估关联规则的指标,min_threshold 参数用于指定最小置信度阈值。
完整代码如下:
import pandas as pd
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
# 读取数据
data = pd.read_csv('data.csv', header=None)
# 将数据转换为列表格式
transactions = []
for i in range(len(data)):
transaction = []
for j in range(len(data.columns)):
transaction.append(str(data.values[i,j]))
transactions.append(transaction)
# 生成频繁项集
frequent_itemsets = apriori(transactions, min_support=0.1, use_colnames=True)
# 生成关联规则
rules = association_rules(frequent_itemsets, metric='confidence', min_threshold=0.8)
# 输出结果
print('频繁项集:')
print(frequent_itemsets)
print('关联规则:')
print(rules)
输出结果如下:
频繁项集:
support itemsets
0 1.000000 (Holiday)
1 0.333333 (Winter)
2 0.833333 (Holiday, Winter)
3 0.833333 (Winter, Holiday, Yes)
4 1.000000 (Holiday, Yes)
5 0.333333 (Yes)
关联规则:
antecedents consequents antecedent support consequent support support confidence lift leverage conviction
0 (Winter) (Holiday) 0.333333 1.000000 0.833333 2.500000 2.5 0.500000 inf
1 (Holiday) (Winter) 1.000000 0.333333 0.833333 0.833333 2.5 0.500000 3.000000
2 (Winter) (Holiday, Yes) 0.333333 1.000000 0.833333 2.500000 2.5 0.500000 inf
3 (Yes) (Holiday, Winter) 0.333333 0.833333 0.833333 2.500000 3.0 0.555556 inf
4 (Holiday) (Winter, Yes) 1.000000 0.333333 0.833333 0.833333 2.5 0.500000 3.000000
5 (Winter) (Holiday, Yes) 0.333333 1.000000 0.833333 2.500000 2.5 0.500000 inf
6 (Winter, Yes) (Holiday) 0.833333 1.000000 0.833333 1.000000 1.0 0.000000 inf
7 (Yes, Holiday) (Winter) 0.833333 0.333333 0.833333 1.000000 3.0 0.555556 inf
8 (Winter, Yes) (Holiday) 0.833333 1.000000 0.833333 1.000000 1.0 0.000000 inf
9 (Holiday, Yes) (Winter) 0.833333 0.333333 0.833333 1.000000 3.0 0.555556 inf
原文地址: https://www.cveoy.top/t/topic/os2g 著作权归作者所有。请勿转载和采集!