给定一个代表总体中元素频率的数据系列,对其进行下采样的最简单方法是什么?
以下人群:pop = ['a', 'b', 'a', 'c', 'c', 'd', 'c', 'a', 'a', 'b', 'a']
可以概括为:freq = {'a': 5, 'c': 3, 'b': 2, 'd': 1}
使用简单:from collections import Counter; Counter(pop)
要将人口随机下采样到 5 个人,我可以这样做:
>>> from random import sample
>>> from collections import Counter
>>> pop = ['a', 'b', 'a', 'c', 'c', 'd', 'c', 'a', 'a', 'b', 'a']
>>> smaller_pop = sample(pop, 5)
>>> smaller_freq = Counter(smaller_pop)
>>> print smaller_freq
Counter({'a': 3, 'c': 1, 'b': 1})
但我正在寻找一种直接从freq
信息中执行此操作而无需构建pop
列表的方法。您将同意不需要这样的程序:
>>> from random import sample
>>> from collections import Counter
>>> flatten = lambda x: [item for sublist in x for item in sublist]
>>> freq = {'a': 5, 'c': 3, 'b': 2, 'd': 1}
>>> pop = flatten([[k]*v for k,v in freq.items()])
>>> smaller_pop = sample(pop, 5)
>>> smaller_freq = Counter(smaller_pop)
>>> print smaller_freq
Counter({'a': 2, 'c': 2, 'd': 1})
出于内存考虑和速度要求,我想避免将pop
列表放在内存中。这肯定可以使用某种类型的加权随机生成器来完成。