《Machine Learning in Action》Chapter 12 FP-growth python兼容性问题

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值