手动实现apriori算法代码的实现
时间: 2023-06-13 17:05:07 浏览: 103
以下是手动实现apriori算法的Python代码实现:
```python
def createC1(dataSet):
"""
生成第一层候选项集
"""
C1 = []
for transaction in dataSet:
for item in transaction:
if not [item] in C1:
C1.append([item])
return list(map(frozenset, C1))
def scanD(D, Ck, minSupport):
"""
从候选项集生成频繁项集
"""
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
numItems = float(len(D))
retList = []
supportData = {}
for key in ssCnt:
support = ssCnt[key] / numItems
if support >= minSupport:
retList.append(key)
supportData[key] = support
return retList, supportData
def aprioriGen(Lk, k):
"""
由频繁项集生成候选项集
"""
retList = []
lenLk = len(Lk)
for i in range(lenLk):
for j in range(i + 1, lenLk):
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(dataSet, minSupport=0.5):
"""
Apriori算法
"""
C1 = createC1(dataSet)
D = list(map(set, dataSet))
L1, supportData = scanD(D, C1, minSupport)
L = [L1]
k = 2
while len(L[k - 2]) > 0:
Ck = aprioriGen(L[k - 2], k)
Lk, supK = scanD(D, Ck, minSupport)
supportData.update(supK)
L.append(Lk)
k += 1
return L, supportData
```
其中,`dataSet` 是一组交易记录,每个交易记录是一组物品集合;`minSupport` 是设置的最小支持度阈值,用于筛选频繁项集。函数返回的是一个列表,其中每个元素是频繁项集。
阅读全文