python-scipyHow do I use scipy.optimize.curve_fit in Python?
scipy.optimize.curve_fit
is a function in the SciPy library of Python used to fit a curve of the form f(x, *params)
to data. It finds the parameters of the curve that best fit the given data points.
from scipy.optimize import curve_fit
import numpy as np
def func(x, a, b):
return a*x + b
x_data = np.array([0, 1, 2, 3, 4, 5])
y_data = np.array([1, 3, 5, 7, 9, 11])
popt, pcov = curve_fit(func, x_data, y_data)
print(popt)
Output example
[2. 1.]
The code above uses curve_fit
to fit a linear function f(x) = a*x + b
to the given data points. The func
function is defined as the model to fit the data to. The x_data
and y_data
are the x-coordinates and y-coordinates of the data points. The curve_fit
function returns two values, popt
and pcov
which are the optimal parameters and the covariance matrix of the parameters respectively. In this case, the optimal parameters are a = 2
and b = 1
.
Code explanation
from scipy.optimize import curve_fit
: imports thecurve_fit
function from the SciPy libraryimport numpy as np
: imports the NumPy library for array manipulationdef func(x, a, b)
: defines the model function to fit the data tox_data
andy_data
: the x-coordinates and y-coordinates of the data pointspopt, pcov = curve_fit(func, x_data, y_data)
: calls thecurve_fit
function to fit the data to the model functionprint(popt)
: prints the optimal parameters
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I create a histogram using Python and SciPy?
- How do I integrate Scipy with Python?
- How do I create a numpy array of zeros using Python?
- How can I use Python and Numpy to zip files?
- How to use Python, XML-RPC, and NumPy together?
- How do I use scipy's griddata function in Python?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- 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?
See more codes...