2015-04-22 52 views
2

我的任務是編寫一個名爲random_line的函數,該函數爲具有正態分佈N(0,σ^ 2)的y方向隨機噪聲的線創建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 
+0

退房'scipy.stats'爲從不同分佈產生值的方法,對於你想要的隨機正態分佈值'scipy.stats.norm.rvs(size = whatever) – Marius

回答

0

檢出Python標準庫中的random.normalvariate。

1

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)