如何在Python中获得加权随机选择?
加权随机选择意味着根据该元素的概率从列表或数组中选择随机元素。我们可以为每个元素分配一个概率,并根据该元素被选择。通过这种方式,我们可以从列表中选择一个或多个元素,并且可以通过两种方式实现。
- 通过 random.choices()
- 通过 numpy.random.choice()
使用 Random.choices() 方法
Choices ()方法从列表中返回多个随机元素并进行替换。您可以使用 weights参数或cum_weights 参数权衡每个结果的可能性。
Syntax : random.choices(sequence, weights=None, cum_weights=None, k=1)
Parameters :
1. sequence is a mandatory parameter that can be a list, tuple, or string.
2. weights is an optional parameter which is used to weigh the possibility for each value.
3. cum_weights is an optional parameter which is used to weigh the possibility for each value but in this the possibility is accumulated
4. k is an optional parameter that is used to define the length of the returned list.
示例 1:
Python3
import random
sampleList = [100, 200, 300, 400, 500]
randomList = random.choices(
sampleList, weights=(10, 20, 30, 40, 50), k=5)
print(randomList)
Python3
import random
sampleList = [100, 200, 300, 400, 500]
randomList = random.choices(
sampleList, cum_weights=(5, 15, 35, 65, 100), k=5)
print(randomList)
Python
from numpy.random import choice
sampleList = [100, 200, 300, 400, 500]
randomNumberList = choice(
sampleList, 5, p=[0.05, 0.1, 0.15, 0.20, 0.5])
print(randomNumberList)
输出:
[200, 300, 300, 300, 400]
您也可以使用 cum_weight 参数。它代表交换权重。默认情况下,如果我们使用上述方法并发送权重,则此函数会将权重更改为可交换权重。所以要使程序快速使用 cum_weight。累积重量按以下公式计算:
let the relative weight of 5 elements are [5,10,20,30,35]
than there cum_weight will be [5,15,35,65,100]
例子:
Python3
import random
sampleList = [100, 200, 300, 400, 500]
randomList = random.choices(
sampleList, cum_weights=(5, 15, 35, 65, 100), k=5)
print(randomList)
输出:
[500, 500, 400, 300, 400]
使用 numpy.random.choice() 方法
如果您使用的Python版本早于 3.6 版本,则必须使用 NumPy 库来实现加权随机数。借助choice()方法,我们可以得到一维数组的随机样本,并返回numpy数组的随机样本。
Syntax: numpy.random.choice(list,k, p=None)
List: It is the original list from you have select random numbers.
k: It is the size of the returning list. i.e, the number of elements you want to select.
p: It is the probability of each element.
注意:所有元素的概率之和应等于 1。
例子:
Python
from numpy.random import choice
sampleList = [100, 200, 300, 400, 500]
randomNumberList = choice(
sampleList, 5, p=[0.05, 0.1, 0.15, 0.20, 0.5])
print(randomNumberList)
输出:
[200 400 400 200 400]