0
0
SciPydata~5 mins

Curve fitting (curve_fit) in SciPy

Choose your learning style9 modes available
Introduction

Curve fitting helps us find a smooth line or curve that best matches a set of points. It helps us understand trends and make predictions.

You have data points from an experiment and want to find a formula that describes the pattern.
You want to predict future values based on past measurements.
You want to smooth noisy data to see the underlying trend.
You want to compare how well different models fit your data.
Syntax
SciPy
scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, **kwargs)

# f: the model function, f(x, ...params)
# xdata: input data (x values)
# ydata: output data (y values)
# p0: initial guess for parameters (optional)
# sigma: uncertainties in ydata (optional)

The function f must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.

Returns the best-fit parameters and their covariance matrix.

Examples
Fit a straight line y = a*x + b to data.
SciPy
def linear(x, a, b):
    return a * x + b

params, covariance = curve_fit(linear, xdata, ydata)
Fit a quadratic curve with initial guesses for parameters.
SciPy
def quadratic(x, a, b, c):
    return a * x**2 + b * x + c

params, covariance = curve_fit(quadratic, xdata, ydata, p0=[1, 1, 1])
Sample Program

This program fits an exponential decay curve to some noisy data points. It prints the best-fit parameters and shows a plot with the data and the fitted curve.

SciPy
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

# Define model function: exponential decay
def model_func(x, a, b):
    return a * np.exp(-b * x)

# Sample data (x values)
xdata = np.array([0, 1, 2, 3, 4, 5])
# y values with some noise
ydata = np.array([5, 3.1, 1.8, 1.0, 0.5, 0.3])

# Fit curve to data
params, covariance = curve_fit(model_func, xdata, ydata, p0=[5, 0.5])

# Extract fitted parameters
a_fit, b_fit = params

# Print results
print(f"Fitted parameters: a = {a_fit:.2f}, b = {b_fit:.2f}")

# Plot data and fitted curve
plt.scatter(xdata, ydata, label='Data')
x_fit = np.linspace(0, 5, 100)
y_fit = model_func(x_fit, a_fit, b_fit)
plt.plot(x_fit, y_fit, 'r-', label='Fitted curve')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Curve fitting with curve_fit')
plt.show()
OutputSuccess
Important Notes

Good initial guesses (p0) help the fitting find the best solution faster.

The covariance matrix helps estimate the uncertainty of the fitted parameters.

Curve fitting assumes the model function is a good choice for the data pattern.

Summary

Curve fitting finds parameters to make a model match data points closely.

Use curve_fit with a model function and data to get best-fit parameters.

Check the fit visually and consider uncertainties from the covariance matrix.