Note that there are some explanatory texts on larger screens.

plurals
  1. POscipy.optimize.curve_fit unable to fit shifted skewed gaussian curve
    text
    copied!<p>I am trying to fit a skewed and shifted Gaussian curve using scipy's <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow">curve_fit</a> function, but I find that under certain conditions the fitting is quite poor, often giving me close to or exactly a straight line.</p> <p>The code below is derived from the <code>curve_fit</code> documentation. The code provided is an arbitrary set of data for test purposes but displays the issue quite well.</p> <pre><code>import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt import math as math import scipy.special as sp #def func(x, a, b, c): # return a*np.exp(-b*x) + c def func(x, sigmag, mu, alpha, c,a): #normal distribution normpdf = (1/(sigmag*np.sqrt(2*math.pi)))*np.exp(-(np.power((x-mu),2)/(2*np.power(sigmag,2)))) normcdf = (0.5*(1+sp.erf((alpha*((x-mu)/sigmag))/(np.sqrt(2))))) return 2*a*normpdf*normcdf + c x = np.linspace(0,100,100) y = func(x, 10,30, 0,0,1) yn = y + 0.001*np.random.normal(size=len(x)) popt, pcov = curve_fit(func, x, yn,) #p0=(9,35,0,9,1)) y_fit= func(x,popt[0],popt[1],popt[2],popt[3],popt[4]) plt.plot(x,yn) plt.plot(x,y_fit) </code></pre> <p>The issue seems to pop up when I shift the gaussian too far from zero (using <code>mu</code>). I have tried giving initial values, even those identical to my original function, but it does not solve the problem. For a value of <code>mu=10</code>, <code>curve_fit</code> works perfectly, but if I use <code>mu&gt;=30</code> it not longer fits the data.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload