条件随机数生成器 python numpy

Conditional random number generator python numpy

我想创建一个随机数生成器,但有条件。

代码如下;

s_weights = []
num = 3
limit = 50000
np.random.seed(101)

for x in range(limit):
    weights = np.random.random(num)
    weights /= np.sum(weights)
    s_weights.append(weights)

它 returns 我 50.000 个 3 个权重 (3,) 的 numpy 数组列表,如下所示

0.429134083359603413e-01 5.115615408184341906e-01 2.552505084560561729e-02

我想用 >=0.60

的规则限制第一个权重

第一个权重应该在 0.60 - 1.00 之间变化,其他两个应该在 0.00 - 1.00 之间变化

如何修改代码?

提前致谢

您可以缩放第一个权重,然后生成其他权重以遵守 求和为 1 的限制。 更新后的代码如下:

import numpy as np
s_weights = []
num = 3
limit = 50000
np.random.seed(101)
offset = 0.6

for x in range(limit):
    # By default all the weights go from 0 to 1
    weights = np.random.random(num)
    # shift and scale the first one to go from 0.6 to 1
    # in the case offset is 0.6 then it is x*0.4 + 0.6, which for 0 in 0 to 1 always falls in 0.6 to 1
    weights[0] = weights[0]*(1-offset) + offset 
    # Scales the second weight respecting that the sum must be 1
    second_max = 1-weights[0]
    weights[1] = weights[1]*second_max
    # third component should be equal to the value we need to complete 1
    weights[2] = 1-weights[0]-weights[1]
    s_weights.append(weights)
print(weights)
print(sum(weights))

一组权重的示例输出,它们的总和如下

[0.84739308 0.11863514 0.03397177]
1.0