高斯拟合在对数日志空间中

时间:2016-03-01 04:05:56

标签: python scipy gaussian

Gaussian fit for Python的答案中是否需要更改任何内容以使数据适合日志空间?具体来说,对于涵盖几个数量级的x和y数据以及此代码段:

from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

b=np.genfromtxt('Stuff.dat', delimiter=None, filling_values=0)
x = b[:,0]
y = b[:,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
popt,pcov = curve_fit(gaus,x,y,p0=[max(y),mean,sigma])
ax = pl.gca()
ax.plot(x, y, 'r.-')
ax.plot(x,gaus(x,*popt),'ro:')
ax.set_xscale('log')
ax.set_yscale('log')

“适合”是水平线,我不确定我的代码中是否遗漏了某些东西,或者我的数据是否不适合高斯分布。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

这就是我所缺少的:数据需要在进行拟合之前进行转换,然后转换回日志轴上的绘图:

from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
import numpy as np

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

b=np.genfromtxt('Stuff.dat', delimiter=None, filling_values=0)
x = np.log(b[:,0])
y = np.log(b[:,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
popt,pcov = curve_fit(gaus,x,y,p0=[max(y),mean,sigma])
ax = pl.gca()
ax.plot(x, y, 'r.-')
ax.plot(10**x,10**(gaus(x,*popt)),'ro:')
ax.set_xscale('log')
ax.set_yscale('log')