Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrained np.polyfit

I am trying to fit a quadratic to some experimental data and using polyfit in numpy. I am looking to get a concave curve, and hence want to make sure that the coefficient of the quadratic term is negative, also the fit itself is weighted, as in there are some weights on the points. Is there an easy way to do that? Thanks.

like image 988
ganesh reddy Avatar asked Nov 06 '14 17:11

ganesh reddy


2 Answers

The use of weights is described here (numpy.polyfit). Basically, you need a weight vector with the same length as x and y.

To avoid the wrong sign in the coefficient, you could use a fit function definition like

def fitfunc(x,a,b,c):
    return -1 * abs(a) * x**2 + b * x + c 

This will give you a negative coefficient for x**2 at all times.

like image 72
jkalden Avatar answered Oct 19 '22 17:10

jkalden


You can use curve_fit .

Or you can run polyfit with rank 2 and if the last coefficient is bigger than 0. run again linear polyfit (polyfit with rank 1)

like image 20
Rotem Hayut Avatar answered Oct 19 '22 17:10

Rotem Hayut