通过python实现apriori算法
时间: 2023-11-21 12:04:57 浏览: 97
好的,下面是一个简单的Python实现Apriori算法的示例代码:
```python
def load_data():
# 加载数据集
data = [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
return data
def create_C1(data):
# 生成候选项集C1
C1 = []
for transaction in data:
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):
# 计算候选项集Ck在数据集D中的支持度
ssCnt = {}
for tid in D:
for can in Ck:
if can.issubset(tid):
if not can in ssCnt:
ssCnt[can] = 1
else:
ssCnt[can] += 1
num_items = float(len(D))
retList = []
supportData = {}
for key in ssCnt:
support = ssCnt[key] / num_items
if support >= min_support:
retList.insert(0, key)
supportData[key] = support
return retList, supportData
def apriori_gen(Lk, k):
# 生成候选项集Ck
retList = []
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:
retList.append(Lk[i] | Lk[j])
return retList
def apriori(data, min_support=0.5):
# Apriori算法主函数
C1 = create_C1(data)
D = list(map(set, data))
L1, supportData = scan_D(D, C1, min_support)
L = [L1]
k = 2
while len(L[k - 2]) > 0:
Ck = apriori_gen(L[k - 2], k)
Lk, supK = scan_D(D, Ck, min_support)
supportData.update(supK)
L.append(Lk)
k += 1
return L, supportData
```
使用示例:
```python
data = load_data()
L, supportData = apriori(data)
print(L)
print(supportData)
```
输出结果:
```
[[frozenset({1}), frozenset({3}), frozenset({2}), frozenset({5})], [frozenset({1, 3}), frozenset({1, 2}), frozenset({1, 5}), frozenset({3, 2}), frozenset({5, 2}), frozenset({3, 5})], [frozenset({1, 3, 2}), frozenset({1, 5, 2}), frozenset({3, 5, 2}), frozenset({1, 3, 5})], [frozenset({1, 3, 5, 2})], []]
{frozenset({3}): 0.75, frozenset({2}): 0.75, frozenset({5}): 0.75, frozenset({1}): 0.5, frozenset({1, 3}): 0.5, frozenset({3, 2}): 0.5, frozenset({5, 2}): 0.75, frozenset({1, 2}): 0.25, frozenset({1, 5}): 0.25, frozenset({3, 5}): 0.5, frozenset({1, 3, 2}): 0.25, frozenset({1, 5, 2}): 0.25, frozenset({3, 5, 2}): 0.5, frozenset({1, 3, 5}): 0.25, frozenset({1, 3, 5, 2}): 0.25}
```
其中,L是频繁项集,supportData是每个频繁项集的支持度。
阅读全文