【问题标题】:NumPy random seed produces different random numbersNumPy 随机种子产生不同的随机数
【发布时间】:2015-03-29 01:45:11
【问题描述】:

我运行以下代码:

 np.random.RandomState(3)
 idx1 = np.random.choice(range(20),(5,))
 idx2 = np.random.choice(range(20),(5,))  
 np.random.RandomState(3)
 idx1S = np.random.choice(range(20),(5,))
 idx2S = np.random.choice(range(20),(5,))       

我得到的输出如下:

idx1:  array([ 2, 19, 19,  9,  4])  
idx1S: array([ 2, 19, 19,  9,  4])  

idx2:  array([ 9,  2,  7, 10,  6]) 
idx2S: array([ 5, 16,  9, 11, 15]) 

idx1 和 idx1S 匹配,但 idx2 和 idx2S 不匹配。我希望一旦我为随机数生成器播种并重复相同的命令序列 - 它应该产生相同的随机数序列。这不是真的吗?还是我还缺少其他东西?

【问题讨论】:

    标签: python numpy random


    【解决方案1】:

    您将RandomStateseed 混淆了。您的第一行构造了一个对象,然后您可以将其用作随机源。例如,我们制作

    >>> rnd = np.random.RandomState(3)
    >>> rnd
    <mtrand.RandomState object at 0xb17e18cc>
    

    然后

    >>> rnd.choice(range(20), (5,))
    array([10,  3,  8,  0, 19])
    >>> rnd.choice(range(20), (5,))
    array([10, 11,  9, 10,  6])
    >>> rnd = np.random.RandomState(3)
    >>> rnd.choice(range(20), (5,))
    array([10,  3,  8,  0, 19])
    >>> rnd.choice(range(20), (5,))
    array([10, 11,  9, 10,  6])
    

    [我不明白为什么你的 idx1idx1S 同意——但你实际上并没有发布一个独立的成绩单,所以我怀疑是用户错误。]

    如果你想影响全局状态,使用seed:

    >>> np.random.seed(3)
    >>> np.random.choice(range(20),(5,))
    array([10,  3,  8,  0, 19])
    >>> np.random.choice(range(20),(5,))
    array([10, 11,  9, 10,  6])
    >>> np.random.seed(3)
    >>> np.random.choice(range(20),(5,))
    array([10,  3,  8,  0, 19])
    >>> np.random.choice(range(20),(5,))
    array([10, 11,  9, 10,  6])
    

    使用特定的RandomState 对象一开始可能看起来不太方便,但是当您想要可以调整不同的熵流时,它会让很多事情变得更容易。

    【讨论】:

      【解决方案2】:

      我认为你应该如下使用 RandomState 类:

      In [21]: r=np.random.RandomState(3)
      
      In [22]: r.choice(range(20),(5,))
      Out[22]: array([10,  3,  8,  0, 19])
      
      In [23]: r.choice(range(20),(5,))
      Out[23]: array([10, 11,  9, 10,  6])
      
      In [24]: r=np.random.RandomState(3)
      
      In [25]: r.choice(range(20),(5,))
      Out[25]: array([10,  3,  8,  0, 19])
      
      In [26]: r.choice(range(20),(5,))
      Out[26]: array([10, 11,  9, 10,  6])
      

      基本上,您创建一个 RandomState 的实例 r 并进一步使用它。可以看出,重新安装会产生相同的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-15
        • 2012-11-02
        • 1970-01-01
        • 2018-06-04
        • 1970-01-01
        • 2011-09-30
        相关资源
        最近更新 更多