首页 > 解决方案 > 我如何在不同 x 值之间的残差上绘制 2 条单独的平均线 - python

问题描述

在以下代码产生的残差图中,中点附近的值大幅下降

我想通过绘制来自 x(0, 110) 的残差图的 2 条平均线和来自 x(110, 240) 的第二条平均线来帮助那些不太倾向于统计的人可视化这一点

这是代码

FINAL LINEAR MODEL

x = merged[['Imp_Col_LNG', 'AveSH_LNG']].values
y = merged['Unproductive_LNG'].values


from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(x,y)

# plt.scatter(x, y)

yp=reg.predict(x)
# plt.plot(xp,yp)
# plt.text(x.max()*0.7,y.max()*0.1,'$R^2$ = 
{score:.4f}'.format(score=reg.score(x,y)))
# plt.show()

plt.scatter(yp, y)

s = yp.argsort()
plt.plot(yp[s], yp[s],color='k',ls='--') 

from scipy.stats import norm
ub = yp + norm.ppf(0.5+0.95/2) * res.std(ddof=1)
lb = yp - norm.ppf(0.5+0.95/2) * res.std(ddof=1)

plt.plot(yp[s], ub[s],color='k',ls='--')
plt.plot(yp[s], lb[s],color='k',ls='--')


plt.text(x.max()*0.7,y.max()*0.1,'$R^2$ = 
{score:.4f}'.format(score=reg.score(x,y)))

plt.xlabel('Predicted Values')
plt.ylabel('Observed Values')
plt.title('LNG_Shuffles')

plt.show()


RESIDUAL PLOTS

res = pd.Series(y - yp)
checkresiduals(res)
plt.plot(res)

标签: pythonlineaverage

解决方案


由于我们试图绘制 (0, 110) 和 (110, 240) 的残差平均值,我们首先必须计算每个部分的平均值。

这里,以对象res的形式存储残差数据。pd.Series要从中获取数组信息,我们可以使用对象的to_numpy方法pd.Series

res_data = res.to_numpy()

现在,让我们计算每个部分的平均值。

first_average = res_data[:110].mean()
second_average = res_data[110:].mean()

现在,由于我们要在两个不同的范围内绘制它,我们必须在绘制之前将它们转换为 numpy 数组。

plt.plot(np.arange(110), np.ones(110) * first_average)
plt.plot(np.arange(110, 240), np.ones(130) * second_average)

这应该为您提供分段残差平均图。


推荐阅读