如何计算 python 中线性回归模型斜率的 99% 置信区间?

How to calculate the 99% confidence interval for the slope in a linear regression model in python?

我们有以下线性回归:y ~ b0 + b1 * x1 + b2 * x2。我知道 Matlab 中的回归函数会计算它,但 numpy 的 linalg.lstsq 不会 (https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html).

您可以使用 scipy 的线性回归,它会计算 r/p 值和标准误差:http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.linregress.html

编辑:正如 Brian 强调的那样,我从 scipy 文档中获得了代码:

from scipy import stats
import numpy as np
x = np.random.random(10)
y = np.random.random(10)
 slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

confidence_interval = 2.58*std_err

StatsModels 的 RegressionResults 有一个 conf_int() method. Here an example using it (minimally modified version of their Ordinary Least Squares 示例):

import numpy as np, statsmodels.api as sm

nsample = 100
x = np.linspace(0, 10, nsample)
X = np.column_stack((x, x**2))
beta = np.array([1, 0.1, 10])
e = np.random.normal(size=nsample)

X = sm.add_constant(X)
y = np.dot(X, beta) + e

mod = sm.OLS(y, X)
res = mod.fit()
print res.conf_int(0.01)   # 99% confidence interval