简体   繁体   中英

Fitting a gaussian to a curve in Python

I want to fit a gaussian to a curve using python . I found a solution here somewhere but it only seems to work for an n shaped gaussian , not for au shaped gaussian .

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.

What do I have to change/adjust in the code to fit a U shaped gaussian ? 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.

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”形高斯,然后反转高斯。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM