Search code examples
pythonmodel-fitting

How to do a simple 'model fitting' in python?


Suppose I have three data sets x, y, z.

I want to fit a simple model: A*x + B*y + C = z (A, B, C are constant.)

How can I do that in Python?

I've found scipy.optimize.curve_fit. However, it seems like it can take only one variable: curve_fit(f, xdata, ydata[, p0, sigma]), which fits f(x) = y. What I need is f(x, y)=z.

In Mathematica, NonLinearModelFit can do the job. I am wondering whether there is a similar module in Python that I've missed.


Solution

  • The docs suggest that scipy.optimize.curve_fit can indeed do what you need. In particular:

    xdata : An M-length sequence or an (k,M)-shaped array

    for functions with k predictors. The independent variable where the data is measured.

    ydata : M-length sequence

    The dependent data — nominally f(xdata, ...)

    If your independent variables are currently individual arrays, you could combine them with np.vstack:

    scipy.optimize.curve_fit(f, np.vstack(x, y), z)