我在估计 5 个未知参数 a、b、c、d、e 时遇到了麻烦,这些参数肯定位于区间中。它只是这样看起来:
import numpy as np
from scipy.optimize import curve_fit
diap_a = np.arange(0.01, 1, 0.2)
diap_b = np.arange(0.01, 30, 5)
diap_c = np.arange(0.01, 2, 0.5)
diap_d = np.arange(0.01, 2, 0.5)
diap_e = np.arange(0.01, 0.3, 0.03)
X = np.arange(0.01, 1, 0.01)
def func(a, b, c, d, e):
return a + b + c + d + e #for example
Y = func(a, b, c, d, e)
我有数据(期望值),以便
Y1 = [60, 59, 58, 57, 56, 55, 50, 30, 10]
X1 = [0.048, 0.049, 0.05, 0.05, 0.06, 0.089, 0.1, 0.12, 0.134]
我试图以这种方式实现它:
popt, pcov = curve_fit(func, a, b, c, d, e, Y1, X1)
找到有助于拟合曲线的最佳 A、B、C、D、E
plt.plot(Y, X)
plt.show()
但它不起作用。
结果是:
OptimizeWarning: Covariance of the parameters could not be estimated
对不起,我对这个问题的表述很糟糕。
根据 curve_fit() 文档,您的 curve_fit() 应该将 func、X1 和 Y1 作为前三个参数。正如当前编码的那样,func() 将始终返回一个与 X1 无关且无法拟合数据的单个值。下面是一个使用您的数据绘制拟合器的示例,该数据具有三个参数,并使用 scipy 默认初始参数估计值(所有 1.0) - 这些并不总是最佳的。如果你的数据与任何给定函数的拟合度很差,它可能是初始参数估计值,因此 scipy 有一个遗传算法模块来帮助在需要时找到这些估计值。
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
xData = numpy.array([0.048, 0.049, 0.05, 0.05, 0.06, 0.089, 0.1, 0.12, 0.134])
yData = numpy.array([60, 59, 58, 57, 56, 55, 50, 30, 10])
def func(x, a, b, c): # simple quadratic example
return (a * numpy.square(x)) + 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)