python-scipyHow do I use Python Scipy to fit a curve?
To use Python Scipy to fit a curve, you need to use the curve_fit
function from the scipy.optimize
package. This function takes a function that describes the curve you want to fit, and the data points you are fitting to.
Example code
from scipy.optimize import curve_fit
import numpy as np
def func(x, a, b):
return a * np.exp(-b * x)
xdata = np.linspace(0, 4, 50)
y = func(xdata, 2.5, 1.3)
ydata = y + 0.2 * np.random.normal(size=len(xdata))
popt, pcov = curve_fit(func, xdata, ydata)
The output of this code is the optimized parameters popt
and the covariance of the parameters pcov
.
Code explanation
from scipy.optimize import curve_fit
: imports thecurve_fit
function from thescipy.optimize
packagedef func(x, a, b):
: defines the function that describes the curve you want to fitxdata = np.linspace(0, 4, 50)
: creates an array of x-values for the data pointsy = func(xdata, 2.5, 1.3)
: creates an array of y-values calculated from the function with the given parametersydata = y + 0.2 * np.random.normal(size=len(xdata))
: adds random noise to the y-values to simulate real data pointspopt, pcov = curve_fit(func, xdata, ydata)
: calls thecurve_fit
function to optimize the parameters of the function
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use the NumPy transpose function in Python?
- How do I use Python Scipy to perform a Z test?
- How can I use Python Scipy to solve a Poisson equation?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How can I use Python Scipy to zoom in on an image?
- How can I use Python and Numpy to parse XML data?
- How can I use Python and SciPy to implement an ARIMA model?
See more codes...