Using __call__ class method as input for Numpy curve_fit

I would like to use the __call__ class method as input to the Numpy curve_fit function due to my rather complex function and the process of preparing the data (fitting the analytical data of the model to some dimensions). It works great by defining a function, but I can't get it to work with classes.

To recreate my problem, you can run:

 import numpy as np from scipy.optimize import curve_fit #WORKS: #def goal(x,a1,a2,a3,a4,a5): # y=a1*x**4*np.sin(x)+a2*x**3+a3*x**2+a4*x+a5 # return y # DOES NOT WORK: class func(): def __call__(self,x,a1,a2,a3,a4,a5): y=a1*x**4*np.sin(x)+a2*x**3+a3*x**2+a4*x+a5 return y goal=func() #data prepraration *********** xdata=np.linspace(0,50,100) ydata=goal(xdata,-2.1,-3.5,6.6,-1,2) # **************************** popt, pcov = curve_fit(goal, xdata, ydata) print 'optimial parameters',popt print 'The estimated covariance of optimial parameters',pcov 

The error I am getting is:

 Traceback (most recent call last): File "D:\...some path...\test_minimizacija.py", line 35, in <module> popt, pcov = curve_fit(goal, xdata, ydata) File "C:\Python26\lib\site-packages\scipy\optimize\minpack.py", line 412, in curve_fit args, varargs, varkw, defaults = inspect.getargspec(f) File "C:\Python26\lib\inspect.py", line 803, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function 

How can I do this job?

+4
source share
1 answer

Easy (though not very), just change it to:

 popt, pcov = curve_fit(goal.__call__, xdata, ydata) 

Interestingly, numpy forces you to pass an object to the curve_fit function, not an arbitrary callable ...

quickly checking the source for curve_fit , it seems like another workaround might be:

 popt,pcov = curve_fit(goal, xdata, ydata, p0=[1]*5) 

Here p0 is the initial assumption for the fitting parameters. The problem is that scipy checks the arguments of the function so that it knows how many parameters to use, unless you actually provide parameters as an initial assumption. Here, since we have 5 parameters, my initial guess is a list of all of them with a length of 5. ( scipy is used by default, unless you also give an assumption).

+3
source

All Articles