scipy linregress:仅计算缩放/斜率参数,截距固定为0

时间:2014-08-13 14:39:48

标签: python scipy linear-regression

我正在尝试使用scipy.stats.linregress来计算最小二乘意义上的两组数据之间的比例因子。但是,尽管输入xi变量是向量而不是n X 2矩阵,但它给了我一个截距。

所以,一个简单的代码如下:

from scipy import stats
from numpy import arrange,array

y = [0, 11, 19, 28, 41, 49, 62, 75, 81]
xi = arange(0,9)

scale, intercept, r_value, p_value, std_err = stats.linregress(xi,y)

运行它,我得到10.383的比例,但我也得到-0.86的截距。如何判断它只适合缩放参数,截距应保持为零。

1 个答案:

答案 0 :(得分:6)

如果你想要一个模型,y~xi没有拦截,你可能要考虑使用更多的统计导向包,如statsmodels

In [17]:

import statsmodels.api as sm
import numpy as np
y = [0, 11, 19, 28, 41, 49, 62, 75, 81]
xi = np.arange(0,9)
model = sm.OLS(y, xi)
results = model.fit()
In [18]:

print results.params
[ 10.23039216]

您可以使用R单独验证结果。只有这一点,你现在必须明确指定拦截为0:

x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8)
y <- c(0, 11, 19, 28, 41, 49, 62, 75, 81)
model1 <- lm(y~x+0)
summary(model1)

Call:
lm(formula = y ~ x + 0)

Residuals:
    Min      1Q  Median      3Q     Max 
-2.6912 -1.4608  0.0000  0.6176  3.3873 

Coefficients:
  Estimate Std. Error t value Pr(>|t|)    
x   10.230      0.129   79.29 7.14e-13 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.843 on 8 degrees of freedom
Multiple R-squared:  0.9987,    Adjusted R-squared:  0.9986 
F-statistic:  6286 on 1 and 8 DF,  p-value: 7.14e-13

引擎盖下的计算很简单:

In [29]:

import scipy.optimize as so
so.fmin(lambda b, x, y: ((b*x-y)**2).sum(), x0=0.1, args=(xi, y))
Optimization terminated successfully.
         Current function value: 27.171569
         Iterations: 27
         Function evaluations: 54
Out[29]:
array([ 10.23039063])
相关问题