擅长:python、mysql、java
<p>您还可以使用scipy.optimize()中的curve_fit拟合高斯函数,在这里您可以定义自己的自定义函数。这里,我给出一个高斯曲线拟合的例子。例如,如果有两个数组<code>x</code>和<code>y</code>。</p>
<pre><code>from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])
n = len(x) #the number of data
mean = sum(x*y)/n #note this correction
sigma = sum(y*(x-mean)**2)/n #note this correction
def gaus(x,a,x0,sigma):
return a*exp(-(x-x0)**2/(2*sigma**2))
popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])
plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
</code></pre>
<p>曲线拟合函数需要用三个参数调用:要拟合的函数(在本例中为gaus())、自变量的值(在本例中为x)和从属变量的值(在本例中为y)。curve_fit funtion than返回具有最佳参数的数组(在最小二乘意义上)和包含最佳参数协方差的第二个数组(稍后将详细介绍)。</p>
<p>下面是拟合的输出。</p>
<p><a href="https://i.stack.imgur.com/kAqat.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kAqat.png" alt="enter image description here"/></a></p>