1、遍历字典过程中不得删除元素
原书在createTree函数中包含如下一段删除不满足支持度的元素的代码:
for k in headerTable.keys(): #remove items not meeting minSup
if headerTable[k] < minSup:
del(headerTable[k])
在python3中提示如下错误:
RuntimeError: dictionary changed size during iteration
因为python3在遍历字典时,不允许修改元素。可以将headerTable.keys()转为list,然后遍历list,代码如下:
for k in list(headerTable.keys()): # remove items not meeting minSup
if headerTable[k] < minSup:
del (headerTable[k])
2、排序函数lambda表达式错误
本章在两处使用了排序函数,第一处在createTree函数中,对字典localD按照value值进行排序,程序无误。
localD如下:
<class 'dict'>: {'z': 5, 'r': 3}
排序函数(根据value进行比较,正序,只返回key)如下:
[v[0] for v in sorted(localD.items(), key=lambda p: p[1], reverse=False)]
第二处在mineTree函数中,对头表headerTable中的元素按照value的第一个值(即计数值)排序,代码如下:
[v[0] for v in sorted(headerTable.items(), key=lambda p: p[1])]
执行程序,结果如下:
TypeError: '<' not supported between instances of 'treeNode' and 'treeNode'
意思是treeNode对象之间无法进行比较,设置断点,查看headerTable,如下:
<class 'dict'>: {
'z': [5, <__main__.treeNode object at 0x00000174AD82B080>],
'r': [3, <__main__.treeNode object at 0x00000174AD80DC18>],
'x': [4, <__main__.treeNode object at 0x00000174AD714940>],
't': [3, <__main__.treeNode object at 0x00000174AD82BF28>],
'y': [3, <__main__.treeNode object at 0x00000174AD82B7B8>],
's': [3, <__main__.treeNode object at 0x00000174AD82BDD8>]
}
为了按照计数值进行排序,代码应该修改为:
[v[0] for v in sorted(headerTable.items(), key=lambda p: p[1][0])]
3、打印FP-growth树
def display(self, ind=1):
n = ind
while n > 0:
print('\t', end="")
n -= 1
print(self.name + '\t' + str(self.count))
for child in self.children.values():
child.display(ind+1)