Python 即使迭代更改初始猜测,scipy曲线拟合也不会收敛
我通过实验获得了一些观点 这些点应遵循以下类型的理论函数: f(x)=A*(1-e^{-x/B}) 我尝试使用Python 即使迭代更改初始猜测,scipy曲线拟合也不会收敛,python,scipy,curve-fitting,Python,Scipy,Curve Fitting,我通过实验获得了一些观点 这些点应遵循以下类型的理论函数: f(x)=A*(1-e^{-x/B}) 我尝试使用scipy中的curve\u fit函数进行优化,以找到最适合指数的参数A和B 我必须在几乎100个不同的样品上进行此拟合 此外,根据经验,我知道0.5
scipy中的curve\u fit
函数进行优化,以找到最适合指数的参数A和B
我必须在几乎100个不同的样品上进行此拟合
此外,根据经验,我知道0.5
我的问题与曲线拟合未能收敛到A和B的最佳值有关
这是我写的代码,首先我导入了我需要的包,我定义了指数函数,然后我定义了一个fit函数,在这里我对a值施加了一些约束。我这样做是因为在某些情况下(例如,10%的时间)曲线拟合会为A返回一些不真实的值,例如A=10^5或更大。如果A是一个大于2的值,我通过改变初始猜测再次调用curve_fit函数
from scipy.optimize import curve_fit
import pandas as pd
import numpy as np
initial_guess = [8, 1]
def exponential(x, a, b):
return a*(1 - np.exp(-(x)/b))
def fit(x, y, i):
best_vals, covar = curve_fit(lambda t, a, b: exponential(t, a, b), x, y, p0=i)
if best_vals[1]<0.5 or best_vals[1]>2:
i2 = np.array([1, 0.8, 1])
while best_vals[1]<0.5 or best_vals[1]>2:
i2 = i2 + [0.5, 0.1, 0.5]
best_vals, covar = curve_fit(lambda t, a, b: exponential(t, a, b), x, y, p0=i2)
print(best_vals)
variance = np.sqrt(np.diag(covar))
i2= i
B = best_vals[0]
A = best_vals[1]
return variance, A, B
df = pd.read_csv('data.csv')
v, a, b = fit(df['x'], df['y'], initial_guess)
来自scipy.optimize import curve\u fit的
作为pd进口熊猫
将numpy作为np导入
初始猜测=[8,1]
def指数(x,a,b):
返回a*(1-np.exp(-(x)/b))
def配合(x、y、i):
最佳值,covar=曲线拟合(λt,a,b:指数(t,a,b),x,y,p0=i)
如果最佳值[1]2:
i2=np.数组([1,0.8,1])
而最佳值[1]2:
i2=i2+[0.5,0.1,0.5]
最佳值,covar=曲线拟合(λt,a,b:指数(t,a,b),x,y,p0=i2)
打印(最佳值)
方差=np.sqrt(np.diag(covar))
i2=i
B=最佳值[0]
A=最佳值[1]
返回差异,A,B
df=pd.read\u csv('data.csv'))
v、 a,b=拟合(df['x'],df['y'],初始猜测)
不幸的是,对于这段代码,有时我无法收敛到介于0.5和2.0之间的a值
考虑到我的约束条件,是否有人建议其他方法来执行此拟合?
也许有更好的方法来编写fit函数。。或者考虑我的约束,随后改变初始猜测< /P>
谢谢,谁能帮我
Andrea这里是一个使用scipy的差分进化遗传算法确定曲线拟合()的初始参数估计值的图形拟合师示例。scipy实现使用拉丁超立方体算法来确保参数空间的彻底搜索,这需要搜索的范围。在这个例子中,我使用了你的方程和一个附加的偏移量,以便它与我的测试数据一起工作。我还使A和B上的遗传算法搜索边界比您提供的搜索边界上的“误差范围”稍大一些
你代码中的指数与你帖子中的理论指数不同你是对的,我在文本写作中犯了错误。。这是正确的f(x)=a*(1-np.exp(-(x)/b))你能修正问题中的代码吗?如果代码运行时没有经过编辑,那么有人会更容易帮助您。如果您将文件中的数据替换为再现问题的实际数字,这也会很有帮助。您没有提供data.csv
,因此没有人可以实际运行此代码。我认为代码存在一些问题:1)如果您的函数已经定义,则在curve\u fit
中重用lambda
没有意义。2) 什么是自我指数,为什么不同?3) 代码中的指数与问题中的指数不同,是哪一个?这个问题中的一个可以用一个线性函数来拟合。两边都拿着圆木。4) 您可以使用bounds=[(a_min,b_min),(a_max,b_max)]]将边界应用于曲线拟合,无需虽然循环是的,您是对的,这是因为我从一个大类复制了代码,并且使用self.indexant调用了指数函数。现在我把问题都改正了。我认为边界可以解决这个问题。谢谢,很酷!!我不知道scipy的差分进化遗传算法。非常感谢,这对我绝对有帮助!!参数值的良好范围比单个值更容易猜测。和你一样,我也认为这项技术充满了数字遗传优势。
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings
xData = numpy.array([19.1647, 18.0189, 16.9550, 15.7683, 14.7044, 13.6269, 12.6040, 11.4309, 10.2987, 9.23465, 8.18440, 7.89789, 7.62498, 7.36571, 7.01106, 6.71094, 6.46548, 6.27436, 6.16543, 6.05569, 5.91904, 5.78247, 5.53661, 4.85425, 4.29468, 3.74888, 3.16206, 2.58882, 1.93371, 1.52426, 1.14211, 0.719035, 0.377708, 0.0226971, -0.223181, -0.537231, -0.878491, -1.27484, -1.45266, -1.57583, -1.61717])
yData = numpy.array([0.644557, 0.641059, 0.637555, 0.634059, 0.634135, 0.631825, 0.631899, 0.627209, 0.622516, 0.617818, 0.616103, 0.613736, 0.610175, 0.606613, 0.605445, 0.603676, 0.604887, 0.600127, 0.604909, 0.588207, 0.581056, 0.576292, 0.566761, 0.555472, 0.545367, 0.538842, 0.529336, 0.518635, 0.506747, 0.499018, 0.491885, 0.484754, 0.475230, 0.464514, 0.454387, 0.444861, 0.437128, 0.415076, 0.401363, 0.390034, 0.378698])
# exponential equation + offset
def func(x, a, b, offset):
return a*(1.0 - numpy.exp(-(x)/b)) + offset
# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
val = func(xData, *parameterTuple)
return numpy.sum((yData - val) ** 2.0)
def generate_Initial_Parameters():
minY = min(yData)
maxY = max(yData)
parameterBounds = []
parameterBounds.append([0.0, 5.0]) # search bounds for a
parameterBounds.append([5.0, 15.0]) # search bounds for b
parameterBounds.append([minY, maxY]) # search bounds for offset
# "seed" the numpy random number generator for repeatable results
result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
return result.x
# by default, differential_evolution completes by calling curve_fit() using parameter bounds
geneticParameters = generate_Initial_Parameters()
# now call curve_fit without passing bounds from the genetic algorithm,
# just in case the best fit parameters are aoutside those bounds
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
print('Fitted parameters:', fittedParameters)
print()
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()
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)