如何推断简单的线性回归并获取Python中系数的误差?

时间:2019-09-23 07:11:12

标签: python python-3.x linear-regression

这是我的示例数据:

x = np.array([19.0, 47.0, 34.6, 23.2, 33.5, 28.2,34.8, 15.8, 23.8])
y = np.array([6.12,3.55, 2.67, 2.81, 5.34, 3.75,3.43, 1.44, 0.84])
pl.scatter(x,y, facecolors='b', edgecolors='b', s=24)
x = x[:,np.newaxis]
a, _, _, _ = np.linalg.lstsq(x, y)
pl.plot(x, a*x, 'r-')
pl.xlim(0,50)
pl.ylim(0,7)

Resulting plot with linear fit

您可以在图中看到线性拟合未达到y = 0。如何找到y = 0时的x值(即外推数据)?有没有一种方法可以进行误差传播以获取系数的误差?

2 个答案:

答案 0 :(得分:0)

要进行推断,只需传递以绘制更长的y数组即可。

仅需在插入行之后将0插入数组即可。

y = np.insert(y, 0, 0)

然后传递到情节:

pl.plot(y/a, y, 'r-')

答案 1 :(得分:0)

与Numpy中相对较低级别的statsmodels函数相比,lstsq软件包可能更易于使用。您的问题只是估计:

y_i = x_i*a + sigma_i

因此,x=0将始终位于y=0。您可能希望您的代码会估算:

y_i = a_0 + x_i*a_1 + sigma_i

a_0是截距,a_1x系数。

使用statsmodels需要提取更多软件包,但有much easier interface

import statsmodels.formula.api as smf
import pandas as pd

df = pd.DataFrame(dict(x=x, y=y))

fit = smf.ols('y ~ x', df).fit()
fit.summary()

将打印出来:

                 coef    std err          t      P>|t|      [0.025      0.975]
Intercept      2.4528      1.960      1.251      0.251      -2.183       7.088
x              0.0303      0.065      0.468      0.654      -0.123       0.183

您可以通过以下方式获得x,其中y=0

-fit.params[0] / fit.params[1]

给出大约-81。如果您确实想将截距固定为零,则可以在公式中添加+ 0

fit = smf.ols('y ~ x + 0', df).fit()

此接口违反了Python的“显式优于隐式”规则,但是复制了“ R”语言样式formula s,并且(以我的经验)大多数回归都想估计截距。