Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monotonically decreasing curve fit using Python

I have a set of data points as shown in the figure. enter image description here

I need to fit a curve to these points such that the curve is monotonically decreasing. There is no specified functional form for the curve. I am experimenting with curve fitting for the first time and in general, I wanted to know how to proceed with being able to choose certain functions, fit them and compare their fit to choose the best.

I believe that for a monotonically decreasing curve,a constraint would be that the first derivative is negative. I was looking at the scipy.curve_fit and scipy.interpolate.UnivariateSpline functions but they don't seem to have the option for a constrained fit. What would be the best function to use in such a case? Thanks.

like image 637
Nitin Avatar asked Feb 10 '14 07:02

Nitin


1 Answers

I am afraid that there is no package for general function fitting. You have to choose and define your function space. And when you do it, it will certainly be finite and there is no problem to add constraints to coefficients that will make sure your function is decreasing.

Moreover, you have to choose your metric/objective function. Do you want to minimize SSE or you have some weights to your points? Or perhaps a completely different objective?

You could start with something like:

import numpy as np
impoty scipy.optimize as opt

def objective(pars):
    a, b, c = pars
    return np.sum((y-(a*np.exp(-b*x)+c))**2)

opt.minimize(objective, x0=np.array([12000, 0.3, 2000])) 
like image 137
Martin Avatar answered Oct 15 '22 11:10

Martin