Python与Excel指数曲线拟合结果差异原因探究
指数曲线拟合:Python与Excel结果差异疑问
刚接触Python,此前主要使用Matlab。目前尝试在半对数图上进行指数曲线拟合,以下是编写的Python代码:
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit time = np.array([0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260]) absorbance = np.array([0.02, 0.02, 0.042, 0.049, 0.094, 0.130, 0.160, 0.159, 0.205, 0.290, 0.440, 0.490, 0.310, 0.317]) def expf(x, a, b): return a * np.exp(b*x) popt, pcov = curve_fit(expf, time, absorbance, p0=[0.02,0.0141], sigma=np.sqrt(absorbance)) a = popt[0] b = popt[1] plt.scatter(time, absorbance, label='data') plt.plot(time, expf(time, a, b), 'r-', label='exponential fit') plt.yscale('log') plt.legend() plt.show() # r2 value y_pred = expf(time, a, b) SS_res = np.sum((absorbance - y_pred)**2) SS_tot = np.sum((absorbance - np.mean(absorbance))**2) r2 = 1 - (SS_res / SS_tot) print("a =", a, "and b =", b) print("R-squared value:", '{:.4}'.format(r2))
运行后得到结果:
a = 0.0368729243337103 and b = 0.009635937402567983 R-squared value: 0.6657
但使用相同数据在Excel中得到的a、b和R²值存在差异,不确定差异产生的原因。将Python得到的b值代入Excel可得到一致结果,但想知道差异为何产生、是否显著,是否是因为Python使用了更多小数位?曾尝试对Python结果加权,但Excel是无加权拟合,所以认为Python也应采用无加权方式。
内容的提问来源于stack exchange,提问作者JonasDenmark
相关产品推荐
相关产品推荐

