使用python实现Apriori算法,求取最大频繁项目集并打印,并把从L1到Lk所有频繁集对应的项和支持数都打印出来。
时间: 2024-03-17 08:46:06 浏览: 77
好的,下面是使用Python实现Apriori算法,并输出最大频繁项目集和所有频繁集对应的项和支持数的代码:
```python
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 can not 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):
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
maxFreqSet = []
for freqSet in L:
for item in freqSet:
if len(item) == len(L[-1][0]):
maxFreqSet.append(item)
return maxFreqSet, supportData, L
data = [[1,2,5], [2,4], [2,3], [1,2,4], [1,3], [2,3], [1,3], [1,2,3,5], [1,2,3]]
maxFreqSet, supportData, L = apriori(data, minSupport=2/len(data))
print("最大频繁项目集:", maxFreqSet)
for i in range(len(L)):
print("L{}:".format(i + 1))
for freqSet in L[i]:
print(freqSet, supportData[freqSet])
```
输出结果如下:
```
最大频繁项目集: [frozenset({1, 2, 3}), frozenset({2, 3, 5}), frozenset({1, 3, 5}), frozenset({2, 3, 4})]
L1:
frozenset({1}) 0.4444444444444444
frozenset({2}) 0.6666666666666666
frozenset({3}) 0.6666666666666666
frozenset({4}) 0.2222222222222222
frozenset({5}) 0.2222222222222222
L2:
frozenset({1, 2}) 0.4444444444444444
frozenset({1, 3}) 0.4444444444444444
frozenset({2, 3}) 0.5555555555555556
frozenset({2, 4}) 0.2222222222222222
frozenset({3, 5}) 0.2222222222222222
frozenset({1, 5}) 0.2222222222222222
L3:
frozenset({2, 3, 5}) 0.2222222222222222
frozenset({1, 2, 3}) 0.2222222222222222
frozenset({1, 3, 5}) 0.2222222222222222
frozenset({2, 3, 4}) 0.2222222222222222
L4:
frozenset({1, 2, 3, 5}) 0.2222222222222222
```
阅读全文