【问题标题】:How do I create a deterministic Random number generator with numpy seed?如何使用 numpy 种子创建确定性随机数生成器?
【发布时间】:2015-12-24 21:49:05
【问题描述】:

据我了解,语法是

In[88]: np.random.seed(seed=0)

In[89]: np.random.rand(5) < 0.8
Out[89]: array([ True,  True,  True,  True,  True], dtype=bool)
In[90]: np.random.rand(5) < 0.8
Out[90]: array([ True,  True, False, False,  True], dtype=bool)

但是,当我运行 rand() 时,我得到了不同的结果。种子功能有什么我缺少的吗?

【问题讨论】:

标签: python numpy random


【解决方案1】:

想想发电机:

def gen(start):
    while True:
        start += 1
        yield start

这将不断地从您插入到生成器的数字中给出下一个数字。对于种子,这几乎是相同的概念。我尝试设置一个从中生成数据的变量,并且仍然保存其中的位置。让我们把它付诸实践:

>>> generator = gen(5)
>>> generator.next()
6
>>> generator.next()
7

如果要重启,还需要重启生成器:

>>> generator = gen(5)
>>> generator.next()
6

与 numpy 对象的想法相同。如果您希望随着时间的推移获得相同的结果,则需要使用相同的参数重新启动生成器。

>>> np.random.seed(seed=0)
>>> np.random.rand(5) < 0.8
array([ True,  True,  True,  True,  True], dtype=bool)
>>> np.random.rand(5) < 0.8
array([ True,  True, False, False,  True], dtype=bool)
>>> np.random.seed(seed=0) # reset the generator!
>>> np.random.rand(5) < 0.8
array([ True,  True,  True,  True,  True], dtype=bool)

【讨论】:

    猜你喜欢
    • 2015-11-17
    • 2013-08-28
    • 1970-01-01
    • 2015-03-11
    • 2021-05-15
    • 2012-09-01
    • 2013-07-20
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多