Assume a situation where you have the frame of an equation at ready but are struggling to fit that equation to some data points. In other words, if you are stuck in a situation where you need to fit the and equation or function to a set of data points, using curve_fit in scipy is very helpful.

Here is an example where I have created an equation(check out func in the below sample code) with undecided parameters(a,b,c) which has the shape that I want. But I want this shape to pass three points, (0,0) (1,1) (5, 0.2).

Of course, there is no guarantee that by adjusting the three parameters would pass these three points precisely. But I at least want to get the values of the parameters which will be as close to passing these three points as possible.

import numpy as np
from scipy.optimize import curve_fit

def func(x, a,b,c):

    return a - np.exp(b-x) - c * 1/(1+ np.exp(-x))


points = [
    (0,0),
    (1,1),
    (5, 0.2)
]

points = np.array(points)
xdata = points[:,0]
ydata = points[:,1]

out = curve_fit(func, xdata, ydata)


param_matrix = out[0]

a = param_matrix[0]
b = param_matrix[1]
c = param_matrix[2]

if we visualize this function it looks like this:


0 Comments

Leave a Reply

Your email address will not be published.