高斯不能正确拟合数据

Gaussian does not fit correctly to data

我正在尝试将高斯曲线拟合到我的数据,这是一个密度随高度变化的列表,但是生成的拟合曲线图总是关闭(峰值未对齐,宽度被高估)。这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

#Gaussian function
def gauss_function(x, a, x0, sigma):
    return a*np.exp(-(x-x0)**2/float((2*sigma**2)))

x = heights5
y = demeans5 #density values at each height

amp = max(y)
center = x[np.argmax(y)]
width = 20 #eye-balled estimate


#p0 = amp, width, center
popt, pcov = curve_fit(gauss_function, x, y, p0 = [amp, width, center])

#plot
dataplot = plt.scatter(x, y, marker = '.', label = 'Observations')
gausplot = plt.plot(x,gauss_function(x, *popt), color='red', label ='Gaussian fit')

string = 'fwhm = ' + str(2.355*popt[2]) + '\npeak = ' + str(popt[0]) + '\nmean = ' + str(popt[1]) + '\nsigma = ' + str(popt[2])

#plot labels etc.
plt.xlabel("Height[km]")
plt.ylabel("Density")
plt.legend([dataplot, gausplot], labels = ['fit', 'Observations'])
plt.text(130, 2000, string)
plt.show()

这是它生成的图:

如何更准确地拟合曲线?还有,有没有办法用数据估计宽度?

要获得更准确的匹配,您可以查看 scipy.interpolate 模块。那里的功能在插值和拟合方面做得很好。

其他可以很好地完成工作的拟合技术是: a) CST b) B样条 c) 多项式插值

Scipy 也有 BSplines 的实现。另外两个,可能要自己实现了。

这里回答了一个关于使用 Python 来拟合双峰的非常相似的问题: