Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scipy: bounds for fitting parameter(s) when using optimize.leastsq

Tags:

python

scipy

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.

like image 510
gandi2223 Avatar asked Sep 13 '11 23:09

gandi2223


People also ask

What does SciPy optimize Leastsq do?

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.

How does SciPy optimize curve_fit work?

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.

Is SciPy optimize multithreaded?

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.

What is POPT and PCOV?

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.


2 Answers

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)
like image 186
unutbu Avatar answered Nov 03 '22 20:11

unutbu


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.

like image 22
Josef Avatar answered Nov 03 '22 22:11

Josef