我有这个多项式适合我的数据。
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')
这就是我得到的:
我想算卡方,但老实说我不知道怎么做。 我能够做到这样的事情,但我认为这是错误的。
chisquare = chi(popt)
print chisquare
Power_divergenceResult(statistic=-0.4318298090941465, pvalue=1.0)
答案 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()