Re: [SciPy-User] is it possible to constrain the scipy.optimize.curve_fit function?
![](https://secure.gravatar.com/avatar/2b8e50178b9a65017380fefadd0ba65a.jpg?s=120&d=mm&r=g)
Afaik, there was a big discussion about this a while ago, and the short answer is, currently there is no 'automatic' way to do it. However, in your case, it's pretty easy. Simply define: def func (x, a,b, r): a = abs(a) b = abs(b) r = abs(r) return r + a*np.power(x,-b) And that will do the trick. If you need to more complex boundaries, you can simply use a combination of period functions with a given amplitude or what have you. Alternatively, there are *a lot* of optimization libraries available for Python that are not a part of scipy that offer the possibility to specify boundaries. For example: http://newville.github.com/lmfit-py/ http://ab-initio.mit.edu/wiki/index.php/NLopt_Python_Reference Federico Date: Wed, 16 May 2012 18:20:27 +0200
From: servant mathieu <servant.mathieu@gmail.com> Subject: [SciPy-User] is it possible to constrain the scipy.optimize.curve_fit function? To: scipy-user@scipy.org Message-ID: <CALnu5bM+c9L7taG_CBHdJhw7xpe5amHSVBRUEX7pa7gnRN+-7Q@mail.gmail.com
Content-Type: text/plain; charset="iso-8859-1"
Dear scipy users,
I'm trying to fit to data a power law of the form :
def func (x, a,b, r):
return r + a*np.power(x,-b)
I would like to constrain the curve_fit routine to only allow positive parameter values. How is it possible to do so?
Kind regards,
Mathieu
![](https://secure.gravatar.com/avatar/da3a0a1942fbdc5ee9a9b8115ac5dae7.jpg?s=120&d=mm&r=g)
17.05.2012 11:51, federico vaggi kirjoitti: [clip]
And that will do the trick. If you need to more complex boundaries, you can simply use a combination of period functions with a given amplitude or what have you. Alternatively, there are *a lot* of optimization libraries available for Python that are not a part of scipy that offer the possibility to specify boundaries.
Note that Scipy has several solvers that support bounds in optimization problems --- to use those for least squares, you'll just need to do "return (r**2).sum()" yourself. This is AFAIK also what lmfit does, in addition to clipping parameter values within the bounds in the residual function (I'm not sure how robust the results such clipping produces are). Pauli
participants (2)
-
federico vaggi
-
Pauli Virtanen