如何解决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 举报,一经查实,本站将立刻删除。