python 加权随机算法_python中的加权随机样本
從你的代碼:..
weight_sample_indexes = lambda weights, k: random.sample([val
for val, cnt in enumerate(weights) for i in range(cnt)], k)
..我認(rèn)為權(quán)重是正整數(shù),而“沒有替換”你的意思是沒有替換解開的序列.
這是一個基于random.sample和O(log n)__getitem__的解決方案:
import bisect
import random
from collections import Counter, Sequence
def weighted_sample(population, weights, k):
return random.sample(WeightedPopulation(population, weights), k)
class WeightedPopulation(Sequence):
def __init__(self, population, weights):
assert len(population) == len(weights) > 0
self.population = population
self.cumweights = []
cumsum = 0 # compute cumulative weight
for w in weights:
cumsum += w
self.cumweights.append(cumsum)
def __len__(self):
return self.cumweights[-1]
def __getitem__(self, i):
if not 0 <= i < len(self):
raise IndexError(i)
return self.population[bisect.bisect(self.cumweights, i)]
例
total = Counter()
for _ in range(1000):
sample = weighted_sample("abc", [1,10,2], 5)
total.update(sample)
print(sample)
print("Frequences %s" % (dict(Counter(sample)),))
# Check that values are sane
print("Total " + ', '.join("%s: %.0f" % (val, count * 1.0 / min(total.values()))
for val, count in total.most_common()))
產(chǎn)量
['b', 'b', 'b', 'c', 'c']
Frequences {'c': 2, 'b': 3}
Total b: 10, c: 2, a: 1
總結(jié)
以上是生活随笔為你收集整理的python 加权随机算法_python中的加权随机样本的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 保存时间 默认_一些不起眼但又非常的实用
- 下一篇: 阿里云数据库mysql 创建数据库服务器