问题描述
我知道如果我使用相同的种子,numpy.random.seed(seed)
将输出相同的数字.我的问题是,这会随着时间的推移而改变吗?如果我明天再次尝试调用它,它是否仍会输出与昨天相同的一组随机数?
np.random
文档描述了所使用的 PRNG.显然,MT19937
有部分切换 到 PCG64
在最近的过去.如果您想要一致性,您需要:
- 修复使用的 PRNG,以及
- 确保您使用的是本地句柄(例如
RandomState
、Generator
),这样对其他 外部库的任何更改都不会自己调用np.random
全局变量来搞砸.
在本例中,我们使用较新的BitGenerator
API,提供各种 PRNG 的选择.
from numpy.random import Generator, PCG64rg = 发电机(PCG64(1234))
可以如下使用:
>>>rg.uniform(0, 10, 10)数组([9.767, 3.802, 9.232, 2.617, 3.191, 1.181, 2.418, 3.185, 9.641,2.636])如果我们多次重新运行它(即使在同一个 REPL 中!),我们将始终获得相同的随机数生成器.PCG64 与 MT19937 一样,提供以下保证:
兼容性保证
PCG64 保证固定的种子并将始终产生相同的随机整数流.
虽然,正如@user2357112 支持 Monica 所指出的那样,对使用随机整数序列(例如 np.random.Generator.uniform
)的随机 API 函数的更改仍然存在技术上可行,但不太可能.
为了生成多个生成器,可以利用SeedSequence.spawn(k)
生成k
个不同的SeedSequence
s.这对于一致的并发计算很有用:
from numpy.random import Generator, PCG64, SeedSequencesg = 种子序列(1234)rgs = [Generator(PCG64(s)) for s in sg.spawn(10)]
I know that numpy.random.seed(seed)
will output the same numbers if I use the same seed. My question is, does this change over time? If I try to call it again tomorrow, will it still output the same set of random numbers as yesterday?
The np.random
documentation describes the PRNGs used. Apparently, there was a partial switch from MT19937
to PCG64
in the recent past. If you want consistency, you'll need to:
- fix the PRNG used, and
- ensure that you're using a local handle (e.g.
RandomState
,Generator
) so that any changes to other external libraries don't mess things up by callingnp.random
globals themselves.
In this example, we make use of the newer BitGenerator
API, which provides a selection of various PRNGs.
from numpy.random import Generator, PCG64
rg = Generator(PCG64(1234))
Which may be used as follows:
>>> rg.uniform(0, 10, 10)
array([9.767, 3.802, 9.232, 2.617, 3.191, 1.181, 2.418, 3.185, 9.641,
2.636])
If we re-run this any number of times (even within the same REPL!), we will always obtain the same random number generator. PCG64, like MT19937, provides the following guarantee:
Though, as @user2357112 supports Monica noted, changes to the random API functions that use the random integer sequence (e.g. np.random.Generator.uniform
) are still technically possible, though unlikely.
In order to generate multiple generators, one can make use of SeedSequence.spawn(k)
to generate k
different SeedSequence
s. This is useful for consistent concurrent computations:
from numpy.random import Generator, PCG64, SeedSequence
sg = SeedSequence(1234)
rgs = [Generator(PCG64(s)) for s in sg.spawn(10)]
这篇关于numpy.random.seed() 每次总是给出相同的随机数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!