0

I am trying to to fit my data to a curve using the function scipy.optimize.curve_fit. Given certain values, the function works the way I want it to. As such:

from scipy.optimize import curve_fit    

def f1(x, a, b):
    return a*((1-(x/b))**2)

x_given = [450, 500, 525, 575, 625]
y_given = [33.8, 32.5, 32, 30.2, 28.4]

params, extras = curve_fit(f1, x_given, y_given)

x_new = list(range(-1000, 10000, 1))

plt.plot(x_given, y_given, 'o', markersize=10, color='r')
plt.plot(x_new, f1(x_new, params[0], params[1]))
plt.grid()
plt.show()

And gives the following curve:

figure 1 However when I try to fit different data by changing x_given and y_given to x_given = [875, 850, 825, 800] and y_given = [26, 26.75, 27.25, 28], the following error shows up:

RuntimeError: Optimal parameters not found: Number of calls to function has    
reached maxfev = 600.

So I increased maxfev till the error stops showing up:

def f1(x, a, b):
    return a*((1-(x/b))**2)

x_given = [875, 850, 825, 800]
y_given = [26, 26.75, 27.25, 28]

params, extras = curve_fit(f1, x_given, y_given, maxfev=3700)
x_new = list(range(-1000, 10000, 1))

However, now I get a wrong fitting of the curve. The left part of the curve should be where the points are.

enter image description here

I'm not sure how to correct this. Or if adjusting maxfev is the right way to do it?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
xplodnow
  • 247
  • 4
  • 14
  • Basically you got a reasonable approximation. To get a better one start with a closer initial guess `params, extras = curve_fit(f1, x_given, y_given, p0=[2000**2, 2000])`. – Aguy Aug 08 '16 at 20:00
  • @Aguy Oh. I see what you mean. That worked out well! Thank you! – xplodnow Aug 17 '16 at 03:10

0 Answers0