Python curve_fit with multiple independent variables

后端 未结 6 602
广开言路
广开言路 2020-11-30 00:27

Python\'s curve_fit calculates the best-fit parameters for a function with a single independent variable, but is there a way, using curve_fit or something else,

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 01:02

    Yes. We can pass multiple variables for curve_fit. I have written a piece of code:

    import numpy as np
    x = np.random.randn(2,100)
    w = np.array([1.5,0.5]).reshape(1,2)
    esp = np.random.randn(1,100)
    y = np.dot(w,x)+esp
    y = y.reshape(100,)
    

    In the above code I have generated x a 2D data set in shape of (2,100) i.e, there are two variables with 100 data points. I have fit the dependent variable y with independent variables x with some noise.

    def model_func(x,w1,w2,b):
      w = np.array([w1,w2]).reshape(1,2)
      b = np.array([b]).reshape(1,1)
      y_p = np.dot(w,x)+b
      return y_p.reshape(100,)
    

    We have defined a model function that establishes relation between y & x.
    Note: The shape of output of the model function or predicted y should be (length of x,)

    popt, pcov = curve_fit(model_func,x,y)
    

    The popt is an 1D numpy array containing predicted parameters. In our case there are 3 parameters.

提交回复
热议问题