Search code examples
pythondata-analysiscurve-fitting

Not getting a proper curve fit for logistic function


I am a newbie, Please help me, and thanks in advance. I am not getting a proper fit with this code.

def cauchy(x, l, k, x1):
    return l / 1+np.exp(-k*(x-x1))
distance= [1000*0.001, 2000*0.001, 3000*0.001, 4000*0.001,5000*0.001,6000*0.001,7000*0.001,8000*0.001,
           9000*0.001, 11000*0.001, 12000*0.001, 13000*0.001, 14000*0.001, 15000*0.001, 16000*0.001,
           17000*0.001, 18000*0.001, 19000*0.001, 21000*0.001, 22000*0.001, 23000*0.001, 24000*0.001, 25000*0.001, 26000*0.001,
           27000*0.001, 28000*0.001, 29000*0.001, 30000*0.001, 31000*0.001, 32000*0.001, 33000*0.001,
           34000*0.001, 35000*0.001]
amplitude= [26, 31, 29, 26, 27, 24, 24, 28, 24, 24, 28, 31, 24, 26, 55, 30, 73, 101, 168, 219, 448, 833, 1280, 1397, 1181, 1311,
            1715, 1975, 2003, 2034, 2178, 2180, 2182]
plt.plot(distance,amplitude, 'o')
popt, pcov = curve_fit(cauchy, distance, amplitude,maxfev=100, bounds=((-10, -10, -10), (3000, 3000, 3000)),p0=[2500, 1, 0])
print(popt)
plt.plot(distance, cauchy(distance, *popt), 'r', label='cauchy fit')
plt.show()

Solution

  • There two errors in your MCVE:

    • Missing parenthesis in the fitting function;
    • Invalid boundaries for parameters

    Changing for:

    def cauchy(x, l, k, x1):
        return l/(1 + np.exp(-k*(x-x1)))
    
    popt, pcov = curve_fit(cauchy, distance, amplitude, maxfev=100, bounds=((100, 0.1, 0), (1e6, 2, 1e3)), p0=[2500, 1, 0])
    

    Does fit the curve:

    array([2.22741416e+03, 4.06253160e-01, 2.57502178e+01])
    array([[ 6.44969848e+03, -2.38406117e+00,  2.03470488e+01],
           [-2.38406117e+00,  1.73892065e-03, -7.35023469e-03],
           [ 2.03470488e+01, -7.35023469e-03,  1.02073483e-01]])
    

    enter image description here