直接引用apriori算法python代码
时间: 2023-10-13 07:19:57 浏览: 99
Apriori算法的实现的python代码.doc
5星 · 资源好评率100%
以下是Python中Apriori算法的示例代码:
```python
def loadDataSet():
return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
def createC1(dataSet):
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 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.insert(0,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):
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
```
这个示例中,`loadDataSet`函数返回一个包含多个交易的列表,每个交易是一个由项目编号构成的列表。`createC1`函数用于生成包含单个项目集的候选项集。`scanD`函数用于计算每个项集在数据集中的支持度,并返回满足最小支持度要求的项集和它们的支持度。`aprioriGen`函数用于生成候选项集。`apriori`函数是Apriori算法的主要实现,它使用上述函数计算频繁项集和它们的支持度。
阅读全文