Search code examples
pythonscipyscipy-optimize

How to use scipy curve_fit to solve equation with some parameters values known


I try to use scipy curve_fit to solve an equation in order to get the estimated value for some unknown parameters. I have the independent variable (x) and dependent variable(y) and one parameter (e) known, now I need to find the estimated value for a, b, c and d.

I used the following code and not quite sure if a, b, c, and d are the "correct" estimated value by using this approach. Any advice would be greatly appreciated.

import pandas as pd
import numpy as np
from scipy.optimize import curve_fit

np.random.seed(0)

x = np.random.randint(0, 100, 100) # known independent variable
y = np.random.randint(0, 100, 100) # known dependent variable
e = np.random.randint(0, 100, 100) # know parameter 

def cubic(x, a, b, c, d, e ):
    return a * x**3 + b * x**2 + c * x + d + e


(a, b, c, d, e), _ = curve_fit(cubic, x, y)

print((a, b, c, d ))
(0.00010514483118750917, -0.00810393624233341, -0.10316706291775657, -24200081.18055175) 

Solution

  • Create a function that only accepts a, b, c, d and passes in the fixed value of e:

    (a, b, c, d), _ = curve_fit(lambda x, a, b, c, d: cubic(x, a, b, c, d, e), x, y)
    

    You can make things a bit more explicit by using *args and an initial guess:

    def func(*args):
        return cubic(*args, e)
    (a, b, c, d), _ = curve_fit(func, x, y, p0=np.zeros(4))