[英]Python lmfit: Model object trys to use “self” as free variable
I am using the Python module "lmfit" to fit a function to some data. 我正在使用Python模块“ lmfit”来使函数适合某些数据。 The variables should have constraints and I want to implement the fitting procedure into an existing framework.
变量应具有约束条件,我想将拟合过程实现到现有框架中。 That is why the fit function has to be a class method.
这就是为什么fit函数必须是类方法的原因。 Therefore the first argument of the function should be "self".
因此,该函数的第一个参数应为“ self”。
import lmfit class foo(object): def __init__(self): self.x_data = range(10) self.y_data = range(10) + 2 def fit_func(self, x, a, b): return a * x + b def fit_with_lmfit(self): model = lmfit.Model(self.fit_func, independent_vars=["x"]) model.set_param_hint("a", 1) model.set_param_hint("b", 2) results = model.fit(self.y_data, x=self.x_data) return results
But now lmfit interprets "self" as free variable for the fit alogrithm. 但是现在lmfit将“自我”解释为适合算法的自由变量。 I tried adding a parameter hint:
我尝试添加参数提示:
model.set_param_hint("self", self, vary=False)
But that results in the following error: 但这导致以下错误:
TypeError: fit_func() got multiple values for keyword argument 'self'
I know that that curve_fit()
from scipy.optimize does not has any problems with class methods and neither should leastsq()
. 我知道这
curve_fit()
从scipy.optimize不具有类方法的任何问题和任何一方都不应该leastsq()
But I would like to use lmfit since it offers a nice interface to implement constraints for some variables. 但是我想使用lmfit,因为它提供了一个不错的接口来实现某些变量的约束。
On could also define fit_function()
inside fit_with_lmfit()
but I need to have access to it from outside the class as well and returning the function alongside results
seems messy. 在还可以定义
fit_function()
内fit_with_lmfit()
但我需要访问它从外部类以及和返回功能旁边results
似乎凌乱。
So my question would be: is there any way to let lmfit ignore certain variables of a fit function or better yet ignore "self" as positional argument? 所以我的问题是:有没有办法让lmfit忽略fit函数的某些变量,或者更好地忽略“ self”作为位置参数?
Since fit_func
is not using self, make it a static method: 由于
fit_func
没有使用self,因此将其fit_func
静态方法:
@staticmethod
def fit_func(x, a, b):
return a * x + b
This way you don't have to worry about self
. 这样,您不必担心
self
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.