python代码:计算点预测结果的85%,90%,95%的置信区间,和真实值绘制在一张图上
时间: 2024-03-20 14:42:23 浏览: 33
好的,我可以帮你实现这个功能。假设你已经有了模型预测的结果和真实值,并且已经使用了标准差或置信区间分位数等方法计算出了置信区间,下面是一个绘制置信区间的 Python 代码示例:
```python
import matplotlib.pyplot as plt
import numpy as np
# 假设你有预测值和真实值的列表,以及对应的置信区间
y_pred = [10, 12, 15, 20, 25, 30, 35, 40, 45, 50]
y_true = [8, 11, 13, 18, 23, 28, 33, 38, 43, 48]
conf_int_85 = [(9, 11), (11, 13), (14, 16), (19, 21), (24, 26), (29, 31), (34, 36), (39, 41), (44, 46), (49, 51)]
conf_int_90 = [(8.5, 11.5), (10.5, 12.5), (13, 17), (17.5, 22.5), (22, 27), (27.5, 32.5), (32, 37), (37.5, 42.5), (42, 47), (47.5, 52.5)]
conf_int_95 = [(8, 12), (10, 14), (13, 17), (18, 22), (23, 27), (28, 32), (33, 37), (38, 42), (43, 47), (48, 52)]
# 绘制预测值和真实值的线条
plt.plot(y_pred, label='预测值', color='#BCE6E1')
plt.plot(y_true, label='真实值', color='#FFFF77')
# 绘制不同置信度的置信区间
colors = ['#E8FAFC', '#79E4EF', '#09484F']
conf_ints = [conf_int_85, conf_int_90, conf_int_95]
for i, conf_int in enumerate(conf_ints):
q = i * 5 + 85 # 根据索引计算置信区间的百分比
c = colors[i] # 选取对应的颜色
y_upper = [x[1] for x in conf_int]
y_lower = [x[0] for x in conf_int]
plt.fill_between(range(len(y_pred)), y_lower, y_upper, color=c, alpha=0.5, edgecolor='none', label=f"{q}%的置信区间")
# 添加图例和标签
plt.legend(loc='upper left')
plt.title('Confidence Intervals')
plt.xlabel('Data Points')
plt.ylabel('Value')
# 显示图形
plt.show()
```
这段代码可以绘制点预测结果的多个置信区间,并将预测值和真实值绘制在同一张图上。你可以根据自己的需求和数据格式修改代码。