【问题标题】:How to count the occurrences of sets which are part of a list in Python?如何计算作为 Python 列表一部分的集合的出现次数?
【发布时间】:2017-06-30 23:35:47
【问题描述】:

尝试实现先验算法并使其达到可以提取所有事务中一起出现的子集的程度。

这就是我所拥有的:

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'

有什么想法吗?

【问题讨论】:

  • 这可能不再是 Apriori 了,你正在实现什么,而是“频繁项集”想法的幼稚和低效的近似。使用一些更大的数据集进行基准测试,例如ELKI 或 R 的 arules 包。将所有内容放入 Counter 不会扩展。尝试例如超市数据集。
  • 它是 Apriori 的一部分。如果它可以扩展,那是一个不同的问题。在这一点上,它还不是为生产而构建的!
  • 不,不是。 Apriori 的目的不是低效,而是高效。如果你忽略效率方面,它就不再是 Apriori。

标签: python data-mining


【解决方案1】:

您可以将集合转换为可散列的 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})

【讨论】:

    猜你喜欢
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    相关资源
    最近更新 更多