由于其值而对键进行采样(Sampling keys due to their values)

编程入门 行业动态 更新时间:2024-10-26 13:33:24
于其值而对键进行采样(Sampling keys due to their values)

我在python中有一个字典,key-> value为str->int 。 如果我必须根据它自己的值选择一个键,那么当值变大时,键的选择可能性就会降低。

例如,如果key1=2且key2->1 ,则key1的态度应为2:1 。

我怎样才能做到这一点?

I have a dictionary in python with key->value as str->int. If I have to chose a key based on it's own value, then as the value gets larger the key has a lower possibility of being chosen.

For example, if key1=2 and key2->1, then the attitude of key1 should be 2:1.

How can I do this?

最满意答案

1.构建类似CDF的列表,如下所示:

def build_cdf(distrib): cdf = [] val = 0 for key, freq in distrib.items(): val += freq cdf.append((val, key)) return (val, cdf)

此函数返回一个元组,第一个值是概率之和,第二个值是CDF。

2.像这样构造采样器:

import random def sample_from_cdf(val_and_cdf): (val, cdf) = val_and_cdf; rand = random.uniform(0, val) # use bisect.bisect_left to reduce search time from O(n) to O(log n). return [key for index, key in cdf if index > rand][0]

用法:

x = build_cdf({"a":0.2, "b":0.3, "c":0.5}); y = [sample_from_cdf(x) for i in range(0,100000)]; print (len([t for t in y if t == "a"])) # 19864 print (len([t for t in y if t == "b"])) # 29760 print (len([t for t in y if t == "c"])) # 50376

你可能想把它变成一个类。

1. Construct a CDF-like list like this:

def build_cdf(distrib): cdf = [] val = 0 for key, freq in distrib.items(): val += freq cdf.append((val, key)) return (val, cdf)

This function returns a tuple, the 1st value is the sum of probabilities, and 2nd value is the CDF.

2. Construct the sampler like this:

import random def sample_from_cdf(val_and_cdf): (val, cdf) = val_and_cdf; rand = random.uniform(0, val) # use bisect.bisect_left to reduce search time from O(n) to O(log n). return [key for index, key in cdf if index > rand][0]

Usage:

x = build_cdf({"a":0.2, "b":0.3, "c":0.5}); y = [sample_from_cdf(x) for i in range(0,100000)]; print (len([t for t in y if t == "a"])) # 19864 print (len([t for t in y if t == "b"])) # 29760 print (len([t for t in y if t == "c"])) # 50376

You may want to make this into a class.

更多推荐

本文发布于:2023-07-31 09:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1341932.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而对   于其   Sampling   values   due

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!