1.scipy.optimize.curve_fit
scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, bounds=(- inf, inf), method=None, jac=None, **kwargs)
返回:
popt —— 参数最佳值
pcov —— 协方差
R² —— 需要自己计算
residuals = ydata- f(xdata, popt)
ss_res = numpy.sum(residuals**2)
ss_tot = numpy.sum((ydata-numpy.mean(ydata))**2)
r_squared = 1 - (ss_res/ss_tot)
例子:
df = pd.read_excel(r'./7.xlsx')
def func(x, a, b, c):
return a * x * x + b* x + c
xdata = df['x']
ydata = df['y']
popt, pcov = curve_fit(func, xdata, ydata)
perr = np.sqrt(np.diag(pcov))
residuals = ydata- func(xdata, popt[0],popt[1],popt[2])
ss_res = numpy.sum(residuals**2)
ss_tot = numpy.sum((ydata-numpy.mean(ydata))**2)
r_squared = 1 - (ss_res/ss_tot)
print(r_squared)
# plt.plot(xdata, ydata, 'b-', label='data')
# plt.plot(xdata, func(xdata, *popt), 'r-',
# label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
# plt.xlabel('x')
# plt.ylabel('y')
# plt.legend()
# plt.show()
2.numpy.polyfit
numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)