简体   繁体   中英

Curve fitting in Python using scipy

I want to fit a curve to some data using curve_fit in scipy. After I searched for the syntax I found this,

import numpy as np
from scipy.optimize import curve_fit

def func(x, a, b, c):
     return a * np.exp(-b * x) + c

xdata = np.linspace(0, 4, 50)
y = func(xdata, 2.5, 1.3, 0.5)
ydata = y + 0.2 * np.random.normal(size=len(xdata))

popt, pcov = curve_fit(func, xdata, ydata)

But the documentation is not really clear, specially regarding the parameters of the function func, I know x is the numpy array of independent variable values, but what are a, b, and c? Also, what does this line mean,

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

to calculate y we call func with the independent variables and other parameters, but what is ydata? And why do we calculate it this way,

ydata = y + 0.2 * np.random.normal(size=len(xdata))

One last thing, if I get the fitted model (the equation) by scipy inside some function, how can I use it in another one?

Any help is appreciated. Thanks.

curve_fit fits a set of data, ydata , with each point given at a value of the independent variable, x , to some model function. In the example, the model function is a * exp(-b * x) + c , where a , b and c are some constants to be determined to best represent the data with this model.

The y calculated by func is the value of the model function at each data point, x .

In the example, ydata is simulated by the fit function with some random Gaussian (normally-distributed) noise added to it:

ydata = y + 0.2 * np.random.normal(size=len(xdata))

You can see this by plotting y (green line) and ydata (blue dots) against xdata :

在此处输入图片说明

To use the fitted parameters, popt , pass them to func :

yfit = func(xdata, *popt)

A plot will show you a comparison of the "exact" (green line) and fit (blue line):

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM