2021年4月4日 星期日

[ Python 常見問題 ] Choose element(s) from List with different probability in Python

 Source From Here

Question
Have you ever wondered how to select random elements from a list with different probability in Python? In this article, we will discuss how to do the same. Let’s first consider the below example.
  1. import random  
  2.     
  3. sam_Lst = [102034100]  
  4. ran = random.choice(sam_Lst)  
  5. print(ran)  
In the above example, the probability of getting any element from the list is equal. But we want such methods in which the probability of choosing one element from the list is different. This is known as the weighted random choice in Python. In order to find weighted random choices in Python, there exist two ways:
* Relative weights
* Cumulative weights

HowTo
The function which will help us in this situation is random.choices(). This function allows making weighted random choices in python with replacement:
  1. random.choices(population, weights=None, *, cum_weights=None, k=1)  
Here, the ‘weight’ parameter plays an important role.

Case 1: Using Relative weights
The weight assigned to an element is known as relative weight.

Example1:
  1. import random  
  2.     
  3. # Creating a number list  
  4. num_lst = [12243191329]  
  5.     
  6. print(random.choices(num_lst, weights=(142530455510), k=6))  
Output:
[19, 19, 13, 22, 13, 13]

In the above example, we assign weights to every element of the list. The weight of the element ‘13′ is highest i.e 55, so the probability of its occurrence is maximum. As we can see in the output, element 13 occurs 3 times, 19 occurs 2 times, and so on. So, now the probability of choosing an element from the list is different.

Example 2:
  1. import random  
  2.     
  3. # Creating a name list  
  4. name_lst = ['October''November''December''January''March''June']  
  5.     
  6. print(random.choices(name_lst, weights=(40253051580), k=3))  
Output:
['June', 'October', 'June']

In the above example, the weight of element ‘June’ is maximum so its probability of selection will be maximum. And here, k=3 which means we are choosing only the top 3 elements from the list.

Case 2: Using Cumulative weights
The cumulative weight of an element is determined by adding the weight of its previous element and its own weight.

Example 1:
  1. import random  
  2.     
  3. # Creating a number list  
  4. num_lst = [12293191325]  
  5.     
  6. print(random.choices(num_lst, cum_weights=(71315202520), k=6))  
Output:
[1, 22, 93, 22, 19, 1]

In the above example, the cumulative weight of element ‘19′ is maximum, so the probability of its selection will also be maximum.

沒有留言:

張貼留言

[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...