I am using optimize.leastsq to fit data. I would like to constrain the fitting parameter(s) to a certain range. Is it possible to define bounds when using optimize.leastsq? Bounds are implemented in optimize.fmin_slsqp, but I'd prefer to use optimize.leastsq.
leastsq. Minimize the sum of squares of a set of equations. Should take at least one (possibly length N vector) argument and returns M floating point numbers.
The SciPy open source library provides the curve_fit() function for curve fitting via nonlinear least squares. The function takes the same input and output data as arguments, as well as the name of the mapping function to use. The mapping function must take examples of input data and some number of arguments.
NumPy/SciPy's functions are usually optimized for multithreading. Did you look at your CPU utilization to confirm that only one core is being used while the simulation is being ran? Otherwise you have nothing to gain from running multiple instances.
The return value popt contains the best-fit values of the parameters. The return value pcov contains the covariance (error) matrix for the fit parameters. From them we can determine the standard deviations of the parameters, just as we did for linear least chi square.
I think the standard way of handling bounds is by making the function to be minimized (the residuals) very large whenever the parameters exceed the bounds.
import scipy.optimize as optimize
def residuals(p,x,y):
if within_bounds(p):
return y - model(p,x)
else:
return 1e6
p,cov,infodict,mesg,ier = optimize.leastsq(
residuals,p_guess,args=(x,y),full_output=True,warning=True)
I just found this a short time ago
http://code.google.com/p/nmrglue/source/browse/trunk/nmrglue/analysis/leastsqbound.py
It uses parameter transformation to impose box constraints. It also calculates the adjusted covariance matrix for the parameter estimates.
BSD licensed, but I haven't tried it out yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With