I want to fit some data using curve_fit
. I have a function such as
def fitf(x,y,z=10):
return x*y+z
How do I proceed if I want to pass the optional argument z
? Right now I'm using a wrapper function around fift
such as
def fitff(x,y):
return fitf(x,y,z=50)
but I believe there has to be a better solution to control the optional parameter, which I haven't been able to find in curve_fit
. Is there a clean way to do this?
EDIT
For example, in the MWE below the plot that comes out is the following, which indicates that curve_fit
is actually optimizing the optional value z
as well. Is this behavior expected?
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
def fitf(x,y,z=10):
return x*y+z
array1=range(10)
array2=[ fitf(el,5., z=2) for el in array1 ]
print array1
print array2
a=curve_fit(fitf, array1, array2)[0]
print a[0]
array3=[ fitf(el, a[0], z=a[1]) for el in array1 ]
print array3
plt.plot(array1)
plt.plot(array2)
plt.plot(array3, 'o')
plt.show()
You can do this with a
lambda
or a closure. Here's a lambda:A closure would look like:
which takes a few extra lines for defining the closure, but then the call to
curve_fit
is cleaner and more intuitive.As pointed out by @TomCho
partial
won't work, "Apparently this is because partial functions cannot be inspected..."