numpy.random 与 numpy.random 之间有什么区别。生成

What's the difference between numpy.random vs numpy.random.Generate

我最近一直在尝试模拟一些蒙特卡洛斯模拟并遇到了 numpy.random。检查指数生成器的 documentation 我注意到这是页面中的警告,它告诉

Generator.exponential should be used for new code.

尽管如此,numpy.random.exponential 仍然有效,但我无法 运行 Generator 对应。我收到以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-c4cc7e61aa98> in <module>
----> 1 np.random.Generator.exponential(2, 1000)

TypeError: descriptor 'exponential' for 'numpy.random._generator.Generator' objects doesn't apply to a 'int' object

我的问题是:

  1. 这两个有什么区别?

  2. 如何用Generator生成样本?

Generator referred to in the documentation is a class, introduced in NumPy 1.17: it's the core class responsible for adapting values from an underlying bit generator to generate samples from various distributions. numpy.random.exponential is part of the (now) legacyMersenne-Twister-based随机框架。您可能不应该担心很快就会删除遗留函数 - 这样做会破坏大量代码,但是 NumPy 开发人员建议对于 new 代码,您应该使用新系统,不是遗留系统。

您对系统更改的基本原理的最佳来源可能是 NEP 19:https://numpy.org/neps/nep-0019-rng-policy.html

要使用Generator.exponential as recommended by the documentation, you first need to create an instance of the Generator class. The easiest way to create such an instance is to use the numpy.random.default_rng()功能。

所以您想从以下内容开始:

>>> import numpy
>>> my_generator = numpy.random.default_rng()

此时,my_generatornumpy.random.Generator的一个实例:

>>> type(my_generator)
<class 'numpy.random._generator.Generator'>

并且您可以使用 my_generator.exponential 从指数分布中获取变量。在这里,我们从具有尺度参数 3.2(或等效地,比率 0.3125)的指数分布中抽取 10 个样本:

>>> my_generator.exponential(3.2, size=10)
array([6.26251663, 1.59879107, 1.69010179, 4.17572623, 5.94945358,
       1.19466134, 3.93386506, 3.10576934, 1.26095418, 1.18096234])

您的 Generator 实例当然也可以用于获取您需要的任何其他随机变量:

>>> my_generator.integers(0, 100, size=3)
array([56, 57, 10])