<p>有很多方法可以将高斯函数拟合到数据集。我经常在拟合数据时使用astropy,这就是为什么我想添加这个作为额外的答案。</p>
<p>我使用的一些数据集应该模拟高斯噪声:</p>
<pre><code>import numpy as np
from astropy import modeling
m = modeling.models.Gaussian1D(amplitude=10, mean=30, stddev=5)
x = np.linspace(0, 100, 2000)
data = m(x)
data = data + np.sqrt(data) * np.random.random(x.size) - 0.5
data -= data.min()
plt.plot(x, data)
</code></pre>
<p><a href="https://i.stack.imgur.com/Gu5ln.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Gu5ln.png" alt="enter image description here"/></a></p>
<p>然后拟合它实际上非常简单,您可以指定要拟合数据的模型和拟合者:</p>
<pre><code>fitter = modeling.fitting.LevMarLSQFitter()
model = modeling.models.Gaussian1D() # depending on the data you need to give some initial values
fitted_model = fitter(model, x, data)
</code></pre>
<p>并绘制:</p>
<pre><code>plt.plot(x, data)
plt.plot(x, fitted_model(x))
</code></pre>
<p><a href="https://i.stack.imgur.com/81Z2I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/81Z2I.png" alt="enter image description here"/></a></p>
<hr/>
<p>不过,也可以只使用Scipy,但必须自己定义函数:</p>
<pre><code>from scipy import optimize
def gaussian(x, amplitude, mean, stddev):
return amplitude * np.exp(-((x - mean) / 4 / stddev)**2)
popt, _ = optimize.curve_fit(gaussian, x, data)
</code></pre>
<p>这将返回拟合的最佳参数,您可以这样绘制:</p>
<pre><code>plt.plot(x, data)
plt.plot(x, gaussian(x, *popt))
</code></pre>
<p><a href="https://i.stack.imgur.com/3akUy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3akUy.png" alt="enter image description here"/></a></p>