Trying to implement the apriori algorithm and made it to the point where I can extract the subsets occurring together in all transactions.
This is what I have:
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'])]
For example set(['Breakfast & Brunch', 'Restaurants'])
occurs twice
and I need to keep track of the numbers of occurrences together with the corresponding patterns.
I tried to use:
from collections import Counter
support_set = Counter()
# some code that generated the list above
support_set.update(subsets)
but it generates this error:
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'
Any idea?
Method 4: Count occurrences of an element in a list Using countof() Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value.
Use the list. count() method of the built-in list class to get the number of occurrences of an item in the given list.
You can turn the sets to frozenset
instances which are hashable:
>>> 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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With