使用scipy.optimize.curve_fit时如何传递参数以适合函数 [英] How to pass parameter to fit function when using scipy.optimize.curve_fit
问题描述
我正在尝试使用scipy.optimize.curve_fit拟合一些数据。
我的拟合函数是:
I am trying to fit some data that I have using scipy.optimize.curve_fit. My fit function is:
def fitfun(x, a):
return np.exp(a*(x - b))
我要定义的是 a
作为拟合参数, b
作为根据我要拟合的数据而变化的参数。这意味着对于一组数据,我希望适合该函数: np.exp(a *(x-10))
而对于另一组数据,我希望适合函数 np.exp(a *(x-20))
。原则上,我希望将参数b作为任何值传递。
What i want is to define a
as the fitting parameter, and b
as a parameter that changes depending on the data I want to fit. This means that for one set of data I would want to fit the function: np.exp(a*(x - 10))
while for another set I would like to fit the function np.exp(a*(x - 20))
. In principle, I would like the parameter b to be passed in as any value.
我目前对curve_fit的称呼是:
The way I am currently calling curve_fit is:
coeffs, coeffs_cov = curve_fit(fitfun, xdata, ydata)
但是我想要的是这样的:
But what I would like would be something like this:
b=10
coeffs, coeffs_cov = curve_fit(fitfun(b), xdata, ydata)
b=20
coeffs2, coeffs_cov2 = curve_fit(fitfun(b), xdata, ydata)
这样我就得到了两种情况下的系数a(b = 10和b = 20)。
So that I get the coefficient a for both cases (b=10 and b=20).
我是python的新手,所以即使我也无法使用它试图阅读文档。任何帮助将不胜感激。
I am new to python so I cannot make it work, even though I have tried to read the documentation. Any help would be greatly appreciated.
推荐答案
我不知道这是否是正确的工作方式,但是我通常将函数包装在一个类中,以便可以从 self
访问参数。然后,您的示例如下所示:
I don't know if this is the "proper" way of doing things, but I usually wrap my function in a class, so that I can access parameters from self
. Your example would then look like:
class fitClass:
def __init__(self):
pass
def fitfun(self, x, a):
return np.exp(a*(x - self.b))
inst = fitClass()
inst.b = 10
coeffs, coeffs_cov = curve_fit(inst.fitfun, xdata, ydata)
inst.b = 20
coeffs, coeffs_cov = curve_fit(inst.fitfun, xdata, ydata)
这种方法避免使用全局参数,通常认为是邪恶的。
This approach avoids using global parameters, which are generally considered evil.
这篇关于使用scipy.optimize.curve_fit时如何传递参数以适合函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!