簡體   English   中英

用高斯噪聲繪制線條

[英]Plotting line with gaussian noise

我的任務是編寫一個名為random_line的函數,該函數為具有正態分布的y方向隨機噪聲的線創建x和y數據N(0,σ^ 2):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的發行版,可以輕松地創建正常分布的錯誤,使您可以輕松地將它們添加到xdata等其他numpy數組中:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM