构建FP-growth算法高效发现频繁项集
1、构建FP树
1.1创建FP树的结构
#创建FP树的数据结构
#FP树的类定义
class treeNode:
def __init__(self, nameValue, numOccur, parentNode):
self.name = nameValue
self.count = numOccur
self.nodeLink = None
self.parent = parentNode #needs to be updated
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)
if __name__ == '__main__':
#创建一个单节点
rootNode = treeNode('pyramid',9,None)
#增加一个子节点
rootNode.children['eye'] = treeNode('eye',13,None)
#显示子节点
rootNode.disp()
#添加一个子节点
rootNode.children['phoenix'] = treeNode('phoenix',3,None)
rootNode.disp()
'''
pyramid 9
eye 13
pyramid 9
eye 13
phoenix 3
'''
1.2构建FP树
1.2.1加载数据集
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
if __name__ == '__main__':
data = loadSimpDat()
data = createInitSet(data)
print(data)
'''
{frozenset({'z', 'h', 'r', 'p', 'j'}): 1, frozenset({'s', 'v', 'z', 'u', 'w', 't', 'y', 'x'}): 1, frozenset({'z'}): 1, frozenset({'s', 'o', 'r', 'n', 'x'}): 1,
frozenset({'p', 'z', 't', 'r', 'y', 'q', 'x'}): 1, frozenset({'e', 's', 'z', 't', 'm', 'y', 'q', 'x'}): 1}
'''
1.2.2统计每个商品出现的次数
def createTree(dataSet, minSup=1): #create FP-tree from dataset but don't mine
#头指针表,存储每个元素出现的频率
headerTable = {}
#go over dataSet twice
for trans in dataSet:#first pass counts frequency of occurance
for item in trans:
headerTable[item] = headerTable.get(item, 0) + dataSet[trans]
print(headerTable)
if __name__ == '__main__':
data = loadSimpDat()
data = createInitSet(data)
createTree(data)
'''
{'r': 3, 'h': 1, 'z': 5, 'p': 2, 'j': 1, 'x': 4, 's': 3, 'u': 1, 'v': 1, 'y': 3, 't': 3, 'w': 1, 'o': 1, 'n': 1, 'q': 2, 'm': 1, 'e': 1}
'''
1.2.3过滤支持度小于最小支持度的商品
#删除支持度小于最小支持度的商品
for k in headerTable.keys(): #remove items not meeting minSup
if headerTable[k] < minSup:
del(headerTable[k])
freqItemSet = set(headerTable.keys())
print ('freqItemSet: ',freqItemSet)
'''
freqItemSet: {'n', 't', 'q', 'e', 'p', 'w', 'h', 'r', 'u', 'j', 'o', 'x', 'v', 'm', 'z', 'y', 's'}
'''
if len(freqItemSet) == 0:
return None, None #if no items meet min support -->get out
1.2.4将剩下的商品重新组合成节点的形式
for k in headerTable:
headerTable[k] = [headerTable[k], None] #reformat headerTable to use Node link
print ('headerTable: ',headerTable)
'''
headerTable: {'p': [2, None], 'h': [1, None], 'r': [3, None], 'j': [1, None], 'z': [5, None], 't': [3, None], 'w': [1, None], 'u': [1, None],
'x': [4, None], 'v': [1, None], 'y': [3, None], 's': [3, None], 'n': [1, None], 'o': [1, None], 'q': [2, None], 'e': [1, None], 'm': [1, None]}
'''
1.2.5创建FP树
#FP树构建函数
'''
dataSet:数据集
minSup=1:最小支持度
'''
def createTree(dataSet, minSup=1): #create FP-tree from dataset but don't mine
#头指针表,存储每个元素出现的频率
headerTable = {}
#go over dataSet twice
for trans in dataSet:#first pass counts frequency of occurance
for item in trans:
headerTable[item] = headerTable.get(item, 0) + dataSet[trans]
#删除支持度小于最小支持度的商品
for k in list(headerTable.keys()): #remove items not meeting minSup
if headerTable[k] < minSup:
del(headerTable[k])
freqItemSet = set(headerTable.keys())
print ('freqItemSet: ',freqItemSet)
'''
freqItemSet: {'n', 't', 'q', 'e', 'p', 'w', 'h', 'r', 'u', 'j', 'o', 'x', 'v', 'm', 'z', 'y', 's'}
'''
if len(freqItemSet) == 0:
return None, None #if no items meet min support -->get out
for k in headerTable:
headerTable[k] = [headerTable[k], None] #reformat headerTable to use Node link
print ('headerTable: ',headerTable)
'''
headerTable: {'p': [2, None], 'h': [1, None], 'r': [3, None], 'j': [1, None], 'z': [5, None], 't': [3, None], 'w': [1, None], 'u': [1, None],
'x': [4, None], 'v': [1, None], 'y': [3, None], 's': [3, None], 'n': [1, None], 'o': [1, None], 'q': [2, None], 'e': [1, None], 'm': [1, None]}
'''
retTree = treeNode('Null Set', 1, None) #create tree
#第二次遍历数据集
for tranSet, count in dataSet.items(): #go through dataset 2nd time
localD = {}
for item in tranSet: #put transaction items in order
if item in freqItemSet:
localD[item] = headerTable[item][0]
if len(localD) > 0:
# p: p[1]按照value排序
# p: p[0]按照key排序
#reverse=True降序排列
orderedItems = [v[0] for v in sorted(localD.items(), key=lambda p: p[1], reverse=True)]
'''
orderedItems:['z', 'x', 'y', 's', 't', 'q', 'm', 'e']
'''
updateTree(orderedItems, retTree, headerTable, count)#populate tree with ordered freq itemset
return retTree, headerTable #return tree and header table
# print(localD.items())
'''
dict_items([('e', 1), ('y', 3), ('s', 3), ('z', 5), ('m', 1), ('t', 3), ('x', 4), ('q', 2)])
'''
# if __name__ == '__main__':
# data = loadSimpDat()
# data = createInitSet(data)
# createTree(data)
'''
{'r': 3, 'h': 1, 'z': 5, 'p': 2, 'j': 1, 'x': 4, 's': 3, 'u': 1, 'v': 1, 'y': 3, 't': 3, 'w': 1, 'o': 1, 'n': 1, 'q': 2, 'm': 1, 'e': 1}
'''
'''
items:按照出现次数已排好序的商品列表
inTree:节点树
headerTable:商品节点集
count:频繁项集出现的次数
'''
def updateTree(items, inTree, headerTable, count):
#测试第一个元素项是否作为子节点存在
if items[0] in inTree.children:#check if orderedItems[0] in retTree.children
#如果存在就更新该元素项的计数
inTree.children[items[0]].inc(count) #incrament count
else: #add items[0] to inTree.children
#如果不存在,则将该元素作为一个新节点添加到树中
inTree.children[items[0]] = treeNode(items[0], count, inTree)
#如果头指针表的值为None
if headerTable[items[0]][1] == None: #update header table
#将该元素节点添加到头指针表中
headerTable[items[0]][1] = inTree.children[items[0]]
else:
#如果头指针表已经存在,则更新头指针表
updateHeader(headerTable[items[0]][1], inTree.children[items[0]])
#如果元素项的长度大于1
if len(items) > 1:#call updateTree() with remaining ordered items
#每次不断的调用自身,每次调用去掉列表的第一个元素
updateTree(items[1::], inTree.children[items[0]], headerTable, count)
return inTree
#头指针更新
#确保节点链接指向树中该元素项的每个实例
#构成一个链表
#头指针从nodelink开始,一直沿着nodelink到达链表末尾
def updateHeader(nodeToTest, targetNode): #this version does not use recursion
while (nodeToTest.nodeLink != None): #Do not use recursion to traverse a linked list!
nodeToTest = nodeToTest.nodeLink
nodeToTest.nodeLink = targetNode
if __name__ == '__main__':
data = loadSimpDat()
data = createInitSet(data)
MyFPtree,MyHeaderTable=createTree(data,3)
MyFPtree.disp()
Null Set 1
z 5
r 1
x 3
t 3
y 2
s 2
r 1
y 1
x 1
r 1
s 1
上树中给出了对应的元素项以及对应的频率计数值,每个缩进表示所处的树的深度1.3从FP树中挖掘频繁项集
1.3.1抽取条件模式基
条件模式基:以所查找元素结尾的所有路径的集合,每一条路径都是前缀路径,一条前缀路径是所查找元素项与根节点的所有内容。
#发现以给定元素项结尾的所有路径的函数
#迭代上溯整棵树
#从末尾节点开始遍历,保存节点的名字,一直遍历到根节点
def ascendTree(leafNode, prefixPath): #ascends from leaf node to root
if leafNode.parent != None:
prefixPath.append(leafNode.name)
ascendTree(leafNode.parent, prefixPath)
#遍历链表到达结尾
def findPrefixPath(basePat, treeNode): #treeNode comes from header table
#条件模式基字典
condPats = {}
while treeNode != None:
prefixPath = []
ascendTree(treeNode, prefixPath)
#如果前缀路径大于1
if len(prefixPath) > 1:
print("len(prefixPath) > 1",prefixPath)
print("prefixPath[1:]",prefixPath[1:])
condPats[frozenset(prefixPath[1:])] = treeNode.count
treeNode = treeNode.nodeLink
return condPats
以y结尾的条件模式基
if __name__ == '__main__':
data = loadSimpDat()
data = createInitSet(data)
MyFPtree,MyHeaderTable=createTree(data,3)
path = findPrefixPath('y', MyHeaderTable['y'][1]);
print("path-->",path)
freqItemSet: {'z', 'x', 't', 'r', 's', 'y'}
headerTable: {'z': [5, None], 'r': [3, None], 'x': [4, None], 't': [3, None], 's': [3, None], 'y': [3, None]}
len(prefixPath) > 1 ['y', 's', 't', 'x', 'z']
prefixPath[1:] ['s', 't', 'x', 'z']
len(prefixPath) > 1 ['y', 'r', 't', 'x', 'z']
prefixPath[1:] ['r', 't', 'x', 'z']
path--> {frozenset({'s', 'x', 'z', 't'}): 2, frozenset({'x', 'r', 'z', 't'}): 1}
以r结尾的条件模式基
if __name__ == '__main__':
data = loadSimpDat()
data = createInitSet(data)
MyFPtree,MyHeaderTable=createTree(data,3)
path = findPrefixPath('r', MyHeaderTable['r'][1]);
print("path-->",path)
len(prefixPath) > 1 ['r', 'z']
prefixPath[1:] ['z']
len(prefixPath) > 1 ['r', 'x']
prefixPath[1:] ['x']
len(prefixPath) > 1 ['r', 'x', 'z']
prefixPath[1:] ['x', 'z']
path--> {frozenset({'z'}): 1, frozenset({'x'}): 1, frozenset({'x', 'z'}): 1}
求出所有的元素的条件模式基if __name__ == '__main__':
data = loadSimpDat()
data = createInitSet(data)
MyFPtree,MyHeaderTable=createTree(data,3)
freqItemSet= {'x', 'y', 't', 's', 'z', 'r'}
for i in freqItemSet:
path = findPrefixPath(i, MyHeaderTable[i][1]);
print(i,"path-->",path)
'''
y path--> {frozenset({'x'}): 2, frozenset({'x', 'z'}): 2, frozenset({'t'}): 2, frozenset({'x', 't'}): 4, frozenset({'x', 't', 'z'}): 2}
x path--> {frozenset({'z'}): 4}
s path--> {frozenset({'x', 'y'}): 1, frozenset({'x', 'z', 'y'}): 2, frozenset({'x'}): 2, frozenset({'x', 't', 'y'}): 1, frozenset({'x', 't', 'z', 'y'}): 1}
r path--> {frozenset({'z'}): 1, frozenset({'x', 's'}): 1, frozenset({'x', 't', 'y'}): 1, frozenset({'x', 't', 'z', 'y'}): 1}
z path--> {}
t path--> {frozenset({'x', 's', 'z', 'y'}): 1, frozenset({'x'}): 4, frozenset({'x', 'z'}): 2}
'''
1.3.2通过条件模式基创建条件FP树
def mineTree(inTree, headerTable, minSup, preFix, freqItemList):
#按照value排序的key
#默认升序排列,按照元素项出现的次数从小到大排列
bigL = [v[0] for v in sorted(headerTable.items(), key=lambda p: p[1][0])]#(sort header table)
#从出现次数最小的元素开始(头指针表的底端开始)
for basePat in bigL: #start from bottom of header table
newFreqSet = preFix.copy()
newFreqSet.add(basePat)
print ('频繁项集: ',newFreqSet ) #append to set)
freqItemList.append(newFreqSet)
#得到每个元素的条件模式基
condPattBases = findPrefixPath(basePat, headerTable[basePat][1])
print ('条件模式基 :',basePat, condPattBases)
#2. construct cond FP-tree from cond. pattern base
#根据条件模式基创建条件FP树
myCondTree, myHead = createTree(condPattBases, minSup)
print ('头指针列表 ', myHead)
#挖掘条件FP树
if myHead != None: #3. mine cond. FP-tree
print ('产生的条件树 ',newFreqSet)
myCondTree.disp(1)
mineTree(myCondTree, myHead, minSup, newFreqSet, freqItemList)
if __name__ == '__main__':
minSup = 3
preFix = set([])
freqItemList = []
data = loadSimpDat()
data = createInitSet(data)
MyFPtree,MyHeaderTable=createTree(data,3)
mineTree( MyFPtree,MyHeaderTable, minSup, preFix, freqItemList)
MyHeaderTable {'z': [5, <__main__.treeNode object at 0x0000016BD70FA4A8>], 'r': [3, <__main__.treeNode object at 0x0000016BD70FA470>], 'x': [4, <__main__.treeNode object at 0x0000016BD70FA748>], 'y': [3, <__main__.treeNode object at 0x0000016BD70FA780>], 't': [3, <__main__.treeNode object at 0x0000016BD70FA7B8>], 's': [3, <__main__.treeNode object at 0x0000016BD70FA7F0>]}
MyFPtree <__main__.treeNode object at 0x0000016BD6E8B198>
频繁项: {'r'}
条件模式基 : r {frozenset({'z'}): 1, frozenset({'s', 'x'}): 1, frozenset({'y', 'x', 'z', 't'}): 1}
头指针列表: None
频繁项: {'y'}
条件模式基 : y {frozenset({'x', 'z'}): 3}
头指针列表: {'x': [3, <__main__.treeNode object at 0x0000016BD70FA9E8>], 'z': [3, <__main__.treeNode object at 0x0000016BD70FA978>]}
{'y'} 产生的条件树:
Null Set 1
x 3
z 3
频繁项: {'y', 'x'}
条件模式基 : x {}
头指针列表: None
频繁项: {'y', 'z'}
条件模式基 : z {frozenset({'x'}): 3}
头指针列表: {'x': [3, <__main__.treeNode object at 0x0000016BD70FAA58>]}
{'y', 'z'} 产生的条件树:
Null Set 1
x 3
频繁项: {'y', 'x', 'z'}
条件模式基 : x {}
头指针列表: None
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}]
myCondTree=> None
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}]
myCondTree=> <__main__.treeNode object at 0x0000016BD70FA9B0>
频繁项: {'t'}
条件模式基 : t {frozenset({'y', 'x', 'z'}): 3}
头指针列表: {'y': [3, <__main__.treeNode object at 0x0000016BD70FAB00>], 'x': [3, <__main__.treeNode object at 0x0000016BD70FAA20>], 'z': [3, <__main__.treeNode object at 0x0000016BD70FAA90>]}
{'t'} 产生的条件树:
Null Set 1
y 3
x 3
z 3
频繁项: {'y', 't'}
条件模式基 : y {}
头指针列表: None
频繁项: {'x', 't'}
条件模式基 : x {frozenset({'y'}): 3}
头指针列表: {'y': [3, <__main__.treeNode object at 0x0000016BD70FABA8>]}
{'x', 't'} 产生的条件树:
Null Set 1
y 3
频繁项: {'y', 'x', 't'}
条件模式基 : y {}
头指针列表: None
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}, {'t'}, {'y', 't'}, {'x', 't'}, {'y', 'x', 't'}]
myCondTree=> None
频繁项: {'z', 't'}
条件模式基 : z {frozenset({'y', 'x'}): 3}
头指针列表: {'y': [3, <__main__.treeNode object at 0x0000016BD70FAC88>], 'x': [3, <__main__.treeNode object at 0x0000016BD70FAC50>]}
{'z', 't'} 产生的条件树:
Null Set 1
y 3
x 3
频繁项: {'y', 'z', 't'}
条件模式基 : y {}
头指针列表: None
频繁项: {'x', 'z', 't'}
条件模式基 : x {frozenset({'y'}): 3}
头指针列表: {'y': [3, <__main__.treeNode object at 0x0000016BD70FABE0>]}
{'x', 'z', 't'} 产生的条件树:
Null Set 1
y 3
频繁项: {'y', 'x', 'z', 't'}
条件模式基 : y {}
头指针列表: None
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}, {'t'}, {'y', 't'}, {'x', 't'}, {'y', 'x', 't'}, {'z', 't'}, {'y', 'z', 't'}, {'x', 'z', 't'}, {'y', 'x', 'z', 't'}]
myCondTree=> None
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}, {'t'}, {'y', 't'}, {'x', 't'}, {'y', 'x', 't'}, {'z', 't'}, {'y', 'z', 't'}, {'x', 'z', 't'}, {'y', 'x', 'z', 't'}]
myCondTree=> <__main__.treeNode object at 0x0000016BD70FACF8>
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}, {'t'}, {'y', 't'}, {'x', 't'}, {'y', 'x', 't'}, {'z', 't'}, {'y', 'z', 't'}, {'x', 'z', 't'}, {'y', 'x', 'z', 't'}]
myCondTree=> <__main__.treeNode object at 0x0000016BD70FAC18>
频繁项: {'s'}
条件模式基 : s {frozenset({'y', 'x', 'z', 't'}): 2, frozenset({'x'}): 1}
头指针列表: {'x': [3, <__main__.treeNode object at 0x0000016BD70FAB38>]}
{'s'} 产生的条件树:
Null Set 1
x 3
频繁项: {'s', 'x'}
条件模式基 : x {}
头指针列表: None
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}, {'t'}, {'y', 't'}, {'x', 't'}, {'y', 'x', 't'}, {'z', 't'}, {'y', 'z', 't'}, {'x', 'z', 't'}, {'y', 'x', 'z', 't'}, {'s'}, {'s', 'x'}]
myCondTree=> None
频繁项: {'x'}
条件模式基 : x {frozenset({'z'}): 3}
头指针列表: {'z': [3, <__main__.treeNode object at 0x0000016BD70FAD68>]}
{'x'} 产生的条件树:
Null Set 1
z 3
频繁项: {'x', 'z'}
条件模式基 : z {}
头指针列表: None
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}, {'t'}, {'y', 't'}, {'x', 't'}, {'y', 'x', 't'}, {'z', 't'}, {'y', 'z', 't'}, {'x', 'z', 't'}, {'y', 'x', 'z', 't'}, {'s'}, {'s', 'x'}, {'x'}, {'x', 'z'}]
myCondTree=> None
频繁项: {'z'}
条件模式基 : z {}
头指针列表: None
freqItemList=> [{'r'}, {'y'}, {'y', 'x'}, {'y', 'z'}, {'y', 'x', 'z'}, {'t'}, {'y', 't'}, {'x', 't'}, {'y', 'x', 't'}, {'z', 't'}, {'y', 'z', 't'}, {'x', 'z', 't'}, {'y', 'x', 'z', 't'}, {'s'}, {'s', 'x'}, {'x'}, {'x', 'z'}, {'z'}]
myCondTree=> None
Null Set 1
z 5
r 1
x 3
y 3
t 3
s 2
r 1
x 1
s 1
r 1
Process finished with exit code 0
2、应用:从新闻网站点击流中挖掘
if __name__ == '__main__':
fs = open("G:\kosarak.dat")
readlines = fs.readlines()
mydat=[]
for line in readlines:
split = line.split()
mydat.append(split)
data = createInitSet(mydat)
MyFPtree,MyHeaderTable=createTree(data,100000)
myFreqList = []
#寻找至少被十万人浏览过的报道
mineTree(MyFPtree,MyHeaderTable,100000,set([]),myFreqList)
print(len(myFreqList))
print(myFreqList)
欢迎关注我的公众号:小秋的博客
CSDN博客:https://blog.csdn.net/xiaoqiu_cr
github:https://github.com/crr121
联系邮箱:rongchen633@gmail.com
有什么问题可以给我留言噢~