在Python中绘制GP 95%的置信区间

时间:2020-07-27 09:34:45

标签: python matplotlib confidence-interval gaussian-process

我使用高斯过程回归来拟合我的数据,并且效果很好。但是,当我尝试在估计中绘制置信区间时。我看到的是一个混乱的图,如下所示。

enter image description here

红线表示较高的CI,蓝线表示较低的CI,黑线是我的估计数据。我为此编写了以下代码

f3 = plt.figure()
plt.plot(X_te_rescale[:,0],pred_y.ravel(),'k.',markersize=20,label='prediction')
plt.plot(X_te_rescale[:,0],low_CIs,'b.',markersize=2)
plt.plot(X_te_rescale[:,0],Upper_CIs,'r.',markersize=2)
plt.legend(loc='1')
plt.show()

我在Google中进行搜索,发现fill between对此很有用,因此也使用了它,结果也很糟糕。见下图

enter image description here

主要GP代码

pred_y, sigma = gpr.predict(X_te_rescale, return_std=True)
confidence_interval = sigma * 1.96
low_CIs=pred_y - confidence_interval
Upper_CIs= pred_y + confidence_interval

我为此编写的代码如下

plt.scatter(X_tr_rescale, y_tr_rescale, label='Train data')
plt.fill_between(X_te_rescale[:,0],
                  pred_y[:,0] - confidence_interval,
                  pred_y[:,0] + confidence_interval,
                  facecolor='black', alpha=0.5, label='95% confidence interval')
plt.gca().set_title(gp.kernel_)
plt.plot(X_te_rescale, pred_y, 'r.',label='Prediction')

数据细节如下。

y_te_rescale: Array of floats64 (1188,1)
sigma: Array of floats64 (1188,)
Confidence interval: Array of floats64 (1188,)
lower CIs: Array of floats64 (1188,1188)
upper CIs: Array of floats64 (1188,1188)
pred_y: Array of floats64 (1188,1)

是否可能有一个CI与我的估计值不重叠?或我缺少的东西。提前致谢。 根据评论,我将代码修改如下

x_unsorted=X_te_rescale.flatten()
pred_y=pred_y.flatten()
sorted_inds = np.argsort(x_unsorted)
plt.fill_between(
    x_unsorted[sorted_inds],
    (pred_y - confidence_interval)[sorted_inds],
    (pred_y+ confidence_interval)[sorted_inds],
    label='95% CI',
)
plt.plot(
    x_unsorted[sorted_inds], 
    pred_y.ravel[sorted_inds], 
    'r--',
    label='Prediction',
)

这给出了如下图

enter image description here

上面的代码虽然显示了置信区间,但是无法估计值。此代码正确吗?或如何绘制置信区间以及可以清楚看到的估计值。

1 个答案:

答案 0 :(得分:0)

使用plt.fill_between的问题是x值未排序。如果您是绘制一条线而不是一组点,plt.plot也会产生类似的不良结果。

尝试这样的事情:

sorted_inds = np.argsort(x_unsorted)
plt.fill_between(
    x_unsorted[sorted_inds],
    (y_pred - conf_intervals)[sorted_inds],
    (y_pred + conf_intervals)[sorted_inds],
    label='95% CI',
)
plt.plot(
    x_unsorted[sorted_inds], 
    y_pred[sorted_inds], 
    'k-',
    label='Prediction',
)
相关问题