python-scipyHow do I use Python and SciPy to fit a curve?
To fit a curve with Python and SciPy, you can use the curve_fit function from the scipy.optimize module. This function takes a function that you want to fit to the data, as well as the x and y data. It then returns the parameters of the fitted curve.
For example:
from scipy.optimize import curve_fit
import numpy as np
# Define function to fit
def func(x, a, b):
return a * np.exp(-b * x)
# Generate data
xdata = np.linspace(0, 4, 50)
y = func(xdata, 2.5, 1.3)
ydata = y + 0.2 * np.random.normal(size=len(xdata))
# Fit
popt, pcov = curve_fit(func, xdata, ydata)
print(popt)
# Output: [2.55423706 1.35190947]
The curve_fit function returns an array of parameters, popt, that can be used to generate a fitted curve.
Parts of the code:
from scipy.optimize import curve_fit: imports thecurve_fitfunction from thescipy.optimizemoduledef func(x, a, b):: defines the function to fit to the dataxdata = np.linspace(0, 4, 50): creates an array of x valuesydata = y + 0.2 * np.random.normal(size=len(xdata)): creates an array of y values with noisepopt, pcov = curve_fit(func, xdata, ydata): fits the function to the dataprint(popt): prints the parameters of the fitted curve
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I create a zero matrix using Python and Numpy?
- How do I use Scipy zeros in Python?
- How can I use Python Scipy to zoom in on an image?
- How can I use Python and Numpy to parse XML data?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I use Python Scipy to generate a PDF?
- How do I use Python and SciPy to create a tutorial PDF?
- How can I use Python and Numpy to zip files?
- How do I calculate the cross-correlation of two arrays using Python and NumPy?
See more codes...