[英]Why does “random.choices” return always the same element when passing a list “cum_weights” of decreasing values?
我不明白的cum_weights
的參數random.choices
。
我讀到它是:
前一個元素的權重 + 自身權重 [10, 5, 1] → [10, 15, 16]
所以據我了解, "cherry"
的概率是16,是最高的。 那么為什么"apple"
重復性更高呢?
import random
mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist, cum_weights=[10, 5, 1], k=9))
輸出:
['apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple']
當您有相對權重時,累積權重看起來像這些值的總和:
你的 cum_weights 應該是: [10, 15, 16]
mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist, cum_weights=[10, 15, 16], k=14))
['apple', 'banana', 'cherry', 'banana', 'apple', 'banana', 'apple', 'apple', 'banana', 'banana', 'apple', 'banana', 'banana', 'banana']
說weights=[10,5,1]
與說cum_weights=[10,15,16]
。 cum_weights
值必須按遞增順序排列才能有意義。 你提供的東西會讓事情變得混亂。 choice
將使用最大值作為其隨機范圍,因此在您的情況下,它將選擇一個從 0 到 9 的數字,並且因為您的前 10 個值是“apple”,因此它總是會選擇“apple”。
您正在混淆相對重量和累積重量。 隨機選擇中的cum_weights=[10, 5, 1]
參數是累積權重本身,它不會進一步累積。
cum_weights
參數不會進一步累積。 您可以在此處查看函數的實現https://github.com/python/cpython/blob/3.9/Lib/random.py#L473並查看此行https://github.com/python/cpython /blob/3.9/Lib/random.py#L505生成輸出的位置。 在bisect
方法中,它嘗試確定索引random()*total
在數組cum_weights
。 在您的情況下cum_weights
是[10, 5, 1]
。 並查看這一行https://github.com/python/cpython/blob/3.9/Lib/random.py#L500以了解如何計算total
。 total = cum_weights[-1] +0.0
這意味着你的total
總是1.0
因為cum_weights
的最后一個值是 1。所以,你總是得到第一個指數,即你的人口中的 0。 所以你的輸出將包含所有“蘋果”。 即使您運行該算法一千次,您當前的實現在我們的輸出列表中也只會得到apple
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.