【发布时间】:2019-11-07 14:47:48
【问题描述】:
我正在尝试拟合指数函数的数据集。为此,我创建了这个函数来重新创建指数函数:
def exponential(x,a,b,c):
return a*(b**x)+c
我正在使用模块scipy
.这里是进行拟合并打印的代码:
def fit_exponential(x_data,y_data,file):
params,paramscov= optimize.curve_fit(exponential, x_data, y_data,p0=[1,2,3])
#Here we calculate the Coeficent of deternination (R²)
#It is a statistical measure of how well the regression predictions approximate the real data points.
residuals = y_data - exponential(x_data, *params)
ss_res = np.sum(residuals**2)
ss_tot = np.sum((y_data-np.mean(y_data))**2)
r_squared = 1 - (ss_res / ss_tot)
print('R²= ',r_squared)
result = print_exponential(*params)
print(result)
#Compound the chart of data and the data with a little text of results
plt.figure(figsize=(6, 4))
plt.plot(x_data, exponential(x_data,*params),label='Fitted function',color='m')
plt.scatter(x_data, y_data, label='Data',color='salmon')
texto='R²= '+str(round(r_squared,5))+'\n'+result
plt.text(x_data[-1]*0.55, y_data[-1]*0.15, texto,verticalalignment='center',bbox=dict(facecolor='m', alpha=0.3))
plt.legend(loc='best')
plt.xlabel('Size N')
plt.ylabel('Steps')
plt.savefig(file)
正如我们所见,数据似乎是指数级的,但我无法为其拟合函数。我已经看到了一些帖子,但我做不到。
【问题讨论】:
-
能否包含您的导入语句以便我们运行代码?
标签: python curve-fitting exponential