新增或更改#
NumPy 1.17.0 引入了 Generator 作为 旧版 RandomState 的改进替代品。以下是两种实现的快速比较。
功能 |
旧版等效功能 |
备注 |
|
||
访问 还支持许多其他分布。 |
||
使用 |
正态、指数和伽马生成器使用 256 步 Ziggurat 方法,这些方法在
standard_normal,standard_exponential或standard_gamma中比 NumPy 的默认实现快 2-10 倍。由于算法的改变,使用Generator无法精确复现这些分布或依赖于它们的任何分布方法的随机值。
In [1]: import numpy.random
In [2]: rng = np.random.default_rng()
In [3]: %timeit -n 1 rng.standard_normal(100000)
...: %timeit -n 1 numpy.random.standard_normal(100000)
...:
1.02 ms +- 9.03 us per loop (mean +- std. dev. of 7 runs, 1 loop each)
1.75 ms +- 15.3 us per loop (mean +- std. dev. of 7 runs, 1 loop each)
In [4]: %timeit -n 1 rng.standard_exponential(100000)
...: %timeit -n 1 numpy.random.standard_exponential(100000)
...:
487 us +- 6.98 us per loop (mean +- std. dev. of 7 runs, 1 loop each)
1.25 ms +- 6.35 us per loop (mean +- std. dev. of 7 runs, 1 loop each)
In [5]: %timeit -n 1 rng.standard_gamma(3.0, 100000)
...: %timeit -n 1 numpy.random.standard_gamma(3.0, 100000)
...:
1.85 ms +- 24.4 us per loop (mean +- std. dev. of 7 runs, 1 loop each)
3.42 ms +- 27.1 us per loop (mean +- std. dev. of 7 runs, 1 loop each)
integers现在是生成离散均匀分布的整数随机数的标准方法。这取代了randint和已弃用的random_integers。rand和randn方法仅通过旧版RandomState可用。Generator.random现在是生成浮点随机数的标准方法,它取代了RandomState.random_sample,sample, andranf,所有这些都是别名。这与 Python 的random.random一致。所有
BitGenerator都可以通过 CTypes (ctypes) 和 CFFI (cffi) 生成double、uint64和uint32。这使得这些BitGenerator可以在 numba 中使用。可以通过 Cython 在下游项目中使用
BitGenerator。所有
BitGenerator都使用SeedSequence将种子整数转换为初始状态。可选的
dtype参数,它接受np.float32或np.float64,以便为选定的分布生成单精度或双精度均匀随机变量。integers接受一个dtype参数,它可以接受任何有符号或无符号整数dtype。正态分布(
standard_normal)标准伽马分布(
standard_gamma)标准指数分布(
standard_exponential)
In [6]: rng = np.random.default_rng()
In [7]: rng.random(3, dtype=np.float64)
Out[7]: array([0.15428534, 0.69863672, 0.45724786])
In [8]: rng.random(3, dtype=np.float32)
Out[8]: array([0.1729908 , 0.0745824 , 0.42687505], dtype=float32)
In [9]: rng.integers(0, 256, size=3, dtype=np.uint8)
Out[9]: array([183, 218, 161], dtype=uint8)
可选的
out参数,允许为选定的分布填充现有数组均匀分布(
random)正态分布(
standard_normal)标准伽马分布(
standard_gamma)标准指数分布(
standard_exponential)
这允许多线程使用合适的
BitGenerator并行地分块填充大型数组。
In [10]: rng = np.random.default_rng()
In [11]: existing = np.zeros(4)
In [12]: rng.random(out=existing[:2])
Out[12]: array([0.99546415, 0.1408341 ])
In [13]: print(existing)
[0.99546415 0.1408341 0. 0. ]
可选的
axis参数,用于choice,permutation和shuffle等方法,它控制对多维数组执行操作的轴。
In [14]: rng = np.random.default_rng()
In [15]: a = np.arange(12).reshape((3, 4))
In [16]: a
Out[16]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [17]: rng.choice(a, axis=1, size=5)
Out[17]:
array([[ 2, 2, 3, 2, 1],
[ 6, 6, 7, 6, 5],
[10, 10, 11, 10, 9]])
In [18]: rng.shuffle(a, axis=1) # Shuffle in-place
In [19]: a
Out[19]:
array([[ 3, 1, 2, 0],
[ 7, 5, 6, 4],
[11, 9, 10, 8]])
添加了从复数正态分布 (complex_normal) 采样的功能