随机 Generator#

Generator 提供了对各种分布的访问,并且可以替代 RandomState .两者之间的主要区别在于 Generator 依赖于额外的 BitGenerator 来管理状态并生成随机位,然后将其转换为来自有用分布的随机值. Generator 使用的默认 BitGenerator 是 PCG64 .可以通过将实例化的 BitGenerator 传递给 Generator 来更改 BitGenerator.如果传递了 Generator ,它将保持不变地返回.如果传递了传统的 RandomState 实例,它将被强制转换为 Generator .

numpy.random.default_rng(seed=None)#

使用默认的 BitGenerator (PCG64) 构造一个新的 Generator.

参数:
seed{None, int, array_like[ints], SeedSequence, BitGenerator, Generator, RandomState}, optional

用于初始化 BitGenerator 的种子.如果为 None,则将从操作系统中提取新的,不可预测的熵.如果传递 intarray_like[ints] ,则所有值必须为非负数,并将传递给 SeedSequence 以派生初始 BitGenerator 状态.也可以传入 SeedSequence 实例.此外,当传递 BitGenerator 时,它将被 Generator 包裹.如果传递 Generator ,它将保持不变地返回.当传递传统的 RandomState 实例时,它将被强制转换为 Generator .

返回:
Generator

已初始化的生成器对象.

注释

如果 seed 不是 BitGeneratorGenerator ,则会实例化一个新的 BitGenerator .此函数不管理默认的全局实例.

有关播种的更多信息,请参见 播种和熵 .

示例

default_rng 是随机数类 Generator 的推荐构造函数.以下是我们可以使用 default_rngGenerator 类构建随机数生成器的几种方法.

这里我们使用 default_rng 生成一个随机浮点数:

>>> import numpy as np
>>> rng = np.random.default_rng(12345)
>>> print(rng)
Generator(PCG64)
>>> rfloat = rng.random()
>>> rfloat
0.22733602246716966
>>> type(rfloat)
<class 'float'>

这里我们使用 default_rng 生成 3 个介于 0(包括)和 10(不包括)之间的随机整数:

>>> import numpy as np
>>> rng = np.random.default_rng(12345)
>>> rints = rng.integers(low=0, high=10, size=3)
>>> rints
array([6, 2, 7])
>>> type(rints[0])
<class 'numpy.int64'>

这里我们指定一个种子,以便我们获得可重现的结果:

>>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> print(rng)
Generator(PCG64)
>>> arr1 = rng.random((3, 3))
>>> arr1
array([[0.77395605, 0.43887844, 0.85859792],
       [0.69736803, 0.09417735, 0.97562235],
       [0.7611397 , 0.78606431, 0.12811363]])

如果我们退出并重新启动我们的 Python 解释器,我们将看到我们再次生成相同的随机数:

>>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> arr2 = rng.random((3, 3))
>>> arr2
array([[0.77395605, 0.43887844, 0.85859792],
       [0.69736803, 0.09417735, 0.97562235],
       [0.7611397 , 0.78606431, 0.12811363]])
class numpy.random.Generator(bit_generator)#

BitGenerator 的容器.

Generator 公开了许多用于生成从各种概率分布中提取的随机数的方法.除了特定于分布的参数外,每种方法都采用一个关键字参数 size ,该参数默认为 None .如果 sizeNone ,则生成并返回单个值.如果 size 是一个整数,则返回一个填充了生成值的 1-D 数组.如果 size 是一个元组,则填充具有该形状的数组并返回.

函数 numpy.random.default_rng 将实例化一个带有 numpy 默认 BitGeneratorGenerator .

无兼容性保证

Generator 不提供版本兼容性保证.特别是,随着更好的算法的演变,比特流可能会改变.

参数:
bit_generatorBitGenerator

用作核心生成器的 BitGenerator.

参见

default_rng

Generator 的推荐构造函数.

注释

Python stdlib 模块 :external+python random 包含伪随机数生成器,它具有许多与 Generator 中可用的方法类似的方法.它使用 Mersenne Twister,可以使用 MT19937 访问此位生成器. Generator 除了是 NumPy 感知的之外,还具有提供更多概率分布可供选择的优势.

示例

>>> from numpy.random import Generator, PCG64
>>> rng = Generator(PCG64())
>>> rng.standard_normal()
-0.203  # random

访问 BitGenerator 和 spawning#

bit_generator ]

获取生成器使用的位生成器实例

spawn (n_children)

创建新的独立子生成器.

简单随机数据#

integers (low[, high, size, dtype, endpoint])

返回 low (包含)到 high (不包含)之间的随机整数,如果 endpoint=True,则返回 low (包含)到 high (包含)之间的随机整数.

random ([size, dtype, out])

返回半开区间 [0.0, 1.0) 中的随机浮点数.

choice (a[, size, replace, p, axis, shuffle])

从给定数组中生成随机样本

bytes (length)

返回随机字节.

排列组合#

随机排列序列的方法有

shuffle (x[, axis])

通过随机排列数组的内容,就地修改数组或序列.

permutation (x[, axis])

随机置换一个序列,或返回一个置换的范围.

permuted (x[, axis, out])

沿着轴 axis 随机置换 x .

下表总结了这些方法的行为.

method

复制/原地操作

轴处理

shuffle

原地操作

如同1维

permutation

复制

如同1维

permuted

都可以(使用 ‘out’ 进行原地操作)

轴独立

以下小节提供了关于差异的更多细节.

原地操作 vs. 复制#

Generator.shuffleGenerator.permutation 之间的主要区别在于 Generator.shuffle 进行原地操作,而 Generator.permutation 返回一个副本.

默认情况下, Generator.permuted 返回一个副本.要使用 Generator.permuted 进行原地操作,请将同一个数组作为第一个参数和 out 参数的值传递.例如,

>>> import numpy as np
>>> rng = np.random.default_rng()
>>> x = np.arange(0, 15).reshape(3, 5)
>>> x 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> y = rng.permuted(x, axis=1, out=x)
>>> x 
array([[ 1,  0,  2,  4,  3],  # random
       [ 6,  7,  8,  9,  5],
       [10, 14, 11, 13, 12]])

请注意,当给出 out 时,返回值是 out :

>>> y is x
True

处理 axis 参数#

这些方法的一个重要区别是它们如何处理 axis 参数. Generator.shuffleGenerator.permutation 都将输入视为一维序列, axis 参数确定使用输入数组的哪个维度作为序列.在二维数组的情况下, axis=0 实际上会重新排列数组的行,而 axis=1 将重新排列列.例如

>>> import numpy as np
>>> rng = np.random.default_rng()
>>> x = np.arange(0, 15).reshape(3, 5)
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> rng.permutation(x, axis=1) 
array([[ 1,  3,  2,  0,  4],  # random
       [ 6,  8,  7,  5,  9],
       [11, 13, 12, 10, 14]])

请注意,列已"批量"重新排列:每列中的值没有更改.

Generator.permuted 方法处理 axis 参数的方式类似于 numpy.sort 处理它的方式.沿着给定轴的每个切片都与其他切片独立地进行置换.将以下 Generator.permuted 的使用示例与上面的 Generator.permutation 示例进行比较:

>>> import numpy as np
>>> rng = np.random.default_rng()
>>> rng.permuted(x, axis=1) 
array([[ 1,  0,  2,  4,  3],  # random
       [ 5,  7,  6,  9,  8],
       [10, 14, 12, 13, 11]])

在此示例中,每行中的值(即沿 axis=1 的值)已独立置换.这不是列的"批量"置换.

置换非 NumPy 序列#

Generator.shuffle 可以处理非 NumPy 序列.也就是说,如果给定一个不是 NumPy 数组的序列,它会原地置换该序列.

>>> import numpy as np
>>> rng = np.random.default_rng()
>>> a = ['A', 'B', 'C', 'D', 'E']
>>> rng.shuffle(a)  # shuffle the list in-place
>>> a 
['B', 'D', 'A', 'E', 'C']  # random

分布#

beta (a, b[, size])

从 Beta 分布中抽取样本.

binomial (n, p[, size])

从二项分布中抽取样本.

chisquare (df[, size])

从卡方分布中抽取样本.

dirichlet (alpha[, size])

从 Dirichlet 分布中抽取样本.

exponential ([scale, size])

从指数分布中抽取样本.

f (dfnum, dfden[, size])

从 F 分布中抽取样本.

gamma (shape[, scale, size])

从伽马分布中抽取样本.

geometric (p[, size])

从几何分布中抽取样本.

gumbel ([loc, scale, size])

从耿贝尔分布中抽取样本.

hypergeometric (ngood, nbad, nsample[, size])

从超几何分布中抽取样本.

laplace ([loc, scale, size])

从具有指定位置(或均值)和尺度(衰减)的拉普拉斯或双指数分布中抽取样本.

logistic ([loc, scale, size])

从逻辑分布中抽取样本.

lognormal ([mean, sigma, size])

从对数正态分布中抽取样本.

logseries (p[, size])

从对数级数分布中抽取样本.

multinomial (n, pvals[, size])

从多项分布中抽取样本.

multivariate_hypergeometric (colors, nsample)

从多元超几何分布生成变量.

multivariate_normal (mean, cov[, size, ...])

从多元正态分布中抽取随机样本.

negative_binomial (n, p[, size])

从负二项分布中抽取样本.

noncentral_chisquare (df, nonc[, size])

从非中心卡方分布中抽取样本.

noncentral_f (dfnum, dfden, nonc[, size])

从非中心 F 分布中抽取样本.

normal ([loc, scale, size])

从正态(高斯)分布中抽取随机样本.

pareto (a[, size])

从具有指定形状的Pareto II (AKA Lomax) 分布中抽取样本.

poisson ([lam, size])

从泊松分布中抽取样本.

power (a[, size])

从具有正指数 a - 1 的幂分布中抽取 [0, 1] 中的样本.

rayleigh ([scale, size])

从瑞利分布中抽取样本.

standard_cauchy ([size])

从 mode = 0 的标准柯西分布中抽取样本.

standard_exponential ([size, dtype, method, out])

从标准指数分布中抽取样本.

standard_gamma (shape[, size, dtype, out])

从标准 Gamma 分布中抽取样本.

standard_normal ([size, dtype, out])

从标准正态分布(均值=0,标准差=1)中抽取样本.

standard_t (df[, size])

从具有 df 自由度的标准学生 t 分布中抽取样本.

triangular (left, mode, right[, size])

从区间 [left, right] 上的三角分布中抽取样本.

uniform ([low, high, size])

从均匀分布中抽取样本.

vonmises (mu, kappa[, size])

从 von Mises 分布中抽取样本.

wald (mean, scale[, size])

从 Wald 或逆高斯分布中抽取样本.

weibull (a[, size])

从 Weibull 分布中抽取样本.

zipf (a[, size])

从 Zipf 分布中抽取样本.