How to Curve Fitting in Python

Published on Aug. 22, 2023, 12:16 p.m.

To perform curve fitting in Python, you can use the Scipy library’s curve_fit() function. Here’s a simple example:

import numpy as np
from scipy.optimize import curve_fit

# Define the function to fit
def func(x, a, b, c):
    return a * np.exp(-b * x) + c

# Generate some dummy data
x_data = np.linspace(0, 4, 50)
y_data = func(x_data, 2.5, 1.3, 0.5) + 0.2 * np.random.normal(size=len(x_data))

# Perform curve fitting
initial_guess = [1, 1, 1] # initial guess for the parameters
popt, pcov = curve_fit(func, x_data, y_data, p0=initial_guess)

# Print the fitted parameters
print(popt)

# Plot the data and the fitted curve
import matplotlib.pyplot as plt
plt.plot(x_data, y_data, 'o', label='data')
plt.plot(x_data, func(x_data, *popt), 'r-', label='fit')
plt.legend()
plt.show()

In this example, we define a function func() to fit, generate some dummy data to fit it to, and then call the curve_fit() function to find the best-fit parameters for the given data using a non-linear least squares algorithm. The result of the fitting is stored in popt, which contains the optimized parameters of the function. We then plot the data and the fitted curve using Matplotlib.

Tags: