1.5.12.8. 曲线拟合

演示简单的曲线拟合

首先生成一些数据

import numpy as np
# Seed the random number generator for reproducibility
rng = np.random.default_rng(27446968)
x_data = np.linspace(-5, 5, num=50)
noise = 0.01 * np.cos(100 * x_data)
a, b = 2.9, 1.5
y_data = a * np.cos(b * x_data) + noise
# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data)
plot curve fit
<matplotlib.collections.PathCollection object at 0x7f791ee56960>

现在将简单的正弦函数拟合到数据

import scipy as sp
def test_func(x, a, b, c):
return a * np.sin(b * x + c)
params, params_covariance = sp.optimize.curve_fit(
test_func, x_data, y_data, p0=[2, 1, 3]
)
print(params)
[2.900026   1.50012043 1.57079633]

并将得到的曲线绘制到数据上

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label="Data")
plt.plot(x_data, test_func(x_data, *params), label="Fitted function")
plt.legend(loc="best")
plt.show()
plot curve fit

脚本的总运行时间:(0 分钟 0.109 秒)

由 Sphinx-Gallery 生成的图库