[英]Fitting a gaussian to a curve in Python
I want to fit a gaussian to a curve using python . 我想使用python将高斯拟合到曲线。 I found a solution here somewhere but it only seems to work for an n shaped gaussian , not for au shaped gaussian . 我在这里某处找到了解决方案,但它似乎仅适用于n型高斯,而不适用于au型高斯。
Here is the code: 这是代码:
import pylab, numpy
from scipy.optimize import curve_fit
x=numpy.array(range(10))
y=numpy.array([0,1,2,3,4,5,4,3,2,1])
n=len(x)
mean=sum(y)/n
sigma=sum(y-mean)**2/n
def gaus(x,a,x0,sigma):
return a*numpy.exp(-(x-x0)**2/(2*sigma**2))
popt, pcov=curve_fit(gaus,x,y,p0=[1,mean,sigma])
pylab.plot(x,y,'r-',x,y,'ro')
pylab.plot(x,gaus(x,*popt),'k-',x,gaus(x,*popt),'ko')
pylab.show()
The code fits a gaussian to an n shaped curve but if I change y to y=numpy.array([5,4,3,2,1,2,3,4,5,6]) then it return some error: Optimal parameters not found: Number of calls to function has reached maxfev = 800. 该代码使高斯曲线适合n形曲线,但是如果我将y更改为y = numpy.array([5,4,3,2,1,2,3,4,5,6]),则返回一些错误:找不到最佳参数:函数调用次数已达到maxfev = 800。
What do I have to change/adjust in the code to fit a U shaped gaussian ? 我必须在代码中进行哪些更改/调整以适合U形高斯? Thanks. 谢谢。
The functional form of your fit is wrong. 适合的功能形式是错误的。 Gaussian's are expected to go to 0 at the tails regardless of whether it is an n or u shape, but yours goes to ~5. 不管是n形还是u形,高斯的尾部都将变为0,但您的约为5。
If you introduce an offset into your equation, and choose reasonable initial values, it works. 如果您在方程式中引入偏移量,并选择合理的初始值,则它会起作用。 See code below: 参见下面的代码:
import pylab, numpy
from scipy.optimize import curve_fit
x=numpy.array(range(10))
y=numpy.array([5,4,3,2,1,2,3,4,5,6])
n=len(x)
mean=sum(y)/n
sigma=sum(y-mean)**2/n
def gaus(x,a,x0,sigma,c):
return a*numpy.exp(-(x-x0)**2/(2*sigma**2))+c
popt, pcov=curve_fit(gaus,x,y,p0=[-1,mean,sigma,-5])
pylab.plot(x,y,'r-',x,y,'ro')
pylab.plot(x,gaus(x,*popt),'k-',x,gaus(x,*popt),'ko')
pylab.show()
也许您可以反转您的值,使其适合“ n”形高斯,然后反转高斯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.