如何用Python生成二维高斯分布?

43 投票
7 回答
150663 浏览
提问于 2025-04-17 03:52

我可以用 random.gauss(mu, sigma) 这个函数生成高斯数据,但我想知道怎么生成二维高斯数据?有没有类似的函数可以用?

7 个回答

27

我想用指数函数来添加一个近似值。这样可以直接生成一个二维矩阵,里面包含一个可移动的、对称的二维高斯分布。

我得说,这段代码是我在scipy的邮件列表档案里找到的,我稍微修改了一下。

import numpy as np

def makeGaussian(size, fwhm = 3, center=None):
    """ Make a square gaussian kernel.

    size is the length of a side of the square
    fwhm is full-width-half-maximum, which
    can be thought of as an effective radius.
    """

    x = np.arange(0, size, 1, float)
    y = x[:,np.newaxis]

    if center is None:
        x0 = y0 = size // 2
    else:
        x0 = center[0]
        y0 = center[1]

    return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / fwhm**2)

如果你想参考或者改进这段代码,可以在这里找到它的链接 这里。欢迎提交改进建议!

72

如果你能使用 numpy 这个库,可以用 numpy.random.multivariate_normal(mean, cov[, size]) 这个函数。

比如说,如果你想得到 10,000 个二维样本,可以这样做:

np.random.multivariate_normal(mean, cov, 10000)

这里的 mean.shape==(2,) 意思是均值是一个包含两个数的数组,而 cov.shape==(2,2) 意思是协方差是一个 2x2 的矩阵。

21

因为标准的二维高斯分布其实就是两个一维高斯分布的乘积,所以如果两个轴之间没有相关性(也就是说协方差矩阵是对角线的),那么只需要调用random.gauss两次就可以了。

def gauss_2d(mu, sigma):
    x = random.gauss(mu, sigma)
    y = random.gauss(mu, sigma)
    return (x, y)

撰写回答