[英]Generating chi_squared using best fit
我正在生成一些假數據集的 1000 次迭代,並使用 curve_fit 來找到最佳擬合 model(具有一定平均值、偏移量、amp ...有更好的 chi2 值。 但是現在 output 很奇怪,甚至數據和 model 都不同意。
true_mean = 5 #Assume that we know the perfect fitting model is gaussian
#with mean value 5. And use try_mean with different mean values to see how
#does the chi2 behave
true_amp = 100
true_wid = 2
true_offset =10
x_values = np.array([i for i in np.arange(0,10,0.4)])
exact_y_values = np.array([true_offset + true_amp*
np.exp(-((i-true_mean)/true_wid)**2)
for i in x_values])
try_mean = 4.8 # Notice the data is generated centered at 5;
# by comparing it to a 4.8 we expect disagreement.
try_amp = 100
try_wid = 2
try_offset =10
try_these_y_values = np.array([try_offset + try_amp*
np.exp(-((i-try_mean)/try_wid)**2)
for i in x_values])
def func (x_values,offset,amp,mean,wid):
return (offset + amp*np.exp(-((i-mean)/wid)**2))
#Excercise 2
#def func (x_values,offset,amp,mean,wid): return (offset + amp*np.exp(-((i-mean)/wid)**2))
chi2_fit=np.zeros(1000)
for i in range (1000):
fake_exp_y_values = np.array([np.random.poisson(y)
for y in exact_y_values])
p01=[true_offset,true_amp,true_mean,true_wid]
[popt,pcov]=opt.curve_fit(func,x_values, fake_exp_y_values,p01)
y_values_fit=np.array([popt[0]+ popt[1]
*np.exp(
-((x_values-popt[2])/popt[3])**2)])
residuals=fake_exp_y_values-y_values_fit
y_err=np.clip(np.sqrt(fake_exp_y_values),1,9999)
pulls=residuals/y_err
chi2_fit[i]=np.sum(pulls**2)
plt.hist(chi2_fit)
plt.scatter(x_values,exact_y_values,color='k',ls='--',
label='true model')
plt.scatter(x_values,y_values_fit,color='r')
plt.errorbar(x_values,y_values_fit,yerr=y_err)
問題是您的 function 的定義和i
的用法:
def func (x_values,offset,amp,mean,wid):
return (offset + amp*np.exp(-((i-mean)/wid)**2))
for i in range (1000):
...
[popt,pcov]=opt.curve_fit(func,x_values, fake_exp_y_values,p01)
...
修正版:
def func (x_values,offset,amp,mean,wid):
return (offset + amp*np.exp(-((x_values-mean)/wid)**2))
也請下次發布MRE 。 這不是最小的,也不是可重復的(我必須在最后添加y_values_fit = y_values_fit.flatten()
才能使其工作)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.