Pythonで重み付けされた選択肢

確率サンプリングによって、リスト上の

  • 入力:要素のコレクションCとCの確率分布p;
  • 出力:Pに応じてCからランダムに選択された要素。

Cが有するn個の要素、1-nは、確率(P =(P [1]、...、P [N])。我々のみはrandom.Random()関数は、[私たち0,1均一な分布を与えます]上のフロート。基本的な考え方は、長さpのn個のセグメントに[0,1]に分割することである[1] ... P [N](ΣのP [I] = 1)。1]、0 [一様であればドット上に、それは、i番目のセグメントに停止する確率は、p [i]があるためはrandom.Random()関数によって実現することができるされている。場所を停止確認し[0,1]、それを返している位置、 Pythonは次のように実装され、そのセグメント・インデックス:

REF:https://scaron.info/blog/python-weighted-choice.html

確率サンプリングによって、リスト上の

import random
import collections

def weighted_choice(seq, weights):
    assert len(weights) == len(seq)
    assert abs(1. - sum(weights)) < 1e-6

    x = random.random()
    for i, elmt in enumerate(seq):
        if x <= weights[i]:
            return elmt
        x -= weights[i]

def gen_weight_list(seq, gt_set, incline_ratio):
    '''
    :param seq:
    :param gt_list:
    :param incline_ratio:
    :return:
    seqe = [1,2,3,4,5]
    gt_list = [3,5,7]
    # incline_ratio = 0.9   # allocate this num of prob for random select gt's in sequence
    '''
    len_seq = len(seq)
    # programmatic gen the prob list:
    prob_list = []
    gts_in_seq = [i for i in seq if i in gt_set]
    len_gts_in_seq = len(gts_in_seq)
    # item_ngt_in_seq = [i for i in seqe if i not in gt_list]
    if len_gts_in_seq > 0:
        prob_gt = incline_ratio/len_gts_in_seq
        prob_ngt = (1-incline_ratio)/(len_seq - len_gts_in_seq)
    else:
        prob_gt = 0
        prob_ngt = 1/len_seq

    for idx in range(len_seq):
        if seq[idx] in gts_in_seq:
            # prob_list[idx] = prob_gt
            prob_list.append(prob_gt)
        else:
            # prob_list[idx] = prob_ngt
            prob_list.append(prob_ngt)

    return prob_list

# add prob incline ratio for allocate heavier weight udr some conditions:
seqe = [1,2,3,4,5]
gt_set = set([3,5,7])    # conditions, if item in seq is also in this list, will be allocated higher weight.
inc_ratio = 0.8   # allocate this num of prob for random select gt's in sequence

prob = gen_weight_list(seqe, gt_set, inc_ratio)
select_seq = []

for i in range(10000):
    select_seq.append(weighted_choice(seqe, prob))

# count the item in select_seq:
select_seq.sort(reverse=True)     #optional?
item_Count = collections.Counter(select_seq)
print(item_Count)

おすすめ

転載: www.cnblogs.com/sonictl/p/11652848.html