生成一个apriori算法的Python源代码有中文注释
时间: 2023-06-23 20:09:04 浏览: 114
Apriori算法 源代码
5星 · 资源好评率100%
以下是使用Python实现Apriori算法的示例代码,其中包含了中文注释:
```python
# -*- coding: utf-8 -*-
"""
Apriori算法实现
"""
def loadDataSet():
"""
加载数据集
:return: 数据集
"""
return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
def createC1(dataSet):
"""
生成C1集合
:param dataSet: 数据集
:return: C1集合
"""
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):
"""
从Ck生成Lk
:param D: 数据集
:param Ck: 频繁项集列表
:param minSupport: 最小支持度
:return: 返回符合最小支持度要求的频繁项集列表和支持度字典
"""
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):
"""
生成Ck
:param Lk: 频繁项集列表
:param k: 项集元素个数
:return: Ck
"""
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算法
:param dataSet: 数据集
:param minSupport: 最小支持度
:return: 返回符合最小支持度要求的频繁项集列表和支持度字典
"""
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
if __name__ == '__main__':
dataSet = loadDataSet()
L, supportData = apriori(dataSet)
print(L)
print(supportData)
```
注意,此代码为示例代码,实际使用时还需要根据自己的需求进行调整。
阅读全文