2

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) 
user032020
  • 406
  • 2
  • 13

1 Answers1

1

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))
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Thanks @Mad Physicist for this solution. the lambda function works well. For the *args option, may I ask what does p0 = np.zeros(4) do? – user032020 Jun 30 '22 at 22:09
  • @user032020. Sets your initial guess to 4 zeros, so `curve_fit` does not have to try to parse the arguments of `func` to figure out how many parameters there are. – Mad Physicist Jun 30 '22 at 22:13
  • I see. Thanks. So does that mean let’s say if I have 10parameters to be solved, I would change to np.zeros(10)? Another question is if the initial guess of 0 would impact the result ? I meant the estimation result of the unknown parameters. – user032020 Jun 30 '22 at 22:55
  • 1
    @user032020. That's the default anyway. It has to start somewhere – Mad Physicist Jun 30 '22 at 23:50