我发现 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
的别名.我将在下面使用后者。 (更多别名参见 this question and answer)
这两个函数都从 uniform distribution 生成样本在 [0, 1) 上。唯一的区别在于如何处理参数。与 numpy.random.rand
,输出数组的每个维度的长度是一个单独的参数。使用 numpy.random.random_sample
,shape 参数是单个元组。
例如,要创建一个形状为 (3, 5) 的样本数组,您可以这样写
sample = np.random.rand(3, 5)
hoặc
sample = np.random.random_sample((3, 5))
(真的,就是这样。)
gia hạn
从 1.17 版开始,NumPy 有一个新的 random API .从 [0, 1) 上的均匀分布生成样本的推荐方法是:
>>> rng = np.random.default_rng() # Create a default Generator.
>>> rng.random(size=10) # 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
lớp không rand()
hoặc random_sample()
phương pháp. có一个 uniform()
方法,允许您指定分布的下限和上限。例如
>>> 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
命名空间中的旧函数将继续工作,但它们被视为“卡住”,没有持续开发。如果您正在编写新代码,并且您不必支持 numpy 1.17 之前的版本,建议您使用新的随机 API。
Tôi là một lập trình viên xuất sắc, rất giỏi!