根据Random sampling 中的最新更新,首选方法是使用Generators 而不是RandomState。请参阅What's new or different 来比较这两种方法。其中一个关键变化是慢 Mersenne Twister 伪随机数生成器 (RandomState) 和基于新方法 (Generators) 中使用的不同算法 (BitGenerators) 的随机比特流之间的区别。
否则,生成随机numpy数组的步骤非常相似:
- 初始化随机发生器
您将初始化随机生成器,而不是 RandomState。 default_rng 是随机生成器的推荐构造函数,但您可以尝试其他方式。
import numpy as np
rng = np.random.default_rng(42)
# rng -> Generator(PCG64)
- 生成 numpy 数组
除了randint 方法,还有Generator.integers 方法,它现在是从离散均匀分布生成整数随机数的规范方法(参见已经提到的What's new or different 总结)。请注意,endpoint=True 使用 [low, high] 间隔进行采样,而不是默认的 [low, high)。
arr = rng.integers(-1, 1, size=10, endpoint=True)
# array([-1, 1, 0, 0, 0, 1, -1, 1, -1, -1])
如前所述,您必须每次初始化随机生成器(或随机状态)以生成相同的数组。因此,最简单的事情是定义类似于@mari756h 答案的自定义函数:
def get_array(low, high, size, random_state=42, endpoint=True):
rng = np.random.default_rng(random_state)
return rng.integers(low, high, size=size, endpoint=endpoint)
当您使用相同的参数调用函数时,您将始终得到相同的 numpy 数组。
get_array(-1, 1, 10)
# array([-1, 1, 0, 0, 0, 1, -1, 1, -1, -1])
get_array(-1, 1, 10, random_state=12345) # change random state to get different array
# array([ 1, -1, 1, -1, -1, 1, 0, 1, 1, 0])
get_array(-1, 1, (2, 2), endpoint=False)
# array([[-1, 0],
# [ 0, -1]])
根据您的需要,您可以使用get_array(-1, 1, size=(100, 2000))。