2021年4月11日 星期日

[ Python 常見問題 ] How to sample a random number from a probability distribution in Python

 Source From Here

Question
A number selected randomly using a probability distribution will return a number according to the relative weights. For example, a number selected from [1, 2] with relative weights [.9, .1] will have a 90% chance of being 1 and a 10% chance of being 2.

HowTo
USE random.choices() TO SELECT A RANDOM NUMBER

Call random.choices(population, weights) to sample a random number from population based on the probability distribution weights. The weights are relative, meaning the percentage of each number being picked depends on what the weights sum to. e.g.:
  1. import random  
  2. from collections import defaultdict  
  3.   
  4. a_list = [12]  
  5. distribution = [.9, .1] # weights add up to 1  
  6. fdict = defaultdict(int)  
  7.   
  8. loop_num = 1000  
  9. for i in range(loop_num):  
  10.     random_number = random.choices(a_list, distribution)[0]  
  11.     fdict[random_number] += 1  
  12.       
  13. for n, f in fdict.items():  
  14.     print(f"number {n} appears with probability as {f*100/loop_num}%")  
Output:
number 1 appears with probability as 91.4%
number 2 appears with probability as 8.6%


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...