fpgrowth算法代码
时间: 2024-01-07 07:01:32 浏览: 156
fpgrowth算法是一种用于频繁项集挖掘的常用算法,它的主要思想是基于Apriori算法的改进,通过构建FP树(频繁模式树)来高效地发现频繁项集。下面是fpgrowth算法的代码示例:
```python
class TreeNode:
def __init__(self, name, count, parent):
self.name = name # 项的名称
self.count = count # 计数
self.nodeLink = None # 指向相似节点的指针
self.parent = parent # 指向父节点
self.children = {} # 子节点
def createFPTree(dataSet, minSup):
headerTable = {}
for trans in dataSet:
for item in trans:
headerTable[item] = headerTable.get(item, 0) + dataSet[trans]
for k in list(headerTable.keys()):
if headerTable[k] < minSup:
del(headerTable[k])
freqItemSet = set(headerTable.keys())
if len(freqItemSet) == 0:
return None, None
for k in headerTable:
headerTable[k] = [headerTable[k], None]
retTree = TreeNode('Null Set', 1, None)
for tranSet, count in dataSet.items():
localD = {}
for item in tranSet:
if item in freqItemSet:
localD[item] = headerTable[item][0]
if len(localD) > 0:
orderedItems = [v[0] for v in sorted(localD.items(), key=lambda p: p[1], reverse=True)]
updateTree(orderedItems, retTree, headerTable, count)
return retTree, headerTable
def updateTree(items, inTree, headerTable, count):
if items[0] in inTree.children:
inTree.children[items[0]].inc(count)
else:
inTree.children[items[0]] = TreeNode(items[0], count, inTree)
if headerTable[items[0]][1] == None:
headerTable[items[0]][1] = inTree.children[items[0]]
else:
updateHeader(headerTable[items[0]][1], inTree.children[items[0]])
if len(items) > 1:
updateTree(items[1:], inTree.children[items[0]], headerTable, count)
def ascendTree(leafNode, prefixPath):
if leafNode.parent != None:
prefixPath.append(leafNode.name)
ascendTree(leafNode.parent, prefixPath)
def findPrefixPath(basePat, treeNode):
condPats = {}
while treeNode != None:
prefixPath = []
ascendTree(treeNode, prefixPath)
if len(prefixPath) > 1:
condPats[frozenset(prefixPath[1:])] = treeNode.count
treeNode = treeNode.nodeLink
return condPats
def mineTree(inTree, headerTable, minSup, preFix, freqItemList):
bigL = [v[0] for v in sorted(headerTable.items(), key=lambda p: p[1])]
for basePat in bigL:
newFreqSet = preFix.copy()
newFreqSet.add(basePat)
freqItemList.append(newFreqSet)
condPattBases = findPrefixPath(basePat, headerTable[basePat][1])
myCondTree, myHead = createFPTree(condPattBases, minSup)
if myHead != None:
mineTree(myCondTree, myHead, minSup, newFreqSet, freqItemList)
dataSet = {frozenset(['e', 'a', 'c', 'd', 'f', 'g', 'm', 'p']): 1,
frozenset(['a', 'b', 'c', 'f', 'l', 'm', 'o']): 1,
frozenset(['b', 'f', 'h', 'j', 'o']): 1,
frozenset(['b', 'c', 'k', 's', 'p']): 1,
frozenset(['a', 'f', 'c', 'e', 'l', 'p', 'm', 'n']): 1}
tree, headerTable = createFPTree(dataSet, 3)
freqItems = []
mineTree(tree, headerTable, 3, set([]), freqItems)
print(freqItems)
```
上面是一个简单的Python实现的fpgrowth算法的代码示例,通过构建FP树来高效地发现频繁项集,并输出频繁项集。
阅读全文