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

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值