我正在使用 Python 的 numpy.random
模块中的 randn
和 normal
函数。这些功能与我在 http://docs.scipy.org 中读到的非常相似。手册(它们都涉及高斯分布),但是我应该注意哪些细微的差异?如果是这样,在什么情况下使用特定功能会更好?
最佳答案
说明
查看您在问题中链接的文档,我将重点介绍一些关键差异:
正常:
numpy.random.normal(loc=0.0, scale=1.0, size=None)
# Draw random samples from a normal (Gaussian) distribution.
# Parameters :
# loc : float -- Mean (“centre”) of the distribution.
# scale : float -- Standard deviation (spread or “width”) of the distribution.
# size : tuple of ints -- Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
因此,在这种情况下,您正在生成 GENERIC 正态分布(稍后会详细说明这意味着什么)。
兰德:
numpy.random.randn(d0, d1, ..., dn)
# Return a sample (or samples) from the “standard normal” distribution.
# Parameters :
# d0, d1, ..., dn : int, optional -- The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned.
# Returns :
# Z : ndarray or float -- A (d0, d1, ..., dn)-shaped array of floating-point samples from the standard normal distribution, or a single such float if no parameters were supplied.
在这种情况下,您正在生成 SPECIFIC 正态分布,即标准分布。
(简要)数学
现在是一些数学,这是真正需要了解您的问题的核心:
正态分布是其中值更有可能出现在平均值附近的分布。自然界有很多这样的案例。例如,达拉斯 6 月份的平均高温是 95 华氏度。它可能在一年内达到 100 甚至 105 的平均温度,但更常见的是接近 95 或 97。类似地,它可能会低至80,但更有可能是 85 或 90。
因此,它与均匀分布(滚动一个诚实的 6 面骰子)有着根本的不同。
标准正态分布只是平均值为0,方差(变化的数学术语)为1的正态分布。
所以,
numpy.random.normal(size= (10, 10))
和写作完全一样
numpy.random.randn(10, 10)
因为 numpy.random.normal
的 default 值(loc= 0, scale= 1)实际上是 standard 分布。
历史
为了使事情更加困惑,如 numpy random documentation状态:
sigma * np.random.randn(...) + mu
与
相同np.random.normal(loc= mu, scale= sigma, ...)
问题确实是特化:在统计学中,高斯分布如此很常见,以至于出现了一些术语来进行讨论:
- 许多分布都是高斯分布,以至于高斯分布被认为是正态分布。
- 良好的建模,尤其是线性建模,要求所有元素“大小相同”(均值和方差相似)。因此,将分布重新调整为
mean=0
和variance=1
成为标准实践。
*最后注:我使用术语方差来数学描述变化。有人说标准差。方差简单地等于标准差的平方。由于标准分布的方差 = 1,在这种标准分布的情况下,variance == standard deviation
。
关于Python randn 和 normal 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21738383/