这是一个图形 Python 拟合器,它使用与您发布的数据上的方程式搜索不同的方程式,它似乎使用所有 1.0 的 scipy 默认初始参数估计值提供了极好的拟合。
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
xData = numpy.array([50000.0, 100000.0, 150000.0, 200000.0, 250000.0, 300000.0, 350000.0, 400000.0, 450000.0, 500000.0, 550000.0, 600000.0, 650000.0, 700000.0, 750000.0, 800000.0, 850000.0, 900000.0, 950000.0, 1000000.0])
yData = numpy.array([1.8779273e-06, 3.81015841e-07, 1.89900422e-07, 1.21302069e-07, 8.3970324e-08, 6.18937868e-08, 4.98975718e-08, 3.97720839e-08, 3.23420144e-08, 2.79493666e-08, 2.35548293e-08, 2.01505953e-08, 1.81079429e-08, 1.59391671e-08, 1.37227044e-08, 1.30031234e-08, 1.19076952e-08, 1.10967303e-08, 9.43339053e-09, 8.98627485e-09])
def func(x, a, b, c): # from zunzun.com equation search
return a / (b+numpy.power(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)