关于python:np.random.rand与np.random.random

np.random.rand vs np.random.random

我发现Python(及其生态系统)充满了奇怪的约定和不一致之处,这是另一个示例:

np.random.rand

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

np.random.random

Return random floats in the half-open interval [0.0, 1.0). Results are from the"continuous uniform" distribution over the stated interval.

??? 到底有什么区别?


首先请注意,numpy.random.random实际上是numpy.random.random_sample的别名。我将在下面使用后者。 (有关更多别名,请参见此问题和答案。)

这两个函数均根据[0,1)上的均匀分布生成样本。唯一的区别在于参数的处理方式。使用numpy.random.rand时,输出数组每个维度的长度是一个单独的参数。对于numpy.random.random_sample,shape参数是单个元组。

例如,要创建形状为(3,5)的样本数组,您可以编写

1
sample = np.random.rand(3, 5)

要么

1
sample = np.random.random_sample((3, 5))

(真的,就是这样。)

更新资料

从1.17版开始,NumPy具有新的随机API。从[0,1)上的均匀分布生成样本的推荐方法是:

1
2
3
4
>>> rng = np.random.default_rng()  # Create a default Generator.
>>> rng.random(size=12)  # Generate 10 samples.
array([0.00416913, 0.31533329, 0.19057857, 0.48732511, 0.40638395,
       0.32165646, 0.02597142, 0.19788567, 0.08142055, 0.15755424])

新的Generator类没有rand()random_sample()方法。有一个uniform()方法,允许您指定分布的下限和上限。例如。

1
2
3
>>> rng.uniform(1, 2, size=10)
array([1.75573298, 1.79862591, 1.53700962, 1.29183769, 1.16439681,
       1.64413869, 1.7675135 , 1.02121057, 1.37345967, 1.73589452])

numpy.random命名空间中的旧功能将继续起作用,但是它们被认为是"冻结的",没有正在进行的开发。如果您正在编写新代码,而不必支持1.17之前的numpy版本,则建议您使用新的随机API。