pul*_*tag 6 python random numpy
我运行以下代码:
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,))
Run Code Online (Sandbox Code Playgroud)
我得到的输出如下:
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])
Run Code Online (Sandbox Code Playgroud)
idx1和idx1S匹配,但idx2和idx2S不匹配.我希望一旦我为随机数生成器播种并重复相同的命令序列 - 它应该产生相同的随机数序列.这不是真的吗?或者还有其他我想念的东西?
你混淆RandomState使用seed.您的第一行构造一个对象,然后您可以将其用作随机源.例如,我们制作
>>> rnd = np.random.RandomState(3)
>>> rnd
<mtrand.RandomState object at 0xb17e18cc>
Run Code Online (Sandbox Code Playgroud)
然后
>>> 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])
Run Code Online (Sandbox Code Playgroud)
[我不明白为什么你idx1和idx1S同意-但你实际上并没有发布一个自包含的成绩单,所以我怀疑用户错误.]
如果要影响全局状态,请使用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])
Run Code Online (Sandbox Code Playgroud)
使用特定RandomState对象起初可能看起来不太方便,但是当您需要可以调整的不同熵流时,它会使很多事情变得更容易.
我认为你应该使用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])
Run Code Online (Sandbox Code Playgroud)
基本上,您创建rRandomState 的实例并进一步使用它.可以看出,重新生成产生相同的结果.