Python 2.7 卡方多项式拟合

Python 2.7 卡方多项式拟合,python-2.7,curve-fitting,polynomials,chi-squared,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 5t

我用多项式拟合我的数据

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)

卡方通常定义为数据拟合的平方和。对于您的示例,这将是:

 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()进行曲线拟合,作为处理许多此类琐事的
curve\u 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()

嗨,我和他们问的问题一样。我使用了你的代码,但我有这个错误<代码>回溯(最后一次调用):文件“S:/Python/Data/Testing File.py”,第97行,在result=pmodel.fit(params,np.log10(psd),freqs=freqs)文件“C:\Python27\lib\site packages\lmfit\model.py”,第812行,在fit for p in self.param_names])AttributeError:'numpy.ndarray'对象没有属性'keys'@hiddengay抱歉,我调用了
Model.fit()
错误!!数据数组应该是第一个,参数对象应该是第二个。但同时:使用不同的SO问题并发布完整的示例。这样做的目的是问一些好问题,这些问题可以被其他人搜索和使用……谢谢你,先生,谢谢你的帮助:)我希望我能提出最后一个问题。我已经按照您的建议更改了代码,但我现在执行以下操作:
Traceback(最后一次调用):文件“S:/Python/Data/Testing File.py”,第100行,打印('Chi-square=',result.Chi_square)AttributeError:'ModelResult'对象没有属性“Chi_square”