numpy.random 的 Generator 类和 np.random 方法有什么区别? [英] What is the difference between numpy.random's Generator class and np.random methods?

查看:189
本文介绍了numpy.random 的 Generator 类和 np.random 方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 numpy 的随机功能,通过调用诸如 np.random.choice()np.random.randint() 等方法.我刚刚发现了创建 default_rng 对象或其他 Generator 对象:

I have been using numpy's random functionality for a while, by calling methods such as np.random.choice() or np.random.randint() etc. I just now found about the ability to create a default_rng object, or other Generator objects:

from numpy.random import default_rng
gen = default_rng()
random_number = gen.integers(10)

到目前为止我会一直使用

So far I would have always used

np.random.randint(10)

相反,我想知道两种方式之间的区别是什么.

instead, and I am wondering what the difference between both ways is.

我能想到的唯一好处是跟踪多个种子,或者想要使用特定的 PRNG,但也许更通用的用例也存在差异?

The only benefit I can think of would be keeping track of multiple seeds, or wanting to use specific PRNGs, but maybe there are also differences for a more generic use-case?

推荐答案

numpy.random.* 函数(包括 numpy.random.binomial)使用全局跨应用程序共享的随机生成器对象.另一方面,default_rng() 是一个独立的 Generator 对象,不依赖于全局状态.

numpy.random.* functions (including numpy.random.binomial) make use of a global random generator object which is shared across the application. On the other hand, default_rng() is a self-contained Generator object that doesn't rely on global state.

如果您不关心应用程序中可重现的随机性",那么这两种方法暂时是等效的.尽管 NumPy 的新 RNG 政策 一般不鼓励使用全局状态,它没有弃用 1.17 版中的任何 numpy.random.* 函数,尽管 NumPy 的未来版本可能会.

If you don't care about reproducible "randomness" in your application, these two approaches are equivalent for the time being. Although NumPy's new RNG policy discourages the use of global state in general, it did not deprecate any numpy.random.* functions in version 1.17, although a future version of NumPy might.

还要注意,因为 numpy.random.* 函数依赖于非线程安全的全局随机生成器对象,所以这些函数 如果您的应用程序可能导致竞争条件使用多线程.(Generator 对象也不是线程安全的,但有一些方法可以通过多线程生成随机数,无需跨线程共享随机生成器对象.)

Note also that because numpy.random.* functions rely on a global random generator object that isn't thread-safe, these functions can cause race conditions if your application uses multiple threads. (Generator objects are not thread-safe, either, but there are ways to generate random numbers via multithreading, without the need to share random generator objects across threads.)

这篇关于numpy.random 的 Generator 类和 np.random 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆