我想创建一个有条件的随机数生成器。
代码如下:
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)
它向我返回50.000个3个权重(3,)的numpy数组列表
0.429134083359603413e-01 5.115615408184341906e-01 2.552505084560561729e-02
我想用> = 0.60的规则限制第一重量
首重应在0.60-1.00之间变化,其他两项应在0.00-1.00之间变化
如何修改代码?
预先感谢
答案 0 :(得分:1)
您可以缩放第一个权重,然后生成其他权重以供参考 求和的限制为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