卡方与多项式拟合

时间:2018-03-18 08:40:53

标签: python-2.7 curve-fitting polynomials chi-squared

我有这个多项式适合我的数据。

fig3 = plt.figure(3)

for dataset in [Bxfft]:
    dataset = np.asarray(dataset)
    freqs, psd = signal.welch(dataset, fs=266336/300, window='hamming', nperseg=8192)
    plt.semilogy(freqs, psd/dataset.size**0, color='r')

# Polynomial 5th grade
def line(freqs, a, b, c, d, e, f):
    return a*freqs**5 + b*freqs**4 + c*freqs**3 + d*freqs**2 + e*freqs + f

popt, pcov = curve_fit(line, freqs, np.log10(psd))
plt.semilogy(freqs, 10**line(freqs, popt[0], popt[1], popt[2], popt[3], popt[4], popt[5]), 'black')

这就是我得到的:

enter image description here

我想算卡方,但老实说我不知道​​怎么做。 我能够做到这样的事情,但我认为这是错误的。

chisquare = chi(popt)
print chisquare
Power_divergenceResult(statistic=-0.4318298090941465, pvalue=1.0)

1 个答案:

答案 0 :(得分:1)

卡方通常被定义为data-fit的平方和。对于你的例子:

 best_fit = 10**line(freqs, popt[0], popt[1], popt[2], popt[3], popt[4], popt[5])
 chi_square = ((psd - best_fit)**2).sum()

请允许我建议使用lmfit(https://lmfit.github.io/lmfit-py/)进行曲线拟合,以替代处理许多此类杂务的curve_fit。使用lmfit,您的示例可能如下所示:

from lmfit import Model
def line(freqs, a, b, c, d, e, f):
    return a*freqs**5 + b*freqs**4 + c*freqs**3 + d*freqs**2 + e*freqs + f

# turn your model function into an lmfit Model
pmodel = Model(line)

# make parameters with initial guesses. note that parameters are
# named 'a', 'b', 'c', etc based on your `line` function, not numbered.
params = pmodel.make_params(a=1, b=-0.5, c=0, d=0, e=0, f=0)

# fit model to data with these parameters, specify independent variable 
result = pmodel.fit(np.log10(psd), params, freqs=freqs)

# this result has chi-square calculated:
print('Chi-square = ', result.chisqr)

# print report with fit statistics, parameter values and uncertainties
print(result.fit_report()) 

# plot, using best-fit in result
plt.semilogy(freqs, psd, color='r')
plt.semilogy(freqs, 10**(result.best_fit), color='k')
plt.show()