【问题标题】:Conditional random number generator python numpy条件随机数生成器 python numpy
【发布时间】:2019-04-25 08:08:05
【问题描述】:

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

代码如下;

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 之间变化

如何修改代码?

提前致谢

【问题讨论】:

  • 这3个权重之和必须等于1

标签: python numpy random conditional generator


【解决方案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

【讨论】:

  • 非常感谢,但我忘了说所有的权重总和必须等于 1,它们就像百分比。
  • 我编辑了答案以适应数字总和为 1 的限制
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
相关资源
最近更新 更多