Search code examples
pythonmachine-learninglinear-regressioncurve-fittingdata-fitting

Fitting a curve with a pivot point Python


I have the plot below and I want to fit it with 2 lines. Using python I manage to fit the upper part:

def func(x,a,b):
    x=np.array(x)
    return a*(x**b)
popt,pcov=curve_fit(func,up_x,up_y)

And I want to fit the lower part with another line, but I want the line to pass through the point where the red one stars, so I can have a continuous function. So my question is how can I use curve_fit by giving a point the function has to pass through, but leaving the slope of the line to be calculated by python? (Or any other python package able to do it)

enter image description here


Solution

  • A possible stepwise parametrisation of your model in log-space is something like:

    (x>q)*((x-q)*a)+(x<q)*((x-q)*c)+b
    

    Where q is the position of the kink, a, and c are the slopes of both parts and b is a global y-offset. Since the model has a discontinuity a gradient based minimizer might not be the best choice to find a best fit. Nevertheless I tried both scipy.optimize.leastsq and scipy.odr and got good results.

    fit to noisy data