我正在尝试编写曲线拟合和卡方平方的脚本。我有一些样本数据,但由于某种原因,拟合度未达到预期,并且我得到了没有意义的卡方值(我已经用matlab计算出来了,所以我知道会发生什么)。 我不知道为什么脚本不起作用,因为它已经可以很好地与玩具值一起使用了。 这是脚本:
import matplotlib.pyplot as plt
import matplotlib as matp
import numpy as np
import scipy.optimize as opt
import math
import pandas as pd
from scipy import stats
#Read the csv file to a DataFrame
df = pd.read_csv('HarmonicData.csv')
#Define data
xdata = df.m
dX = df.dm
ydata = df.Tavg
dY = df.dTavg
def func(x, a, b):
return a/x**2 + b
#Title and axis title Variables
title = 'Fit'
ytitle = 'Tavg [sec]'
xtitle = 'r [cm]'
#Define plot and add errorbars
fig, ax = plt.subplots()
ax.errorbar(xdata, ydata, yerr=dY, xerr=dX, fmt='o', ms=2)
#Axis Title Setting
ax.set_title(title)
ax.set_ylabel(ytitle)
ax.set_xlabel(xtitle)
#Curve parameter initial guess
paraguess = ([0.230000, 0.300000])
#Curve Fit
parafit, pcov = opt.curve_fit(func, xdata, ydata, p0=paraguess)
#Reduced Chi squared
chi_sq = np.sum(((func(xdata, *parafit)-ydata)/dX)**2)
red_chi_sq = (chi_sq)/(len(xdata)-len(parafit))
#Print results
print('initial guess for parameters: a= %.8f b= %.8f' % tuple(paraguess))
print ('The degrees of freedom for this test is', len(xdata)-len(parafit))
print ('The chi squared value is: ',("%.2f" %chi_sq))
print ('The reduced chi squared value is: ',("%.2f" %red_chi_sq))
#Show and plot
plt.plot(xdata, func(xdata, *parafit), 'r-', label='fit: a=%.3f b=%.3f' % tuple(parafit))
plt.legend()
plt.show()
我不知道为什么会这样,而且我也找不到原因。我希望获得一些帮助,因为我通常对scipy / python不太了解