尝试实现apriori算法,并使其能够提取所有事务中一起出现的子集。
这就是我所拥有的:
subsets = [set(['Breakfast & Brunch', 'Restaurants']), set(['American (Traditional)', 'Breakfast & Brunch']), set(['American (Traditional)', 'Restaurants']), set(['American (Traditional)', 'Breakfast & Brunch']), set(['Breakfast & Brunch', 'Restaurants']), set(['American (Traditional)', 'Restaurants'])]
例如set(['Breakfast & Brunch', 'Restaurants'])
出现两次
我需要跟踪出现的次数以及相应的模式。
我试图使用:
from collections import Counter
support_set = Counter()
# some code that generated the list above
support_set.update(subsets)
但它会产生此错误:
supported = itemsets_support(transactions, candidates)
File "apriori.py", line 77, in itemsets_support
support_set.update(subsets)
File"/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 567, in update
self[elem] = self_get(elem, 0) + 1
TypeError: unhashable type: 'set'
有什么想法吗?
答案 0 :(得分:4)
您可以将这些集转换为可以缓存的frozenset
个实例:
>>> from collections import Counter
>>> subsets = [set(['Breakfast & Brunch', 'Restaurants']), set(['American (Traditional)', 'Breakfast & Brunch']), set(['American (Traditional)', 'Restaurants']), set(['American (Traditional)', 'Breakfast & Brunch']), set(['Breakfast & Brunch', 'Restaurants']), set(['American (Traditional)', 'Restaurants'])]
>>> c = Counter(frozenset(s) for s in subsets)
>>> c
Counter({frozenset(['American (Traditional)', 'Restaurants']): 2, frozenset(['Breakfast & Brunch', 'Restaurants']): 2, frozenset(['American (Traditional)', 'Breakfast & Brunch']): 2})