【发布时间】:2021-08-09 08:56:48
【问题描述】:
我有一个datafile,其中第一列是 x 值,第二列是 y 值,第三列是 y 误差。我想拟合数据。我正在遵循here 的示例,我的代码是-
import matplotlib.pyplot as plt
import numpy as np
from lmfit.models import ExponentialModel, GaussianModel
file='sample-data.txt'
dat = np.loadtxt(file)
x = dat[:, 0]
y = dat[:, 1]
exp_mod = ExponentialModel(prefix='exp_')
pars = exp_mod.guess(y, x=x)
gauss1 = GaussianModel(prefix='g1_')
pars.update(gauss1.make_params())
pars['g1_center'].set(value=105000, min=75000, max=125000)
pars['g1_sigma'].set(value=150000, min=30000)
pars['g1_amplitude'].set(value=2000000, min=100000)
gauss2 = GaussianModel(prefix='g2_')
pars.update(gauss2.make_params())
pars['g2_center'].set(value=155000, min=125000, max=175000)
pars['g2_sigma'].set(value=150000, min=30000)
pars['g2_amplitude'].set(value=2000000, min=100000)
mod = gauss1 + gauss2 + exp_mod
init = mod.eval(pars, x=x)
out = mod.fit(y, pars, x=x)
print(out.fit_report(min_correl=0.5))
fig, axes = plt.subplots(1, 2, figsize=(12.8, 4.8))
axes[0].plot(x, y, 'b')
axes[0].plot(x, init, 'k--', label='initial fit')
axes[0].plot(x, out.best_fit, 'r-', label='best fit')
axes[0].legend(loc='best')
comps = out.eval_components(x=x)
axes[1].plot(x, y, 'b')
axes[1].plot(x, comps['g1_'], 'g--', label='Gaussian component 1')
axes[1].plot(x, comps['g2_'], 'm--', label='Gaussian component 2')
axes[1].plot(x, comps['exp_'], 'k--', label='Exponential component')
axes[1].legend(loc='best')
plt.show()
我期待这样的事情-
- 谁能帮我拟合图中的数据?
- 还在example 值、最小值、最大值中手动定义了中心、西格玛和幅度。有没有办法从数据文件中获取/计算这些值?
更新
我尝试使用@mikuszefski 在评论中建议的find_peaks。但它也拾取了所有小峰值(噪声),如图所示。
有没有办法只为较大的峰选择值?
【问题讨论】:
-
尝试使用pythonsfind_peaks获取启动参数。
-
@mikuszefski,感谢您的建议。但是 find_peaks 也会获取噪声的值(请参阅更新)。有没有办法只获取较大峰值的值?
-
尝试使用
height和或thresholdkwarg。干杯
标签: python python-3.x curve-fitting data-fitting lmfit