【问题标题】:Getting the regression line to plot from a Pandas regression从 Pandas 回归中获取回归线
【发布时间】:2014-01-23 19:27:15
【问题描述】:

我已经尝试使用 (pandas)pd.ols 和 (statsmodels)sm.ols 来获得回归散点图使用回归线,我可以得到散点图,但我可以似乎没有得到参数来绘制回归线。很明显,我在这里进行了一些剪切和粘贴编码:-((以此为指导:http://nbviewer.ipython.org/github/weecology/progbio/blob/master/ipynbs/statistics.ipynb

我的数据在 pandas DataFrame 中,x 列被合并2[:-1].lastqu 并且 y 数据列被合并 2[:-1].Units 我的代码现在如下: 得到回归:

def fit_line2(x, y):
    X = sm.add_constant(x, prepend=True) #Add a column of ones to allow the calculation of the intercept
    model = sm.OLS(y, X,missing='drop').fit()
    """Return slope, intercept of best fit line."""
    X = sm.add_constant(x)
    return model
model=fit_line2(merged2[:-1].lastqu,merged2[:-1].Units)
print fit.summary()

^^^^ 好像还可以

intercept, slope = model.params  << I don't think this is quite right
plt.plot(merged2[:-1].lastqu,merged2[:-1].Units, 'bo')
plt.hold(True)

^^^^^ 这完成了散点图 ****并且下面没有给我一条回归线

x = np.array([min(merged2[:-1].lastqu), max(merged2[:-1].lastqu)])
y = intercept + slope * x
plt.plot(x, y, 'r-')
plt.show()

Dataframe 的片段:[:-1] 从数据中消除当前周期,随后将成为投影

Units   lastqu  Uperchg lqperchg    fcast   errpercent  nfcast
date                            
2000-12-31   7177    NaN     NaN     NaN     NaN     NaN     NaN
2001-12-31   10694   2195.000000     0.490038    NaN     10658.719019    1.003310    NaN
2002-12-31   11725   2469.000000

编辑:

我发现我可以做到:

fig = plt.figure(figsize=(12,8))
fig = sm.graphics.plot_regress_exog(model, "lastqu", fig=fig)

Statsmodels doc 中所述 这似乎得到了我想要的主要内容(以及更多)我仍然想知道我在之前的代码中哪里出错了!

【问题讨论】:

  • 有什么问题或问题?从阅读示例来看,我认为一切都是正确的。
  • 剩下的问题是我如何使用类似于上面的 x=np.array 序列的代码获得一个简单的回归线不起作用?(没有错误,只是没有行)虽然我可以得到sm.graphics.plot 的结果

标签: python matplotlib pandas statsmodels


【解决方案1】:

检查数组和变量中的值。

我的猜测是您的 x 只是 nans,因为您使用 Python 的最小值和最大值。至少在我当前打开的 Pandas 版本中会发生这种情况。

min 和 max 方法应该可以工作,因为它们知道如何处理 nans 或缺失值

>>> x = pd.Series([np.nan,2], index=['const','slope'])
>>> x
const   NaN
slope     2
dtype: float64

>>> min(x)
nan
>>> max(x)
nan

>>> x.min()
2.0
>>> x.max()
2.0

【讨论】:

  • 所以我做了截距,斜率 = model.params plt.plot(merged2[:-1].lastqu,merged2[:-1].Units, 'bo') plt.hold(True) x = np.array([merged2[:-1].lastqu.min(), merge2[:-1].lastqu.max()]) y = 截距 + 斜率 * x plt.plot(x, y, ' r-') plt.show()
猜你喜欢
  • 2017-05-21
  • 2015-11-30
  • 2021-11-23
  • 2020-08-26
  • 2020-07-21
  • 1970-01-01
  • 2013-07-11
  • 2016-04-12
  • 1970-01-01
相关资源
最近更新 更多