gaussian fit with scipy.optimize.curve_fit in python with wrong results

后端 未结 1 1894
悲&欢浪女
悲&欢浪女 2020-12-17 01:22

I am having some trouble to fit a gaussian to data. I think the problem is that most of the elements are close to zero, and there not many points to actually be fitted. But

相关标签:
1条回答
  • 2020-12-17 02:10

    Your problem is with the initial parameters of the curve_fit. By default, if no other information is given, it will start with an array of 1, but this obviously lead to a radically wrong result. This can be corrected simply by giving a reasonable starting vector. To do this, I start from the estimated mean and standard deviation of your dataset

    #estimate mean and standard deviation
    meam = sum(x * y)
    sigma = sum(y * (x - m)**2)
    #do the fit!
    popt, pcov = curve_fit(gauss_function, x, y, p0 = [1, mean, sigma])
    #plot the fit results
    plot(x,gauss_function(x, *popt))
    #confront with the given data
    plot(x,y,'ok')
    

    This will perfectly approximate your results. Remember that curve fitting in general cannot work unless you start from a good point (inside the convergence basin, to be clear), and this doesn't depend on the implementation. Never do blind fit when you can use your knowledge!

    0 讨论(0)
提交回复
热议问题