我是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)
我收到了以下错误 我收到的错误 the image of error that i recieved is in this address
答案 0 :(得分:0)
您几乎肯定希望DecayingSineWave
继承lmfit.Model
。正如其他人指出的那样,您的代码存在许多其他问题,包括您的pset
引用self
但未传入但尚未调用pset
的事实,不是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