绘制具有高斯噪声的线



我的任务是编写一个名为 random_line 的函数,该函数为具有 y 方向随机噪声且具有正态分布 N(0,σ^2) 的线创建 x 和 y 数据:y=mx+b+N(0,σ^2).

我现在的问题与数学相关,而不是与编程相关。 要创建我的 ydata 点,我猜我必须将我的 x 个数据点数组代入上述等式。 但是,我不知道如何计算 N(0,σ^2) 部分。 有什么想法吗?

def random_line(m, b, sigma, size=10):
    """Create a line y = m*x + b + N(0,sigma**2) between x=[-1.0,1.0]
    Parameters
    ----------
    m : float
        The slope of the line.
    b : float
        The y-intercept of the line.
    sigma : float
        The standard deviation of the y direction normal distribution noise.
    size : int
        The number of points to create for the line.
    Returns
    -------
    x : array of floats
        The array of x values for the line with `size` points.
    y : array of floats
        The array of y values for the lines with `size` points.
    """
    xdata = np.linspace(-1.0,1.0,size)
    ydata = 'xxxxxxx'
    return xdata, ydata

使用 scipy.stats 中的发行版,很容易创建正态分布错误,使您可以轻松地将它们添加到其他 numpy 数组中,例如 xdata

import scipy.stats
import numpy as np
import matplotlib.pyplot as plt
def random_line(m, b, sigma, size=10):
    xdata = np.linspace(-1.0,1.0,size)
    # Generate normally distributed random error ~ N(0, sigma**2)
    errors = scipy.stats.norm.rvs(loc=0, scale=sigma, size=size)
    ydata = m * xdata + b + errors
    return xdata, ydata
xs, ys = random_line(2, 3, 2, size=50)
# Plot to see how closely the values fit the 
#   original line
fig, ax = plt.subplots()
ax.plot(xs, ys, 'o')
ax.plot(xs, 2 * xs + 3)

查看 Python 标准库中的 random.normalvariate。

最新更新