您遇到的问题是您使用的包和函数from sklearn.linear_model import LinearRegression
没有提供简单获得置信区间的方法。
如果你想绝对使用sklearn.linear_model.LinearRegression
,您将必须深入研究计算置信区间的方法。一种流行的方法是使用引导,就像使用之前的这个答案 https://stackoverflow.com/questions/27164114/show-confidence-limits-and-prediction-limits-in-scatter-plot.
然而,我解释你的问题的方式是,你正在寻找一种在绘图命令内快速执行此操作的方法,类似于你所附的屏幕截图。如果您的目标纯粹是可视化,那么您可以简单地使用seaborn
包,这也是您的示例图像的来源。
import seaborn as sns
sns.lmplot(x='year', y='count', data=df, fit_reg=True, ci=95, n_boot=1000)
我突出显示了三个不言自明的感兴趣参数及其默认值fit_reg
, ci
, and n_boot
。参考文档 https://seaborn.pydata.org/generated/seaborn.lmplot.html以获得完整的描述。
在引擎盖下,seaborn
使用statsmodels
包裹。因此,如果您想要介于纯粹可视化和自己从头开始编写置信区间函数之间的东西,我建议您使用statsmodels
。具体看用于计算普通最小二乘 (OLS) 线性回归的置信区间的文档 https://www.statsmodels.org/stable/generated/statsmodels.regression.linear_model.OLSResults.conf_int.html.
以下代码应该为您提供在示例中使用 statsmodels 的起点:
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
df = pd.DataFrame({'year':['1990','1991','1992','1993','1994','1995','1996','1997','1998','1999','2000'],
'count':[96,184,148,154,160,149,124,274,322,301,300]})
df['year'] = df['year'].astype(float)
X = sm.add_constant(df['year'].values)
ols_model = sm.OLS(df['count'].values, X)
est = ols_model.fit()
out = est.conf_int(alpha=0.05, cols=None)
fig, ax = plt.subplots()
df.plot(x='year',y='count',linestyle='None',marker='s', ax=ax)
y_pred = est.predict(X)
x_pred = df.year.values
ax.plot(x_pred,y_pred)
pred = est.get_prediction(X).summary_frame()
ax.plot(x_pred,pred['mean_ci_lower'],linestyle='--',color='blue')
ax.plot(x_pred,pred['mean_ci_upper'],linestyle='--',color='blue')
# Alternative way to plot
def line(x,b=0,m=1):
return m*x+b
ax.plot(x_pred,line(x_pred,est.params[0],est.params[1]),color='blue')
这会产生您想要的输出 https://i.stack.imgur.com/sdY3A.png
虽然所有内容的值都可以通过标准 statsmodels 函数访问。