randn和normal之间的Python差异

Med*_*ata 23 python numpy

我正在使用Python 模块中的函数randnnormal函数numpy.random.这些函数与我在http://docs.scipy.org手册中读到的函数非常相似(它们都涉及高斯分布),但是我应该注意哪些更微妙的差异?如果是这样,在什么情况下我会更好地使用特定的功能?

Mik*_*son 49

我是一名有时编码的统计学家,反之亦然,所以这是我能够准确回答的问题.

查看您在问题中链接的文档,我将重点介绍一些主要差异:

正常:

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.
Run Code Online (Sandbox Code Playgroud)

因此,在这种情况下,您将生成GENERIC正态分布(有关后面的含义的详细信息).

randn:

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.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将生成SPECIFIC正态分布,即标准分布.


现在有一些数学,这是你的问题的核心所在:

正态分布是这样的分布,其中值更可能发生在平均值附近.本质上有很多这种情况.例如,6月份达拉斯的平均高温,即95华氏度.它可能达到100,甚至一年内平均105,但更典型的是接近95或97.同样,它可能达到低至80,但85或90更有可能.

因此,它与统一分布(滚动诚实的6面模具)根本不同.


标准正态分布是只是一个普通的分布,其中平均值为0和方差(用于变化的数学术语)为1.

所以,

numpy.random.normal(size= (10, 10))
Run Code Online (Sandbox Code Playgroud)

与写作完全相同

numpy.random.randn(10, 10)
Run Code Online (Sandbox Code Playgroud)

因为默认值(loc = 0,scale = 1)numpy.random.normal实际上是标准分布.

更令人困惑的是,numpy随机文档指出:

sigma * np.random.randn(...) + mu
Run Code Online (Sandbox Code Playgroud)

是相同的

np.random.normal(loc= mu, scale= sigma, ...)
Run Code Online (Sandbox Code Playgroud)

*最后的注释:我使用术语方差来数学地描述变化.有些人说标准偏差.方差简单地等于标准差的平方.由于标准分布的方差= 1,因此在标准分布的情况下,variance == standard deviation.


M4r*_*ini 19

randn似乎从一些标准化的正态分布(均值0和方差1)给出分布. normal需要更多参数以进行更多控制.所以rand似乎只是一个便利功能

  • 他们最后调用相同的C函数(`rk_gauss`).我认为`randn`主要是为了让MATLAB转换得很开心.MATLAB`rannd`似乎或多或少相同. (3认同)