【问题标题】:How can I find the right gaussian curve given some data?给定一些数据,如何找到正确的高斯曲线?
【发布时间】:2016-09-05 00:56:03
【问题描述】:

我有从一维高斯中提取的代码:

import numpy as np
from scipy.stats import norm
from scipy.optimize import curve_fit
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import gauss

# Beginning in one dimension:
mean = 0; Var = 1; N = 1000
scatter = np.random.normal(mean,np.sqrt(Var),N)
scatter = np.sort(scatter)
mu,sigma = norm.fit(scatter)

我使用 norm.fit() 获得 mu 和 sigma

现在我想使用

获取我的参数
xdata = np.linspace(-5,5,N)
pop, pcov = curve_fit(gauss.gauss_1d,xdata,scatter)

问题是我不知道如何将我的散点(从一维高斯绘制)映射到 x 线以使用 curve_fit。

另外,假设我像之前一样简单地使用 and mu 和 sigma。

我使用:

n, bins, patches = plt.hist(scatter,50,facecolor='green')
y = 2*max(n)*mlab.normpdf(bins,mu,sigma)
l = plt.plot(bins,y,'r--')

plt.xlabel('x-coord')
plt.ylabel('Occurrences')
plt.grid(True)
plt.show()

但我必须将幅度猜测为 2*max(n)。它可以工作,但它并不健壮。不猜怎么能找到振幅?

【问题讨论】:

    标签: python scipy histogram gaussian


    【解决方案1】:

    为避免猜测幅度,调用hist()normed=True,则幅度对应normpdf()

    为了做曲线拟合,我建议不要使用密度,而是使用累积分布:每个样本的高度为1/N,依次相加为1。这样的好处是你不需要分组垃圾箱中的样本。

    import numpy as np
    from scipy.stats import norm
    from scipy.optimize import curve_fit
    import matplotlib.pyplot as plt
    
    # Beginning in one dimension:
    mean = 0; Var = 1; N = 100
    scatter = np.random.normal(mean,np.sqrt(Var),N)
    scatter = np.sort(scatter)
    mu1,sigma1 = norm.fit(scatter) # classical fit
    
    scat_sum = np.cumsum(np.ones(scatter.shape))/N # cumulative samples
    [mu2,sigma2],Cx = curve_fit(norm.cdf, scatter, scat_sum, p0=[0,1]) # curve fit
    print(u"norm.fit():  µ1= {:+.4f}, σ1={:.4f}".format(mu1, sigma1))
    print(u"curve_fit(): µ2= {:+.4f}, σ2={:.4f}".format(mu2, sigma2))
    
    fg = plt.figure(1); fg.clf()
    ax = fg.add_subplot(1, 1, 1)
    t = np.linspace(-4,4, 1000)
    ax.plot(t, norm.cdf(t, mu1, sigma1), alpha=.5, label="norm.fit()")
    ax.plot(t, norm.cdf(t, mu2, sigma2), alpha=.5, label="curve_fit()")
    ax.step(scatter, scat_sum, 'x-', where='post', alpha=.5, label="Samples")
    ax.legend(loc="best")
    ax.grid(True)
    ax.set_xlabel("$x$")
    ax.set_ylabel("Cumulative Probability Density")
    ax.set_title("Fit to Normal Distribution")
    
    fg.canvas.draw()
    plt.show()
    

    打印

    norm.fit():  µ1= +0.1534, σ1=1.0203
    curve_fit(): µ2= +0.1135, σ2=1.0444
    

    和情节

    【讨论】:

      猜你喜欢
      • 2020-04-03
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2016-08-22
      • 2014-04-27
      • 1970-01-01
      • 2017-04-02
      相关资源
      最近更新 更多