Python全局随机种子vs Numpy生成器

eqoofvh9  于 2023-08-05  发布在  Python
关注(0)|答案(1)|浏览(122)

我目前在函数和单元测试中使用随机性。此外,有时函数应该支持joblib并行。我想知道使用numpy.random.seedGenerator有什么问题?
例如,假设我们有Generator模式:

# pseudocode
def do_something_with_seed(rng):
    rng = np.random.default_rng(rng)

# you can just call as is
do_something_with_seed(12345)

# I need to generate a seed sequence as I understand, when using parallelism
Parallel(do_something_with_seed(_rng) for _rng in rng.spawn(n_jobs))

字符串
接下来,假设我们使用np.random.seed模式

# pseudocode
def do_something_without_seed(seed):
    np.random.seed(seed)
    ...

# this requires you to always set the global seed before running this function
do_something_with_global_seed(12345)

# when using parallelism
random_seeds = np.random.randint(np.iinfo(np.int32).max, size=len(seeds))
Parallel(do_something_with_global_seed(seed) for seed in random_seeds)


正如我所看到的,性能,功能是相同的,只要你记得做正确的事情。是否有任何差异或原因,我们肯定需要/想要使用Generator模式?单元测试呢?

ie3xauqp

ie3xauqp1#

np.random.seed的文档中:
这是一个方便的遗留函数,用于支持使用单例RandomState的旧代码。最佳实践是使用专用的Generator示例,而不是直接在random模块中公开的随机变量生成方法。
换句话说,你应该使用Generator版本的原因是因为它是Numpy推荐你使用的较新版本。出于向后兼容的原因,旧方法仍然存在。

相关问题