深度阅读

How to Curve Fitting in Python

作者
作者
2023年08月22日
更新时间
11.93 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。