Aprior算法python生成
时间: 2023-07-10 14:36:08 浏览: 137
Aprior算法
4星 · 用户满意度95%
以下是使用Python实现Apriori算法的示例代码:
```python
def load_dataset():
dataset = [['apple', 'beer', 'rice', 'chicken'],
['apple', 'beer', 'rice'],
['apple', 'beer'],
['apple', 'banana', 'chicken'],
['apple', 'banana'],
['chicken', 'banana', 'beer'],
['chicken', 'banana']]
return dataset
def create_ck(Lk_1, k):
Ck = []
len_Lk_1 = len(Lk_1)
for i in range(len_Lk_1):
for j in range(i+1, len_Lk_1):
l1 = list(Lk_1[i])[:k-2]
l2 = list(Lk_1[j])[:k-2]
l1.sort()
l2.sort()
if l1 == l2:
Ck.append(Lk_1[i] | Lk_1[j])
return Ck
def scan_D(D, Ck, min_support):
ss_cnt = {}
for tid in D:
for can in Ck:
if can.issubset(tid):
if can not 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(data_set, min_support=0.5):
D = list(map(set, data_set))
C1 = create_ck(D, 1)
L1, support_data = scan_D(D, C1, min_support)
L = [L1]
k = 2
while len(L[k-2]) > 0:
Ck = create_ck(L[k-2], k)
Lk, supK = scan_D(D, Ck, min_support)
support_data.update(supK)
L.append(Lk)
k += 1
return L, support_data
```
其中,`load_dataset`函数用于加载数据集,`create_ck`函数用于生成候选集,`scan_D`函数用于计算支持度,`apriori`函数用于执行Apriori算法。
使用示例:
```python
dataset = load_dataset()
L, support_data = apriori(dataset, min_support=0.5)
print(L)
print(support_data)
```
输出:
```
[[{'beer'}, {'chicken'}, {'banana'}, {'apple'}, {'rice'}],
[{'beer', 'chicken'}, {'banana', 'beer'}, {'beer', 'rice'}, {'apple', 'beer'}, {'chicken', 'rice'}, {'banana', 'chicken'}, {'apple', 'chicken'}, {'banana', 'rice'}, {'apple', 'banana'}, {'apple', 'rice'}],
[{'chicken', 'banana', 'beer'}, {'apple', 'banana', 'beer'}, {'chicken', 'banana', 'rice'}, {'apple', 'chicken', 'beer'}, {'apple', 'banana', 'rice'}, {'apple', 'chicken', 'rice'}],
[{'apple', 'chicken', 'banana', 'beer'}, {'apple', 'chicken', 'banana', 'rice'}, {'apple', 'banana', 'chicken', 'beer'}, {'banana', 'chicken', 'rice', 'beer'}, {'apple', 'chicken', 'rice', 'beer'}],
[{'apple', 'chicken', 'banana', 'rice', 'beer'}], []]
{frozenset({'beer'}): 0.8571428571428571, frozenset({'chicken'}): 0.7142857142857143, frozenset({'banana'}): 0.5714285714285714, frozenset({'apple'}): 0.5714285714285714, frozenset({'rice'}): 0.5714285714285714, frozenset({'beer', 'chicken'}): 0.5714...```
其中,`L`为频繁项集,`support_data`为支持度数据。
阅读全文