3
votes

I have the following "score" function, that meant to give a score between 0 and one for a certain measurement, that looks like:

def func(x, a, b):
    return 1.0/(1.0+np.exp(-b*(x-a)))

I would like to fit it to the following x and y daya:

x = np.array([4000, 2500, 2000, 1000,  500])
y = np.array([ 0.1,  0.3,  0.5,  0.7,  0.9])

But curve_fit does not seems to work:

popt, pcov = curve_fit(func, x, y)

enter image description here When I try to fit it with a linear function curve_fit gives a good fitting (in green line), but with the exponential function above it just give a=1 and b=1, that is not a good fitting. A good fitting should be a=1800 and b=-0.001667, that gives the red line (data in blue).

1
Could you provide a bit more of your code, including the plot? Then it is easier for others to help. - Philipp

1 Answers

3
votes

The reason is likely that the starting condition is not specified. If you give it as some reasonable numbers, then it is more likely that curve_fit will converge. Below is an example with some reasonable starting conditions:

from scipy.optimize import curve_fit

def func(x, a, b):
    return 1.0/(1.0+np.exp(-b*(x-a)))

x = np.array([4000., 2500., 2000., 1000.,  500.])
y = np.array([ 0.1,  0.3,  0.5,  0.7,  0.9])

popt, pcov = curve_fit(func, x, y, p0=[2000., 0.005])

plot(x, y, 'x')
xx = linspace(0, 4000, 100)
yy = func(xx, *popt)
plot(xx, yy, lw=5)

enter image description here