class treeNode:
def __init__(self,nameValue,numOccur,parentNode):
self.name = nameValue #值
self.count = numOccur #计数
self.nodeLink = None #横向链
self.parent = parentNode #父亲节点
self.children = {} #儿子节点
def inc(self,numOccur):
self.count += numOccur
def disp(self,ind = 1): #输出显示
print ' ' * ind,self.name,' ',self.count
for child in self.children.values():
child.disp(ind + 1)
主要目的是将数据一行一行插入字典树里面,但是先进行了过滤操作,删除了一些不可能出现的项集,并且对记录进行了排序.
#dataSet是记录,minSup是最小支持度
def createTree(dataSet,minSup=1):
#对每个元素进行计数
headerTable = {}
for trans in dataSet
for item in trans:
headerTable[item] = headerTable.get(item,0) + dataSet[trans]
#删除项集大小为1的非频繁项集,根据apriori原则,包含该非频繁项集的项集都不可能是频繁项集
for k in headerTable.keys():
if headerTable[k] < minSup:
del(headerTable[k])
freqItemSet = set(headerTable.keys())
if len(freqItemSet) == 0: return None,None
for k in headerTable:
headereTable[k] = [headerTable[k],None]
#创建根节点
retTree = treeNode('Null Set',1,None)
#得到删除非频繁k=1的项的 项集,并以字典树的形式插入树里。
for tranSet, count in dataSet.items():
localID = {}
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
#items一行记录,inTree FP树的树根,headerTable出现的频繁项集,count这行记录出现的次数
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)
#如果这个节点对于的headerTable没有出现就创建.
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)
#更新headerLink的链
def updateHeader(nodeToTest,targetNone):
while(nodeToTest.nodeLink != None):
nodeToTest = nodeToTest.nodeLink
nodeToTest.nodeLink = targetNone
def loadSimpDat():
simpDat = [['r','z','h','j','p'],
['z','y','x','w','v','u','t','s'],
['z'],
['r','x','n','o','s'],
['y','r','x','z','q','t','p'],
['y','z','x','e','q','s','t','m']]
return simpDat
def createInitSet(dataSet):
retDict = {}
for trans in dataSet:
retDict[frozenset(trans)] = 1
return retDict
#leafNode是叶子节点,prefixPath是返回的路径
def ascendTree(leafNode,prefixPath):
#prefixPath = []
if leafNode.parent != None:
prefixPath.append(leafNode.name)
ascendTree(leafNode.parent,prefixPath)
#返回basePat对于的所有前缀和计数,treeNode是其对应的第一个节点
def findPrefixPath(basePat,treeNode):
conPats = {}
while treeNode != None:
prefixPath = []
ascendTree(treeNode,prefixPath)
if len(prefixPath) > 1:
conPats[frozenset(prefixPaht[1:])] = treeNode.count
treeNode = treeNode.nodeLink
return condPats