我有一个描述数学函数的类。该类需要能够使最小二乘法适合传入数据。即你可以调用这样的方法:
classinstance.Fit(x,y)
并调整其内部变量以最适合数据。我试图使用scipy.optimize.curve_fit,它需要我传入一个模型函数。问题是模型函数在类中,需要访问类的变量和成员来计算数据。但是,curve_fit不能调用第一个参数为self的函数。有没有办法让curve_fit使用类的方法作为它的模型函数?
以下是显示问题的最小可执行代码段:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# This is a class which encapsulates a gaussian and fits itself to data.
class GaussianComponent():
# This is a formula string showing the exact code used to produce the gaussian. I
# It has to be printed for the user, and it can be used to compute values.
Formula = 'self.Amp*np.exp(-((x-self.Center)**2/(self.FWHM**2*np.sqrt(2))))'
# These parameters describe the gaussian.
Center = 0
Amp = 1
FWHM = 1
# HERE IS THE CONUNDRUM: IF I LEAVE SELF IN THE DECLARATION, CURVE_FIT
# CANNOT CALL IT SINCE IT REQUIRES THE WRONG NUMBER OF PARAMETERS.
# IF I REMOVE IT, FITFUNC CAN'T ACCESS THE CLASS VARIABLES.
def FitFunc(self, x, y, Center, Amp, FWHM):
eval('y - ' + self.Formula.replace('self.', ''))
# This uses curve_fit to adjust the gaussian parameters to best match the
# data passed in.
def Fit(self, x, y):
#FitFunc = lambda x, y, Center, Amp, FWHM: eval('y - ' + self.Formula.replace('self.', ''))
FitParams, FitCov = curve_fit(self.FitFunc, x, y, (self.Center, self.Amp, self.FWHM))
self.Center = FitParams[0]
self.Amp = FitParams[1]
self.FWHM = FitParams[2]
# Give back a vector which describes what this gaussian looks like.
def GetPlot(self, x):
y = eval(self.Formula)
return y
# Make a gausssian with default shape and position (height 1 at the origin, FWHM 1.
g = GaussianComponent()
# Make a space in which we can plot the gaussian.
x = np.linspace(-5,5,100)
y = g.GetPlot(x)
# Make some "experimental data" which is just the default shape, noisy, and
# moved up the y axis a tad so the best fit will be different.
ynoise = y + np.random.normal(loc=0.1, scale=0.1, size=len(x))
# Draw it
plt.plot(x,y, x,ynoise)
plt.show()
# Do the fit (but this doesn't work...)
g.Fit(x,y)
这会生成下面的图表然后崩溃,因为模型函数在尝试进行拟合时是不正确的。
提前致谢!
答案 0 :(得分:2)
我花了一些时间查看你的代码并且遗憾地迟了2分钟。无论如何,为了让事情变得更有趣,我已经编辑了你的课程,这就是我编造的内容:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
class GaussianComponent():
def __init__(self, func, params=None):
self.formula = func
self.params = params
def eval(self, x):
allowed_locals = {key: self.params[key] for key in self.params}
allowed_locals["x"] = x
allowed_globals = {"np":np}
return eval(self.formula, allowed_globals, allowed_locals)
def Fit(self, x, y):
FitParams, FitCov = curve_fit(self.eval, x, y, self.params)
self.fitparams = fitParams
# Make a gausssian with default shape and position (height 1 at the origin, FWHM 1.
g = GaussianComponent("Amp*np.exp(-((x-Center)**2/(FWHM**2*np.sqrt(2))))",
params={"Amp":1, "Center":0, "FWHM":1})
**SNIPPED FOR BREVITY**
我相信你或许会发现这是一个更令人满意的解决方案?
目前所有高斯参数都是类属性,这意味着如果您尝试使用不同的参数值创建类的第二个实例,您也将更改第一个类的值。通过将所有参数推送为实例属性,您可以摆脱它。这就是为什么我们首先有课程。
self
的问题源于您在self
中撰写Formula
的事实。现在你不再需要了。我觉得它更像这样,因为当你实例化一个类的对象时,你可以根据需要为你声明的函数添加尽可能多的参数。它现在甚至不必是高斯(与以前不同)。
将所有参数都扔到字典中,就像curve_fit
那样,忘了它们。
通过明确说明eval
可以使用的内容,您可以帮助确保任何恶意分子更难以破坏您的代码。但它仍然可能,它始终与eval
。
答案 1 :(得分:1)
啊!这实际上是我的代码中的一个错误。如果我改变这一行:
def FitFunc(self, x, Center, Amp, FWHM):
到
Debug.Print
然后我们没事。因此,curve_fit可以正确处理self参数,但我的模型函数不应包含y。
(让人看见!)