使用 python 拟合指数函数
Fitting to exponential functions using python
我正在尝试用指数函数拟合数据集。为此,我创建了这个函数来重新创建指数函数:
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 拟合器,其中包含从散点图中提取的方程和数据,您应该使用实际数据重新拟合。
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
xData = numpy.array([1.408e-01, 8.169e-01, 1.915e+00, 3.183e+00, 3.972e+00, 4.986e+00, 5.972e+00, 6.986e+00, 7.972e+00, 8.873e+00, 9.915e+00, 1.087e+01, 1.192e+01, 1.299e+01, 1.386e+01, 1.496e+01, 1.594e+01, 1.792e+01, 1.682e+01, 1.890e+01, 1.992e+01])
yData = numpy.array([8.214e-01, 8.214e-01, 8.214e-01, 8.214e-01, 6.160e-01, 8.214e-01, 8.214e-01, 4.107e-01, 1.027e+00, 1.027e+00, 8.214e-01, 1.027e+00, 1.027e+00, 1.643e+00, 1.643e+00, 3.285e+00, 5.749e+00, 2.300e+01, 1.170e+01, 4.723e+01, 9.651e+01])
def func(x, a, b, c):
return a*(b**x)+c
# these are the same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0, 1.0])
# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)
modelPredictions = func(xData, *fittedParameters)
absError = modelPredictions - yData
SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)
print()
##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
axes = f.add_subplot(111)
# first the raw data as a scatter plot
axes.plot(xData, yData, 'D')
# create data for the fitted equation plot
xModel = numpy.linspace(min(xData), max(xData))
yModel = func(xModel, *fittedParameters)
# now the model as a line plot
axes.plot(xModel, yModel)
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label
plt.show()
plt.close('all') # clean up after using pyplot
graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)
我正在尝试用指数函数拟合数据集。为此,我创建了这个函数来重新创建指数函数:
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 拟合器,其中包含从散点图中提取的方程和数据,您应该使用实际数据重新拟合。
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
xData = numpy.array([1.408e-01, 8.169e-01, 1.915e+00, 3.183e+00, 3.972e+00, 4.986e+00, 5.972e+00, 6.986e+00, 7.972e+00, 8.873e+00, 9.915e+00, 1.087e+01, 1.192e+01, 1.299e+01, 1.386e+01, 1.496e+01, 1.594e+01, 1.792e+01, 1.682e+01, 1.890e+01, 1.992e+01])
yData = numpy.array([8.214e-01, 8.214e-01, 8.214e-01, 8.214e-01, 6.160e-01, 8.214e-01, 8.214e-01, 4.107e-01, 1.027e+00, 1.027e+00, 8.214e-01, 1.027e+00, 1.027e+00, 1.643e+00, 1.643e+00, 3.285e+00, 5.749e+00, 2.300e+01, 1.170e+01, 4.723e+01, 9.651e+01])
def func(x, a, b, c):
return a*(b**x)+c
# these are the same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0, 1.0])
# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)
modelPredictions = func(xData, *fittedParameters)
absError = modelPredictions - yData
SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)
print()
##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
axes = f.add_subplot(111)
# first the raw data as a scatter plot
axes.plot(xData, yData, 'D')
# create data for the fitted equation plot
xModel = numpy.linspace(min(xData), max(xData))
yModel = func(xModel, *fittedParameters)
# now the model as a line plot
axes.plot(xModel, yModel)
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label
plt.show()
plt.close('all') # clean up after using pyplot
graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)