How to extrapolate simple linear regression and get errors for the coefficients in Python?

雨燕双飞 提交于 2020-01-06 07:03:10

问题


Here is my sample data:

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)

You can see in the plot that the linear fit does not reach y=0. How can I find the x-value (i.e. extrapolate the data) at which y=0? And is there a way to get do an error propagation to get the errors for the coefficient?


回答1:


To extrapolate, you just need to pass to plot a longer y array.

Just insert 0 to the array after you fit the line.

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

And then pass to plot:

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



回答2:


the statsmodels package might be easier to use than the relatively low-level lstsq function that's in Numpy. your question is just estimating:

y_i = x_i*a + sigma_i

therefore x=0 will always be at y=0. you might be expecting your code to be estimating:

y_i = a_0 + x_i*a_1 + sigma_i

i.e a_0 is the intercept, and a_1 is the x coefficient.

using statsmodels would require pulling in more packages, but has a 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()

would print out:

                 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

and you can get x where y=0 via:

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

giving approx -81. if you really wanted to fix the intercept as zero, you would add + 0 to the formula:

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

this interface goes against the Python "explicit is better than implicit" rule, but copies the "R" language style formulas and (in my experience) most regressions want to estimate the intercept anyway.



来源:https://stackoverflow.com/questions/58057314/how-to-extrapolate-simple-linear-regression-and-get-errors-for-the-coefficients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!