python - 我如何在不同 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)
解决方案
由于我们试图绘制 (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)
这应该为您提供分段残差平均图。
推荐阅读
- azure-devops - 在构建队列时扩展模板验证
- ios - iOS Web 应用程序不能在主屏幕应用程序中脱机工作,但在 Safari 中工作
- python - Python Regex:匹配任何由另一个单词分隔的重复单词
- c++ - 如何使用 C++ 在 Visual Studio 中制作 WinPE 应用程序
- matlab - 如何创建一个以矩阵为输入的函数?
- linq - LINQ 查询左连接两个表并连接
- c# - gRPC 作为 Windows 服务
- c# - 使用 C# 使用 ODP .NET 从 Oracle 数据库中读取 BLOB
- ruby-on-rails - 在前块中创建的 Rspec 变量在功能规范到达 POSTed 控制器操作时被删除
- asp.net-core - 为什么当我返回返回 JSON 时招摇给我 ISE 错误