基于置信区间的非线性曲线拟合代码例子
时间: 2023-07-16 12:16:47 浏览: 115
这里提供一个基于置信区间的非线性曲线拟合的 Python 代码例子,使用的是 `scipy.optimize.curve_fit()` 和 `stats.t.interval()` 函数。
```python
import numpy as np
import scipy.optimize as opt
import scipy.stats as stats
import matplotlib.pyplot as plt
# 定义非线性函数 f(x) = a * sin(b * x) + c * cos(d * x)
def func(x, a, b, c, d):
return a * np.sin(b * x) + c * np.cos(d * x)
# 生成随机数据
x_data = np.linspace(0, 2 * np.pi, 50)
y_data = func(x_data, 1, 2, 3, 4) + 0.2 * np.random.normal(size=len(x_data))
# 利用 curve_fit 进行拟合
popt, pcov = opt.curve_fit(func, x_data, y_data)
# 计算置信区间
alpha = 0.05 # 置信度为 95%
n = len(x_data)
p = len(popt)
t_value = stats.t.ppf(1 - alpha / 2, n - p)
s_res = np.sqrt(np.sum((y_data - func(x_data, *popt)) ** 2) / (n - p))
ci = t_value * s_res * np.sqrt(np.diag(pcov))
# 绘制拟合曲线和置信区间
x_fit = np.linspace(0, 2 * np.pi, 100)
y_fit = func(x_fit, *popt)
y_upper = y_fit + ci
y_lower = y_fit - ci
plt.plot(x_data, y_data, 'bo', label='data')
plt.plot(x_fit, y_fit, 'r-', label='fit')
plt.fill_between(x_fit, y_upper, y_lower, alpha=0.2, label='95% confidence interval')
plt.legend()
plt.show()
```
上述代码中,我们首先定义了一个非线性函数 `func()`,然后生成了一组随机数据作为拟合的样本。接着利用 `curve_fit()` 函数进行拟合,得到了拟合参数 `popt` 和协方差矩阵 `pcov`。然后根据置信度和样本数量计算了 t 值和残差的标准差,最后根据公式计算出了置信区间 `ci`。最后,利用 `fill_between()` 函数将置信区间用灰色区域填充,并绘制出拟合曲线和样本数据点。
注意,这里我们假设了样本数据是带有均值为 0、方差为 0.2 的高斯噪声的理想曲线,实际情况可能会更加复杂。因此,在实际应用中需要根据具体情况进行调整。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)