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

3 投票
1 回答
12969 浏览
提问于 2025-04-18 17:09

我正在尝试使用 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 个回答

7

如果你想要建立一个模型,像这样 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])

撰写回答