How To Do Scipy Curve Fitting With Error Bars And Obtain Standard Errors On Fitting Parameters?
I am trying to fit my data points. It looks like the fitting without errors are not that optimistic, therefore now I am trying to fit the data implementing the errors at each point
Solution 1:
You can use scipy.optimize.leastsq
with custom weights:
import scipy.optimize as optimize
import numpy as np
# redefine lists as array
x=np.array(r)
y=np.array(logf)
errup=np.array(upper)
errlow=np.array(lower)
# error functiondeffit_func(x,a,b,c):
return np.log10(a*x**b + c)
defmy_error(V):
a,b,c=V
yfit=fit_func(x,a,b,c)
weight=np.ones_like(yfit)
weight[yfit>y]=errup[yfit>y] # if the fit point is above the measure, use upper weight
weight[yfit<=y]=errlow[yfit<=y] # else use lower weightreturn (yfit-y)**2/weight**2
answer=optimize.leastsq(my_error,x0=[0.0001,-1,0.0006])
a,b,c=answer[0]
print(a,b,c)
It works, but is very sensitive to initial values, since there is a log which can go in wrong domain (negative numbers) and then it fails. Here I find a=9.14464745425e-06 b=-1.75179880756 c=0.00066720486385
which is pretty close to data.
Post a Comment for "How To Do Scipy Curve Fitting With Error Bars And Obtain Standard Errors On Fitting Parameters?"