随机数 Generator#

Generator 提供了对各种分布的访问,并且可以替代 RandomState . 两者之间的主要区别在于 Generator 依赖于额外的 BitGenerator 来管理状态和生成随机位,然后将这些位转换为来自有用分布的随机值. Generator 使用的默认 BitGenerator 是 PCG64 . 可以通过将实例化的 BitGenerator 传递给 Generator 来更改 BitGenerator.

numpy.random.default_rng(seed=None)#

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

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

用于初始化 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)#

BitGenerators 的容器.

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

函数 numpy.random.default_rng 将实例化一个 Generator ,使用 numpy 的默认 BitGenerator .

没有兼容性保证

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

参数:
bit_generatorBitGenerator

用作核心生成器的 BitGenerator.

参见

default_rng

Generator 的推荐构造函数.

注释

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

示例

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

访问 BitGenerator 和衍生#

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

原地操作

如同 1d 数组

permutation

复制

如同 1d 数组

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])

从 Gamma 分布 中抽取样本.

geometric (p[, size])

从几何分布中抽取样本.

gumbel ([loc, scale, size])

从 Gumbel 分布中抽取样本.

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

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

laplace ([loc, scale, size])

从具有指定位置(或均值)和比例(衰减)的 Laplace 或双指数分布中抽取样本.

logistic ([loc, scale, size])

从 logistic 分布中抽取样本.

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])

从负二项分布中抽取 samples.

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 分布中抽取样本.