我的数学知识是有限的,这就是为什么我可能卡住了。我有一个谱图,我试图拟合两个高斯峰。我可以适应最大的高峰,但我无法适应最小的高峰。我知道我需要为两个峰值求和高斯函数,但我不知道我出错的地方。我的电流输出的图像显示:Python:使用非线性最小二乘法的双曲线高斯拟合
蓝线是我的数据和绿线是我目前的契合。有个肩膀可以在我的数据主峰左侧我目前努力配合,使用下面的代码:
import matplotlib.pyplot as pt
import numpy as np
from scipy.optimize import leastsq
from pylab import *
time = []
counts = []
for i in open('/some/folder/to/file.txt', 'r'):
segs = i.split()
time.append(float(segs[0]))
counts.append(segs[1])
time_array = arange(len(time), dtype=float)
counts_array = arange(len(counts))
time_array[0:] = time
counts_array[0:] = counts
def model(time_array0, coeffs0):
a = coeffs0[0] + coeffs0[1] * np.exp(- ((time_array0-coeffs0[2])/coeffs0[3])**2)
b = coeffs0[4] + coeffs0[5] * np.exp(- ((time_array0-coeffs0[6])/coeffs0[7])**2)
c = a+b
return c
def residuals(coeffs, counts_array, time_array):
return counts_array - model(time_array, coeffs)
# 0 = baseline, 1 = amplitude, 2 = centre, 3 = width
peak1 = np.array([0,6337,16.2,4.47,0,2300,13.5,2], dtype=float)
#peak2 = np.array([0,2300,13.5,2], dtype=float)
x, flag = leastsq(residuals, peak1, args=(counts_array, time_array))
#z, flag = leastsq(residuals, peak2, args=(counts_array, time_array))
plt.plot(time_array, counts_array)
plt.plot(time_array, model(time_array, x), color = 'g')
#plt.plot(time_array, model(time_array, z), color = 'r')
plt.show()
在这种情况下,这将非常困难,因为两个峰值相互靠得很近 - 对于较小的“高斯”,没有确定的峰值。通常可以(我认为)识别所有感兴趣的峰,然后遍历每个峰,掩盖所有其他峰,并拟合到每个峰。总的拟合是所有这些拟合的总和。看起来你需要做的是确定大峰和它的范围,然后在拟合到较小峰之前从数据中掩盖这一点 – Chris 2012-04-13 15:50:43