0
0
SciPydata~7 mins

Non-linear curve fitting in SciPy

Choose your learning style9 modes available
Introduction

We use non-linear curve fitting to find a smooth curve that best matches data points when the relationship is not a straight line.

You want to model how a plant grows over time with a curve that bends.
You have data from a chemical reaction that follows a curve, not a line.
You want to predict sales that grow quickly then slow down, not just increase steadily.
You need to fit a curve to data points that form a wave or exponential shape.
Syntax
SciPy
from scipy.optimize import curve_fit

popt, pcov = curve_fit(function, xdata, ydata, p0=None)

function is the model you think fits your data, like an exponential or sine curve.

p0 is optional starting guesses for the curve parameters to help fitting.

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

popt, pcov = curve_fit(model, xdata, ydata)
Fit an exponential curve with initial guesses for parameters.
SciPy
import numpy as np

def model(x, a, b, c):
    return a * np.exp(b * x) + c

popt, pcov = curve_fit(model, xdata, ydata, p0=[1, 0.1, 0])
Sample Program

This program fits an exponential curve to noisy data and shows the fitted parameters and plot.

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

# Create example data: y = 2 * exp(1.5 * x) + noise
xdata = np.linspace(0, 2, 50)
y = 2 * np.exp(1.5 * xdata)
noise = 0.2 * np.random.normal(size=xdata.size)
ydata = y + noise

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

# Fit curve
popt, pcov = curve_fit(model, xdata, ydata, p0=[1, 1])

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

# Plot data and fitted curve
plt.scatter(xdata, ydata, label='Data')
plt.plot(xdata, model(xdata, *popt), 'r-', label='Fitted curve')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Non-linear curve fitting example')
plt.show()
OutputSuccess
Important Notes

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

Curve fitting finds parameters that minimize the difference between your data and the curve.

Plotting the data and fitted curve helps you see how well the curve fits.

Summary

Non-linear curve fitting finds curves that best match data when relationships are not straight lines.

Use scipy.optimize.curve_fit with a model function and your data.

Check fitted parameters and plot results to understand the fit quality.