适合数据的高斯积分函数

时间:2014-06-15 13:48:02

标签: python numpy model-fitting

我找到一组给定数据的最小二乘拟合有问题。 我知道数据遵循的函数是高斯和矩形的卷积(通过宽缝的X射线)。到目前为止我所做的是看看卷积积分并发现它归结为: enter image description here 积分参数a是狭缝的宽度(未知和所需),g(x-t)是高斯函数,定义为 enter image description here 所以基本上拟合的函数是高斯的整数函数和由宽度参数a给出的积分边界。然后,也以x-t的偏移进行积分。

这是数据的一小部分,手工制作。     来自pylab import *     来自scipy.optimize import curve_fit     来自scipy.integrate import quad

# 1/10 of the Data to show the form.
xData = array([-0.1 , -0.09, -0.08, -0.07, -0.06, -0.05, -0.04, -0.03, -0.02,
       -0.01,  0.  ,  0.01,  0.02,  0.03,  0.04,  0.05,  0.06,  0.07,
        0.08,  0.09,  0.1 ])
yData = array([  18.      ,   22.      ,   22.      ,   34.000999,   54.002998,
        152.022995,  398.15799 ,  628.39502 ,  884.781982,  848.719971,
        854.72998 ,  842.710022,  762.580994,  660.435974,  346.119995,
        138.018997,   40.001999,    8.      ,    6.      ,    4.      ,
        6.      ])
yerr = 0.1*yData # uncertainty of the data

plt.scatter(xData, yData)
plt.show()

plot of the Data

# functions
def gaus(x, *p):
    """ gaussian with p = A, mu, sigma """
    A, mu, sigma = p
    return A/(sqrt(2*pi)*sigma)*numpy.exp(-(x-mu)**2/(2.*sigma**2))

def func(x,*p):
    """ Convolution of gaussian and rectangle is a gaussian integral.
        Parameters: A, mu, sigma, a"""
    A, mu, sigma, a = p
    return quad(lambda t: gaus(x-t,A,mu,sigma),-a,a)
vfunc = vectorize(func)  # Probably this is a Problem but if I dont use it, func can only be evaluated at 1 point not an array

要看到func确实描述了数据并且我的计算器是正确的,我使用了数据和功能并且厌倦了匹配它们。 我发现以下内容是可行的:

p0=[850,0,0.01, 0.04] # will be used as starting values for fitting
sample = linspace(-0.1,0.1,200) # just to make the plot smooth
y, dy = vfunc(sample,*p0)       

plt.plot(sample, y, label="Handmade Fit")
plt.scatter(xData, yData, label="Data")
plt.legend()
plt.show()

Data and handmade fit 当我尝试使用刚刚获得的起始值来拟合数据时,会出现问题:

fp, Sfcov =  curve_fit(vfunc, xData, yData, p0=p0, sigma=yerr)
yf = vfunc(xData, fp)
plt.plot(x, yf, label="Fit")
plt.show()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-83-6d362c4b9204> in <module>()
----> 1 fp, Sfcov =  curve_fit(vfunc, xData, yData, p0=p0, sigma=yerr)
      2 yf = vfunc(xData,fp)
      3 plt.plot(x,yf, label="Fit")

    /usr/lib/python3/dist-packages/scipy/optimize/minpack.py in curve_fit(f, xdata, ydata, p0, sigma, **kw)
    531     # Remove full_output from kw, otherwise we're passing it in twice.
    532     return_full = kw.pop('full_output', False)
--> 533     res = leastsq(func, p0, args=args, full_output=1, **kw)
    534     (popt, pcov, infodict, errmsg, ier) = res
    535 

/usr/lib/python3/dist-packages/scipy/optimize/minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    369     m = shape[0]
    370     if n > m:
--> 371         raise TypeError('Improper input: N=%s must not exceed M=%s' % (n, m))
    372     if epsfcn is None:
    373         epsfcn = finfo(dtype).eps

TypeError: Improper input: N=4 must not exceed M=2

我认为这意味着我的数据点少于fit-parameters。好吧,让我们看看它:

print("Fit-Parameters: %i"%len(p0))
print("Datapoints: %i"%len(yData))

Fit-Parameters: 4
Datapoints: 21

实际上我有210个数据点。

如上所述,我并不真正理解为什么我需要使用numpy中的矢量函数作为积分函数(func&lt;&gt; vfunc),但不使用它也没有帮助。通常,可以将numpy数组传递给函数,但它似乎在这里不起作用。另一方面,我可能高估了leas-square-fit的功能,在这种情况下可能无法使用,但我不喜欢在这里使用最大似然。一般来说,我从未尝试过对数据进行积分函数,所以这对我来说是新的。可能问题出在这里。我对四边形的了解有限,可能有更好的方法。根据我的知识,不可能分析地执行积分,但显然是理想的解决方案;)。

所有出现此错误的想法是什么?

1 个答案:

答案 0 :(得分:0)

你有两个问题。一个是quad返回一个元组,其中包含值和误差估计值,另一个是你如何进行矢量化。您不希望在矢量参数上进行矢量化。 np.vectorize有一个for循环,所以自己做这个没有性能提升:

def func(x, p):
    """ Convolution of gaussian and rectangle is a gaussian integral.
        Parameters: A, mu, sigma, a"""
    A, mu, sigma, a = p
    return quad(lambda t: gaus(x-t,A,mu,sigma),-a,a)[0]

def vfunc(x, *p):
    evaluations = numpy.array([func(i, p) for i in x])
    return evaluations

请注意,我已将*取消func,而不取自gaus。另外,我选择quad的第一个输出。

虽然这可以解决您的问题,但为了适应卷积,您可以考虑进入傅立叶空间。卷积的傅立叶变换是函数变换的产物,这将大大简化你的生活。此外,一旦在傅立叶空间中,您可以考虑应用低通滤波器来降低噪声。 210个数据点足够高,可以获得良好的结果。

此外,如果你需要更强大的算法,你应该考虑使用ROOT经过长期验证的Minuit来实现iminuit。

相关问题