【问题标题】:Using scipy.optimize.curve_fit within a class在类中使用 scipy.optimize.curve_fit
【发布时间】:2015-05-08 08:59:38
【问题描述】:

我有一个描述数学函数的类。该类需要能够以最小二乘法拟合自己以传入数据。即你可以调用这样的方法:

classinstance.Fit(x,y)

它会调整其内部变量以最适合数据。我正在尝试为此使用 scipy.optimize.curve_fit ,它需要我传入一个模型函数。问题是模型函数在类中,需要访问类的变量和成员来计算数据。但是,curve_fit 不能调用第一个参数为 self 的函数。有没有办法让curve_fit使用类的方法作为模型函数?

这是显示问题的最小可执行 sn-p:

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)

这会产生以下图表,然后由于模型函数在尝试拟合时不正确而崩溃。

提前致谢!

【问题讨论】:

    标签: python numpy scipy curve-fitting class-method


    【解决方案1】:

    我花了一些时间查看您的代码,不幸的是迟到了 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 的问题源于您在Formula 中写入self 的事实。现在你不必再这样做了。我认为这样更有意义,因为当您实例化类的对象时,您可以根据需要向声明的函数添加尽可能多或尽可能少的参数。它现在甚至不必是高斯的(与以前不同)。

    就像curve_fit 所做的那样,将所有参数扔到字典中,然后忘记它们。

    通过明确说明 eval 可以使用什么,您可以帮助确保任何作恶者都难以破解您的代码。尽管如此,它仍然是可能的,它总是与eval

    祝你好运,请问您是否需要澄清一些事情。

    【讨论】:

      【解决方案2】:

      啊!这实际上是我的代码中的一个错误。如果我改变这一行:

      def FitFunc(self, x, y, Center, Amp, FWHM):
      

      def FitFunc(self, x, Center, Amp, FWHM):
      

      那我们就没事了。所以 curve_fit 确实正确处理了 self 参数,但我的模型函数不应该包含 y。

      (尴尬!)

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 2020-06-05
      • 2018-11-22
      • 2012-05-02
      • 1970-01-01
      相关资源
      最近更新 更多