NumPy随机种子生成不同的随机数

7
我运行了以下代码:

 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不匹配。我期望一旦我种下随机数生成器并重复相同的命令序列 - 它应该产生相同的随机数序列。这不是真的吗?还是我遗漏了什么其他的东西?

2个回答

10

您将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对象可能似乎不太方便,但当你需要不同的熵流并进行调整时,它会让很多事情变得更容易。


7
我认为您应该按以下方式使用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并将其进一步使用。如图所示,重新定居会产生相同的结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接