-2

我是python的新手我有这个代码我想使用子类lmfit.models并实现一个猜测方法,

class DecayingSineModel():

     def __init__(self, *args, **kwargs):

        def decaying_sine(self, x, ampl, offset, freq, x0, tau):
            return ampl * np.sin((x - x0)*freq) * np.exp(-x/tau) + offset

        super(DecayingSineModel, self).__init__(decaying_sine, *args, **kwargs)

    def pset(param, value):
        params["%s%s" % (self.prefix, param)].set(value=value)

    def guess(self, data, **kwargs):         
        params = self.make_params()
        pset("ampl", np.max(data) - np.min(data))
        pset("offset", np.mean(data))
        pset("freq", 1)
        pset("x0", 0)
        pset("tau", 1)
        return lmfit.models.update_param_vals(params, self.prefix, **kwargs)

sp = DecayingSineModel()
params = sp.guess(y, x=x)
fit = sp.fit(y, params, x=x)

我收到以下错误我收到 的错误我收到的错误图像在此地址中

4

1 回答 1

0

你几乎肯定希望你DecayingSineWave继承自lmfit.Model. 正如其他人指出的那样,您的代码还存在许多其他问题,包括您的pset引用self但没有传入但您调用pset, not的事实self.pset。你的模型函数decaying_sine应该有.self

清理后的版本:

import numpy as np
import lmfit
import matplotlib.pyplot as plt

class DecayingSineModel(lmfit.Model):
    def __init__(self, *args, **kwargs):
        def decaying_sine(x, ampl, offset, freq, x0, tau):
            return ampl * np.sin((x - x0)*freq) * np.exp(-x/tau) + offset
        super(DecayingSineModel, self).__init__(decaying_sine, *args, **kwargs)

    def guess(self, data, x=None, **kwargs):
        ampl = np.max(data) - np.min(data)
        offset = np.mean(data)
        params = self.make_params(ampl=ampl, offset=offset, freq=1, x0=0, tau=1)
        return lmfit.models.update_param_vals(params, self.prefix, **kwargs)

sp = DecayingSineModel()

x = np.linspace(0, 25, 201)
noise = np.random.normal(size=len(x), scale=0.25)
y = 2 + 7*np.sin(1.6*(x-0.2)) * np.exp(-x/18) + noise

params = sp.guess(y, x=x)
result = sp.fit(y, params, x=x)
print(result.fit_report())

plt.plot(x, y, 'bo')
plt.plot(x, result.best_fit, 'r-')
plt.show()

报告:

[[Model]]
    Model(decaying_sine)
[[Fit Statistics]]
    # function evals   = 83
    # data points      = 201
    # variables        = 5
    chi-square         = 39.266
    reduced chi-square = 0.200
    Akaike info crit   = -318.220
    Bayesian info crit = -301.703
[[Variables]]
    ampl:     6.92483967 +/- 0.123863 (1.79%) (init= 12.59529)
    offset:   1.96307863 +/- 0.031684 (1.61%) (init= 2.139916)
    freq:     1.60060819 +/- 0.001775 (0.11%) (init= 1)
    x0:       0.19650313 +/- 0.010267 (5.23%) (init= 0)
    tau:      18.3528781 +/- 0.614576 (3.35%) (init= 1)
[[Correlations]] (unreported correlations are <  0.100)
    C(ampl, tau)                 = -0.781 
    C(freq, x0)                  =  0.750

在此处输入图像描述

于 2017-10-29T21:52:24.283 回答