用python代码实现Apriori算法
时间: 2024-05-08 22:17:36 浏览: 110
我可以回答这个问题。Apriori算法是一种频繁项集挖掘算法,可以用于数据挖掘中的关联规则挖掘。以下是一个简单的Python实现:
```python
def load_data():
return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
def create_C1(data_set):
C1 = []
for transaction in data_set:
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 apriori_gen(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(data_set, min_support=0.5):
C1 = create_C1(data_set)
D = list(map(set, data_set))
L1, support_data = scan_D(D, C1, min_support)
L = [L1]
k = 2
while len(L[k-2]) > 0:
Ck = apriori_gen(L[k-2], k)
Lk, sup_k = scan_D(D, Ck, min_support)
support_data.update(sup_k)
L.append(Lk)
k += 1
return L, support_data
data_set = load_data()
L, support_data = apriori(data_set, min_support=0.5)
print(L)
print(support_data)
```
这个代码实现了Apriori算法,并输出了频繁项集和它们的支持度。
阅读全文