高斯直方图曲线拟合的误差曲线拟合()

2024-04-26 00:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到直方图高斯拟合的拟合误差。我正在使用scipy.optimize.curve U拟合在以下代码中:

import matplotlib.pylab as plt 
from pylab import exp
import numpy as np 
from scipy import optimize
from math import sqrt

# Fit functions
def Gaussian(x,a,b,c):
    return a * exp(-(x - b)**2.0 / (2 * c**2))

# Generate data from random Guassian distribution
npix = 10200
nbins = int(sqrt(npix))
data = np.random.standard_normal(npix)
print('\n Length of y: %s' % len(data))
n,bins,patches = plt.hist(data,bins=nbins)

# Generate data from bins as a set of points 
bin_size = abs(bins[1]-bins[0])
x =np.linspace(start=bins[0]+bin_size/2.0,stop=bins[-2]+bin_size/2.0,\
num=nbins,endpoint=True)
print min(x),max(x),len(x), np.mean(x)
y = n
y[y==0]= 1e-8


popt, pcov = optimize.curve_fit(Gaussian,x,y) 

# Curve-fit error method
error = [] 
for i in range(len(popt)):
    try:
      error.append( np.absolute(pcov[i][i])**0.5)
    except:
      error.append( 0.00 )
pfit_curvefit = popt
perr_curvefit = np.array(error) 
print('\n Curve-fit Curve fit: %s' % pfit_curvefit)
print('\n Curve-fit Fit errors: %s' % perr_curvefit)

# Plot the fit
x_fit = np.linspace(x[0], x[-1], nbins)
y_gauss = Gaussian(x_fit, *popt)
# y_boot = Gaussian(x_fit, *pfit_bootstrap)
yerr=Gaussian(x_fit,*perr_curvefit)

plt.plot(x_fit, y_gauss,linestyle='--',linewidth=2,\
color='red',label='Gaussian')



plt.xlabel('Pixel Values')
plt.ylabel('Frequency')
plt.title('Npix = %s, Nbins = %s'% (npix,nbins))
plt.legend()
plt.show()

enter image description here

如您所见,我可以让Python充分拟合直方图数据。当我试图计算拟合误差时,问题就出现了

yerr=高斯(x_拟合,*perr_curvefit)

这似乎是正确的做法,但当我看到这一系列错误时,它看起来毫无意义:

...
0.0
0.0
0.0
0.0
0.0
2.60905702842e-265
2.27384038589e-155
1.02313435685e-74
2.37684931814e-23
0.285080112094
1.76534048255e-08
5.64399121475e-45
9.31623567809e-111
7.93945868459e-206
0.0
0.0
0.0
0.0
0.0
...

我的问题是: 1拟合中的误差是否计算正确,如果没有,正确的计算方法是什么。 2我需要拟合中的误差来计算一个简化的卡平方值。有没有另一种方法可以计算卡方而不必知道拟合中每个点的误差?在

提前谢谢你!在


Tags: fromimportdatanpplterrorgaussianfit
1条回答
网友
1楼 · 发布于 2024-04-26 00:13:30

你的主要错误是错误值的计算。你的数组error是函数Gaussian中系数a,b,c标准差的渐近估计。然后你不能输入一个值x和不确定度+/-a,+/-b,+/-c并得到有意义的结果,因为误差是关于a,b,c的平均值,即高斯(x,a+/-delta a,等等)

如果您不热衷于使用optimize.curve_fit(),并且愿意使用optimize.leastsq(),那么您需要的信息就可以随时获得。
看这个question

更换

popt, pcov = optimize.curve_fit(Gaussian,x,y)

^{pr2}$

然后按照解决方案中的说明,找到缩减的卡平方

s_sq = (infodict['fvec']**2).sum()/ (N-n)

相关问题 更多 >