어떻게 fitting을 할까? 여기서, d,t는 변수이고, c_0,c_1..등은
fitting parameter 이다.
Suppose we have data which corresponds to
y=f[d,t]
Something like (d,t)=(0,0) gives y=0, (0,1) gives y=1....
We want to fit these data with certain fitting function
with parameters c1,c2,c3...
fit[d,t; c1,c2,c3]
Even in this case, we can use curve_fit
(Following example copied from http://stackoverflow.com/a/27096056/2775514
from scipy.optimize import curve_fit
import scipy
def fn(x, a, b, c):
return a + b*x[0] + c*x[1]
# y(x0,x1) data:
# x0=0 1 2
# ___________
# x1=0 |0 1 2
# x1=1 |1 2 3
# x1=2 |2 3 4
x = scipy.array([[0,1,2,0,1,2,0,1,2,],[0,0,0,1,1,1,2,2,2]])
y = scipy.array([0,1,2,1,2,3,2,3,4])
popt, pcov = curve_fit(fn, x, y)
print popt
In this example,x[:, i-th], y[i-th] corresponds to i-th data set.
result returns popt -> [0,1,1].
One can use different form :
x = np.array([ [1.0, 1.0 ],[1.0,1.5],[2.0,0.5],[2.1,1.6],[0.5,0.5],[0.8,1.2] ] )
y = 0.5*x[:,0] + 2.0 *x[:,1]**2
def fitf(x,*paras):
return paras[0]*x[:,0]+paras[1]*x[:,1]**2
xx = np.array( [x[:,0],x[:,1]])
def testf(x,*para):
return para[0]*x[0]+x[1]**2*para[1]
print( curve_fit(fitf,x,y,p0=[1,1]) )
print( curve_fit(testf,xx,y,p0=[1,1]) )
Note that curve_fit calls the function as
ydata = f(xdata, *params) +eps
In other words, when xdata is an (k,M) array with M-data,
the function should return array ydata with M-data.
if function only works work for a scalar f(x), it cannot be used directly with curve_fit.
On the other hand, leastsq(cost, p0) assumes the
cost function returns a number or array of length of p0
#--------------------------------------------------------------------------------------------
scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, **kw)[source]
Use non-linear least squares to fit a function, f, to data.
Assumes ydata = f(xdata, *params) + eps
Parameters: |
f : callable
xdata : An M-length sequence or an (k,M)-shaped array
ydata : M-length sequence
p0 : None, scalar, or N-length sequence
sigma : None or M-length sequence, optional
absolute_sigma : bool, optional
check_finite : bool, optional
|
---|---|
Returns: |
popt : array
pcov : 2d array
|
Raises: |
OptimizeWarning
ValueError
|