关联规则apriori算法实现一段代码
时间: 2023-09-14 12:12:04 浏览: 87
关联规则挖掘算法apriori算法的实现
下面是一个简单的 Python 实现 Apriori 算法的示例代码:
```python
def load_dataset():
# 构建数据集
dataset = [[1, 2, 3], [1, 3, 4], [2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5],
[1, 2, 3, 6], [1, 2, 4, 5], [1, 2, 4, 6], [1, 3, 4, 5], [1, 3, 4, 6]]
return dataset
def create_C1(dataset):
# 生成候选1-项集
C1 = []
for transaction in dataset:
for item in transaction:
if not [item] in C1:
C1.append([item])
C1.sort()
return list(map(frozenset, C1))
def scan_D(D, Ck, min_support):
# 计算支持度
ss_cnt = {}
for tid in D:
for can in Ck:
if can.issubset(tid):
if not can in ss_cnt:
ss_cnt[can] = 1
else:
ss_cnt[can] += 1
num_items = float(len(D))
ret_list = []
support_data = {}
for key in ss_cnt:
support = ss_cnt[key] / num_items
if support >= min_support:
ret_list.insert(0, key)
support_data[key] = support
return ret_list, support_data
def aprioriGen(Lk, k):
# 连接步
ret_list = []
len_Lk = len(Lk)
for i in range(len_Lk):
for j in range(i + 1, len_Lk):
L1 = list(Lk[i])[:k - 2]
L2 = list(Lk[j])[:k - 2]
L1.sort()
L2.sort()
if L1 == L2:
ret_list.append(Lk[i] | Lk[j])
return ret_list
def apriori(dataset, min_support=0.5):
# Apriori 算法主函数
C1 = create_C1(dataset)
D = list(map(set, dataset))
L1, support_data = scan_D(D, C1, min_support)
L = [L1]
k = 2
while len(L[k - 2]) > 0:
Ck = aprioriGen(L[k - 2], k)
Lk, support_k = scan_D(D, Ck, min_support)
support_data.update(support_k)
L.append(Lk)
k += 1
return L, support_data
```
这段代码实现了 Apriori 算法的主要步骤,包括生成候选1-项集、计算支持度、连接步和剪枝步等。具体来说,`load_dataset` 函数用于构建数据集,`create_C1` 函数用于生成候选1-项集,`scan_D` 函数用于计算支持度,`aprioriGen` 函数用于进行连接步,`apriori` 函数是 Apriori 算法的主函数,用于迭代生成频繁项集。最后,`apriori` 函数返回频繁项集列表和支持度字典。
阅读全文