gpt4 book ai didi

python - 跨平台 numpy.random.seed()

转载 作者:行者123 更新时间:2023-12-02 13:00:49 24 4
gpt4 key购买 nike

docs说:

Compatibility Guarantee A fixed seed and a fixed series of calls to ‘RandomState’ methods using the same parameters will always produce the same results up to roundoff error except when the values were incorrect. Incorrect values will be fixed and the NumPy version in which the fix was made will be noted in the relevant docstring. Extension of existing parameter ranges and the addition of new parameters is allowed as long the previous behavior remains unchanged.

没有提及操作系统。

如果我在windows和linux上调用np.random.seed(42),之后生成的随机数会相同吗?64 位 Ubuntu 的不同版本之间是否相同?

我假设 rng 使用系统库,因此代码可能不可移植。如果这是真的,有解决办法吗?我知道这可能会很丑陋,就像将 linux rng 系统更改为模拟 Windows 的系统一样。但我已经准备好接受创造性的解决方案。

最佳答案

更新自numpy v1.17 (2019 年中):
跨平台的结果应该是相同的,但跨 numpy 版本则不同。

np.random.seed被描述为“便利的遗留功能”;它和更新/推荐的替代方案 np.random.default_rng不能再依赖于在 numpy 版本中产生相同的结果,除非专门使用 np.random.RandomState 提供的旧版/兼容性 API 。虽然 RandomState 模块保证提供一致的结果,但它不会通过算法(或正确性)改进进行更新,并且不鼓励在单元测试和向后兼容性之外使用。

参见NEP 0019: Random number generator policy 。这实际上是一本不错的读物:)摘要如下:

For the past decade, NumPy has had a strict backwards compatibility policy for the number stream of all of its random number distributions. Unlike other numerical components in numpy, which are usually allowed to return different when results when they are modified if they remain correct, we have obligated the random number distributions to always produce the exact same numbers in every version. The objective of our stream-compatibility guarantee was to provide exact reproducibility for simulations across numpy versions in order to promote reproducible research. However, this policy has made it very difficult to enhance any of the distributions with faster or more accurate algorithms. After a decade of experience and improvements in the surrounding ecosystem of scientific software, we believe that there are now better ways to achieve these objectives. We propose relaxing our strict stream-compatibility policy to remove the obstacles that are in the way of accepting contributions to our random number generation capabilities.

这已在 numpy 中实现。截至当前编写(numpy 版本 1.22),numpy.random.default_rng() 使用默认的 BitGenerator 构造一个新的 Generator。但在np.random.Generator的描述中,附上以下指导:

No Compatibility Guarantee

Generator does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change.

因此,使用np.random.default_rng()将为跨平台的相同版本的numpy保留随机数,但不能跨版本。确保可重复性的最佳实践是保留您的确切环境,例如在 docker 容器中。除此之外,存储随机生成的数据的结果并在下游工作流程中使用保存的结果可以帮助提高可重复性,尽管这当然不会像 Docker 容器那样让您在工作流程后期免于 API 更改。

关于python - 跨平台 numpy.random.seed(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40676205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com