【问题标题】:How to replicate np.random result directly?如何直接复制 np.random 结果?
【发布时间】:2020-07-06 03:52:15
【问题描述】:
import numpy as np
np.seed(1)
a=np.random.randint(10)
b=np.random.randint(10)

我知道设置随机种子后,每次运行这段代码时,a和b都会分别初始化为某个固定值。

我的问题是:在新的运行中,如何不先生成a的值而直接生成b的值?

在我看来,我需要这样的东西:

import numpy as np
np.seed(1)
a = np.random.randint(10)
# DO SOMETHING to get some situation-specific information, something like a new seed

所以在新的运行中,我可以这样做:

# DO SOMETHING to load or set that situation-specific information
b = np.random.randint(10)

有什么办法吗?

【问题讨论】:

    标签: python numpy random random-seed


    【解决方案1】:

    IIUC,使用numpy.random.get_stateset_state

    import numpy as np
    
    a = np.random.randint(10)
    a
    # 5
    
    # Now get the current state
    after_a = np.random.get_state()
    
    b = np.random.randint(10)
    b
    # 8
    

    # After some work...
    
    np.random.set_state(after_a)
    
    b = np.random.randint(10)
    b
    # 8
    

    【讨论】:

    • 这正是我想要的。谢谢。
    【解决方案2】:

    你可以只运行随机函数,不需要为a设置它。

    第一次

    np.random.randint(10)
    # DO SOMETHING to load or set that situation-specific information
    b = np.random.randint(10)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 2021-07-10
      • 1970-01-01
      相关资源
      最近更新 更多