1

给定一个代表总体中元素频率的数据系列,对其进行下采样的最简单方法是什么?

以下人群: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列表放在内存中。这肯定可以使用某种类型的加权随机生成器来完成。

4

1 回答 1

1

这是一个对频率进行下采样的基本算法:

import random
import bisect
import collections

def downsample(freq, n):
    cumsums = []
    total = 0
    choices, weights = zip(*freq.items())
    for weight in weights:
        total += weight
        cumsums.append(total)
    assert 0 <= n <= total
    result = collections.Counter()
    for _ in range(n):
        rnd = random.uniform(0, total)
        i = bisect.bisect(cumsums, rnd)
        result[choices[i]] += 1
        cumsums = [c if idx<i else c-1 for idx, c in enumerate(cumsums)]
        total -= 1
    return result

freq = {'a': 5, 'c': 3, 'b': 2, 'd': 1}
print(downsample(freq, 5))

打印结果如

Counter({'c': 2, 'a': 1, 'b': 1, 'd': 1})
于 2013-06-13T14:31:57.097 回答