gpt4 book ai didi

python - 为什么 np.random.default_rng().permutation(n) 优于原始 np.random.permutation(n)?

转载 作者:行者123 更新时间:2023-12-04 15:25:08 26 4
gpt4 key购买 nike

Numpy documentationnp.random.permutation建议所有新代码使用 np.random.default_rng()来自随机生成器包。我在文档中看到,Random Generator 包已经标准化了围绕 BitGenerator 与使用 Mersenne Twister 生成的各种随机分布,我对此不太熟悉。

我看到了一个缺点,过去只需一行代码即可完成简单的排列:

np.random.permutation(10)

现在变成两行代码,这么简单的任务感觉有点别扭:

rng = np.random.default_rng()
rng.permutation(10)
  • 为什么这种新方法比以前的方法有所改进?
  • 为什么现有的方法不能像np.random.permutation只是包装这个新的首选方法?
  • 是否有充分的理由不将这种新方法用作单线法 np.random.default_rng().permutation(10) ,假设它没有被大量调用?
  • 是否有理由将现有代码切换到此方法?

最佳答案

一些上下文:

按逻辑顺序回答您的问题:

And why wouldn't existing methods like np.random.permutation just wrap this new preferred method?

可能是因为 backwards compatibility concerns .即使“顶级”API 不会发生变化,其内部结构也足以被视为兼容性中断。

Why is this new approach an improvement over the previous approach?

“默认情况下,生成器使用 PCG64 提供的位,它比 RandomState 中使用的旧版 MT19937 具有更好的统计属性。” (source)。 PCG64文档字符串提供更多技术细节。

Is there a good reason not to use this new method as a one-liner np.random.default_rng().permutation(10), assuming it's not being called at high volumes?

我非常同意,如果它是在模块启动时添加的,那么添加的代码行会有点笨拙。我只想指出 NumPy 文档确实在文档字符串示例中直接使用了这种形式,例如:

n = np.random.default_rng().standard_exponential((3, 8000))

细微的区别在于,一个是在模块加载/导入时实例化一个类,而在您的表单中它可能会稍后出现。但这应该是一个微小的差异(同样,假设它只使用一次或几次)。如果您查看 default_rng(seed)源,当使用 None 调用时,它仅在对 seed 进行几次快速检查后返回 Generator(PCG64(seed))

Is there an argument for switching existing code to this method?

因为我没有任何接近深度的技术知识来对算法进行很好的比较,而且还因为它取决于其他一些变量,比如你是否关心让你的下游代码与旧版本 NumPy 的兼容性,其中 default_rng() 根本不存在。

关于python - 为什么 np.random.default_rng().permutation(n) 优于原始 np.random.permutation(n)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62436859/

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