How To Get The Weighted Random In Python

Here we are going to learn about how to get the weighted random in python? We will learn random.choice() to get the weighted random. Get the weighted random using the NumPy module. And points to remember while implementing weighted random.

Weighted random functions are a way to define several random outcomes and choose one of these randomly. But in a way where we can say some outcomes are more likely to occur than others. Generally, we know that the random method is useful to get random values from the list. The same random weighted means getting the random values based on their probability distribution.

Using random.choice() module

This module is introduced in the version of python 3.6 in a random module. We can choose single or multiple elements using this module. This function is useful to get the weighted random in python.

Example to get the single element

import random
lst=[5,15,60,40,80]
print(random.choices(lst))

Output

[15]

How to get the weighted random in python using a random module?

Syntax

random.choices(sequence, weights=None, cum_weights=None, k=1)

Parameters

  • sequence – list, tuple, or string
  • weights – relative weight
  • cum_weights – cumulative weight
  • k – length

Weights are mentioned using two ways. They are,

  • Relative weight
  • Cumulative weight

Code: Giving relative weights

import random
lst=[5,10,15,20,25,30,35,40,45,50]
print(random.choices(lst,weights=(1,2,3,4,5,6,7,8,9,10),k=5))

Importing module random. Giving a list. Using random.choices to get the weighted random choice. Here we are giving relative weight.

Output

[20, 5, 30, 15, 20]

Code: Giving cumulative weights

import random
lst=[5,10,15,20,25,30,35,40,45,50]
print(random.choices(lst,cum_weights=(1,3,6,10,15,21,28,36,45,55),k=5))

Importing module random. Giving a list. Using random.choices to get the weighted random choice. Here we are giving cumulative weight.

Output

[45, 45, 50, 10, 45]

Using loops to get the weighted random

import random
lst=["Python", "Java", "C++", "CSS"]
for n in range(4):
    s=random.choices(lst,cum_weights=(3,6,9,12),k=3)
    print("In iteration",n,"Weighted Random is:", s)

Importing module random. Giving a list. Using random.choices to get the weighted random choice. Here we are giving cumulative weight. We are iterating the weighted random choice.

Output

In iteration 0 Weighted Random is: ['Python', 'CSS', 'Python']
In iteration 1 Weighted Random is: ['Java', 'Java', 'CSS']
In iteration 2 Weighted Random is: ['CSS', 'CSS', 'Python']
In iteration 3 Weighted Random is: ['Python', 'Python', 'CSS']

More to Know: Getting Weighted Random for Coin

import random
sides=["Head","Tail"]
for n in range(4):
    print(random.choices(sides,cum_weights=(0.61,1.00),k=5))

This code is useful to get the weighted random for coins. First, declaring the sides of the coin. Using cumulative weight to get the weighted random in python. The probability for a head is 0.56 and for the tail 0.44 (1.00-0.56).

Output

['Head', 'Head', 'Head', 'Tail', 'Head']
['Tail', 'Head', 'Head', 'Tail', 'Head']
['Tail', 'Head', 'Tail', 'Head', 'Head']
['Head', 'Head', 'Tail', 'Head', 'Tail']

Using random.module() in the form of class

import random
class WeightedRandom:
    def __init__(self,weight):
        self.size=0.0
        self.weight=[]
        for element,weight in weight.items():
            self.size=self.size+weight
            self.weight.append((self.size,element))
    def random(self):
        a=random.random()*self.size
        for ceil,element in self.weight:
            if ceil>a:
                return element
weights= {'X': 5.0, 'Y': 7.0, 'Z': 4.0}
b=WeightedRandom(weights)
print("The weights are:")
print(weights)
iterations={'X': 0, 'Y': 0, 'Z': 0}
for i in range(100):
    iterations[b.random()]+=1
print ("After 100 rounds of iteration:")
print (iterations)
for i in range(1000):
    iterations[b.random()]+=1
print ("After 1000 rounds of iteration:")
print (iterations)
for i in range(10000):
    iterations[b.random()]+=1
print ("After 10000 rounds of iteration:")
print (iterations)

Output

The weights are:
{'X': 5.0, 'Y': 7.0, 'Z': 4.0}
After 100 rounds of iteration:
{'X': 30, 'Y': 35, 'Z': 35}
After 1000 rounds of iteration:
{'X': 367, 'Y': 451, 'Z': 282}
After 10000 rounds of iteration:
{'X': 3494, 'Y': 4833, 'Z': 2773}

Using NumPy library to get the weighted random in python

random.choices() module is only applicable for the version of 3.6 and above. If we want to implement in the older version of 3.6, we have to go with this NumPy library.

Syntax

numpy.random.choice(a, size=None, replace=True, p=None)

Parameters

  • a – list, tuple, or string
  • size – length
  • p – probability value

Code

import numpy as np  
lst = [3,7,1,9]
print(np.random.choice(lst,4,p=[0.50,0.30,0.05,0.15]))

Output

[3 7 9 7]

Points to remember while implementing weighted random in python

  • The relative or cumulative weight must be specified.
  • If the weight is not specified random.choice() will take the elements that have equal probability.
  • The length of the list or tuple or string must equal the length of the relative weight or cumulative weight.
  • Either relative or cumulative weight should be specified. Don’t specify both at the same time.
  • The weights are always positive.
  • While using the NumPy library, the sum of all the probabilities should be equal to 1.
  • In the Numpy library, the size of a and p must be equal.

1. What are the methods available to get the weighted random in python?

There are two methods available to get the weighted random. They are, by using the random.module() and numpy library.

2. What happens if both the relative and cumulative weights are specified at the same time?

It will display the typeError to the user.

3. What happens if the size of a and p are not equal in the numpy library?

It will display the ValueError.

4. In which version of python random.choice() is introduced?

random.choice() is introduced in a random module in python 3.6

Conclusion

We have come to the end o the article. Here we have learned about how to get the weighted random in python? With that, we got a lot of information about weighted random. We hope this article is straightforward and understandable.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments