【问题标题】:How can I set the linear regression graph's x range to real value?如何将线性回归图的 x 范围设置为实际值?
【发布时间】:2017-06-06 21:25:55
【问题描述】:

您好,我现在正在学习线性回归。我想从我制作的数据中绘制线性回归图。

如果有如下所示的数据,

one_cycle = [(0, 401.92), (5, 103.62), (7, 62.8), (8, 28.26), (10, 10.55)]

我使用了statsmodels.api.OLS,得到了回归结果。

def basic_regression(one_cycle):
    #one_cycle would be [(0,100),(1,75)...]
    X, Y = [x[0] for x in one_cycle], [x[1] for x in one_cycle]
    
    X = numpy.array(X).T
    X = statsmodels.api.add_constant(X)
    results = statsmodels.api.OLS(Y, X).fit()

    return results

当我绘制结果图表时,

def draw(results):
    fig, ax = plt.subplots()
    fig = statsmodels.api.graphics.plot_fit(results, 0, ax=ax)
    ax.ticklabel_format(useOffset=False)
    plt.show()

该图表不是我所期望的,如下所示。

我期待的是这个图表,而不是那个图表:
(来源:sourceforge.net

我怎么能像那样画 grah? 谢谢你有一个美好的一天。

【问题讨论】:

  • 我认为你想要的是相对于 X 的第二列中的变量而不是第一列中的常量进行绘图。即使用 1 作为 x_var 索引 statsmodels.api.graphics.plot_fit(results, 1, ax=ax)

标签: python matplotlib linear-regression statsmodels


【解决方案1】:

问题出现在行中

X = numpy.array(X).T
X = statsmodels.api.add_constant(X)

X 更改为numpy 数组后,将常量重新分配给X,这意味着从此时起X 是一个二维数组,第一列中有一个。

解决方案是完全删除这两行。

【讨论】:

  • 不要那样做。如果不添加常数,回归将通过原点。
  • @user333700 即使0 不在数据中,我也看不出是否添加常量之间有任何 区别。你能解释一下区别吗?在什么情况下这很重要?
  • add_constant 是 statsmodels 的常见问题解答,因为它不遵循大多数包的“自动”常量传统。例如见stackoverflow.com/questions/38836465/…stackoverflow.com/questions/11495051/…
猜你喜欢
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
相关资源
最近更新 更多