【问题标题】:Generating random data in python fitting given function在python拟合给定函数中生成随机数据
【发布时间】:2016-07-21 01:45:03
【问题描述】:

我想在 python 中生成数据,就好像它是一些实验点一样。我希望噪声呈指数下降,噪声呈正态分布。喜欢这张图片,但指数级:noisy polynomial data。 如果我简单地取指数曲线并添加一些高斯噪声并产生这样的随机误差会好吗

import numpy as np
errors = np.random.normal(0,1,100)

或者它可以以更智能的方式完成?

【问题讨论】:

    标签: python numpy random statistics gaussian


    【解决方案1】:

    这是解决问题的方法。我不知道这样做是否正确,但我还是这样做了:

    import numpy as np
    import matplotlib.pyplot as plt
    import scipy.stats as st
    import random 
    from scipy.optimize import curve_fit
    
    #number of data points
    n = 50
    
    #function
    def func(data):
        return 10*np.exp(-0.5*data)
    
    def fit(data, a, b):
        return a*np.exp(b*data)
    
    #define interval 
    a = 0
    b = 4
    
    #generate random data grid
    x = []
    for i in range(0, n):
        x.append(random.uniform(a, b))
    x.sort()
    
    #noise-free data points
    yclean = []
    for i in range(0, n):
        yclean.append(func(x[i]))
    
    #define mean, standard deviation, sample size for 0 noise and 1 errors
    mu0 = 0 
    sigma0 = 0.4
    mu1 = 0.5 
    sigma1 = 0.02
    
    #generate noise 
    noise = st.norm.rvs(mu0, sigma0, size = n)
    y = yclean + noise
    yerr = st.norm.rvs(mu1, sigma1, size = n)
    
    #now x and y is your data 
    #define analytic x and y
    xan = np.linspace(a, b, n)
    yan = []
    for i in range(0, n):
        yan.append(func(xan[i]))
    
    #now estimate fit parameters 
    #initial guesses
    x0 = [1.0, 1.0]
    #popt are list of optimal coefficients, pcov is covariation matrix
    popt, pcov = curve_fit(fit, x, y, x0, yerr)
    
    fity = []
    for i in range(0, n):
        fity.append(fit(xan[i], *popt))
    
    print 'function used to generate is 10 * exp( -0.5 * x )'
    print 'fit function is', popt[0], '* exp(', popt[1], '* x )'  
    
    #plotting data and analytical function 
    plt.rc("figure", facecolor="w")
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif',size = 16)    
    plt.title("Data", fontsize=20)
    plt.errorbar(x, y, yerr, fmt='o')
    plt.plot(xan, yan, 'r')
    plt.plot(xan, fity, 'g')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      • 2013-11-13
      相关资源
      最近更新 更多