[英]Please assist in understanding random.choices() weighting
希望在使用 random.choices() 理解權重方面獲得一些幫助
import random
k = 100
population = random.choices(
population=[['a'],['b'],['c'],['d'],['e'],['f'],['g'],['h'], ['i'],['j']],
weights=[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
k=k)
print(population.count(['a'])/k,
population.count(['b'])/k,
population.count(['c'])/k,
population.count(['d'])/k,
population.count(['e'])/k,
population.count(['f'])/k,
population.count(['g'])/k,
population.count(['h'])/k,
population.count(['i'])/k,
population.count(['j'])/k)
所以我已經通過了幾個答案,我的理解是這應該是計算每個字符串的權重時的公式:
總重量為 100
a 是 10/100 或 10%
b 是 10/100 或 10% 等等。
那我說的對嗎?
其次,在測試上面的代碼時,我沒有得到與我期望的實際權重相匹配的細分,大約每個字母出現。
有人可以盡可能簡單地向 Python 新手解釋為什么嗎?
你對權重有正確的理解。 我不確定您的問題到底是什么,也許您的代碼在其他地方有錯誤。 另一個可能的錯誤是random.choices
使用替換從總體中抽樣。 在此處閱讀文檔。 這意味着您可以使用 k=15 進行采樣並像 3 a
s 和 0 b
s 一樣拉出。
這是我用來測試的代碼,希望對你有用。
import random
from collections import defaultdict
from pprint import pprint
random.seed(500)
d = defaultdict(int)
sum = 0
# Run this a bunch of times
for _ in range(100000):
r = random.choices(
population=[['a'],['b'],['c'],['d'],['e'],['f'],['g'],['h'], ['i'],['j']],
weights=[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
k=9)
for ch in r:
d[ch[0]] += 1
sum += 1
for k, v in d.items():
proportion = v/sum
print(f'{k}: {proportion}')
Output
h: 0.10035777777777778
j: 0.10031111111111111
f: 0.10043333333333333
c: 0.09983555555555555
d: 0.09992888888888889
i: 0.0998
a: 0.10010222222222222
e: 0.09956555555555556
b: 0.10003222222222222
g: 0.09963333333333334
替換為k = 15
的random.choices
示例運行:
[['h'], ['j'], ['f'], ['c'], ['h'], ['d'], ['i'], ['d'], ['f'], ['h'], ['a'], ['d'], ['d'], ['c'], ['j']]
這是完全可以預料的。 如果你不明白這一點,請再次復習你的統計數據。
編輯:根據您對原始帖子的評論,您應該重新了解帶有替換的采樣分布的樣子。 如果僅 100 個樣本中各種字母的所有概率都收斂到 10%,那將是非常令人驚訝的。 我建議你得到一個 6 面骰子並開始滾動,同時記錄它落在什么數字上。 根據您的樣本,需要擲很多次骰子才能以 1/6 的機會獲得每個數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.