Python,在 y 数据中创建具有不确定性的高斯拟合

问题描述

我正在尝试使用 scipy.opimize 曲线拟合来创建高斯拟合。 我的 y 数据有泊松误差,所以我需要将这些不确定性整合到我的曲线拟合中,但我不知道如何。

首先创建一个函数 fit_gauss,它在 y 中没有错误。现在我尝试修改代码。 这就是我得到的:


x = x_data #datas are imported from file
y = y_data
y_un = unp.uarray(y,np.sqrt(y)) 
print("DATA - Gauss")
     
#Define Gauss function   
def f_gauss(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))
    
#Define Fitting function 
def fit_gauss(x,y,title,path):
    n=len(x)
    mean=sum(x*y)/n
    w=[0]*len(x)
    for i in range(len(x)):
        w[i]=y[i]*(x[i]-mean)**2
    sigma = (sum(w) / sum(y))**(1 / 2)
    #sigma = (sum(y * (x - mean)**2) / sum(y))**(1/2)
    
    gopt,gcov = curve_fit(
        f_gauss,x,p0=[max(y),mean,sigma]
    ) #trying to use curve fit 
    gerrors = np.sqrt(np.diag(gcov))
    unparams_gauss = unp.uarray(gopt,gerrors)
    print(f"""
        {title}
        Mean: {mean}
        Sigma: {sigma}
        a={unparams_gauss[0]}
        x0={unparams_gauss[1]}
        sigma={unparams_gauss[2]}
        """)
    #plotting
    plt.title(title)
    plt.plot(x,"k",label=f"{title}")
    plt.plot(x,f_gauss(x,*gopt),"r--",label="Gauß Fit")
    plt.legend(loc="best")
    plt.savefig(path)
    plt.close()
    
fit_gauss(x,y_un,"Cs-137","plots/gauss_fit.pdf")

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)