关联规则aprior算法代码实现
时间: 2023-09-13 19:12:50 浏览: 95
数据挖掘中关联规则之Aprior算法的实现
4星 · 用户满意度95%
以下是Apriori算法的Python实现:
```python
def loadDataSet():
"""
创建一个用于测试的简单数据集
"""
return [[1,3,4],[2,3,5],[1,2,3,5],[2,5]]
def createC1(dataSet):
"""
创建初始候选项集C1
"""
C1 = []
for transaction in dataSet:
for item in transaction:
if not [item] in C1:
C1.append([item])
C1.sort()
return map(frozenset, C1)
def scanD(D, Ck, minSupport):
"""
从候选项集Ck生成符合最小支持度的项集Lk
"""
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):
"""
根据Lk生成候选项集Ck+1
"""
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 = 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
```
使用方法如下:
```python
dataSet = loadDataSet()
L, suppData = apriori(dataSet, minSupport=0.5)
print(L)
print(suppData)
```
其中,`dataSet`是数据集,`minSupport`是最小支持度。`L`即为频繁项集,`suppData`是包含支持度信息的字典。
阅读全文