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_fit
function from thescipy.optimize
moduledef 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 numpy array of zeros using Python?
- How can I use Python Scipy to zoom in on an image?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I calculate variance using Python and SciPy?
- How to use Python, XML-RPC, and NumPy together?
- How do I use Scipy zeros in Python?
- How can I use Python and Numpy to parse XML data?
- How can I use the x.shape function in Python Numpy?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
See more codes...