Python:如何评估StatsModels中的残差?

Python: How to evaluate the residuals in StatsModels?

我想计算残差:(y-hat y).

我知道怎么做:

df = pd.read_csv('myFile', delim_whitespace = True, header = None)
df.columns = ['column1', 'column2']
y, X = ps.dmatrices('column1 ~ column2',data = df, return_type = 'dataframe')
model = sm.OLS(y,X)
results = model.fit()
predictedValues = results.predict()
#print predictedValues
yData = df.as_matrix(columns = ['column1'])
res = yData - predictedValues

我想知道是否有方法可以做到这一点(?)。

存储在 Results class

resid 属性中

同样有一个results.fittedvalues方法,所以你不需要results.predict()

残差的正态性

选项 1:Jarque-Bera 测试

name = ['Jarque-Bera', 'Chi^2 two-tail prob.', 'Skew', 'Kurtosis']
test = sms.jarque_bera(results.resid)
lzip(name, test)

输出:

[('Jarque-Bera', 3.3936080248431666),
 ('Chi^2 two-tail prob.', 0.1832683123166337),
 ('Skew', -0.48658034311223375),
 ('Kurtosis', 3.003417757881633)]
Omni test:

选项 2:Omni 测试

name = ['Chi^2', 'Two-tail probability']
test = sms.omni_normtest(results.resid)
lzip(name, test)

输出:

[('Chi^2', 3.713437811597181), ('Two-tail probability', 0.15618424580304824)]

如果您正在寻找各种(缩放的)残差,例如 externally/internally 学生化残差、PRESS 残差等,请查看 OLSInfluence class 中的 statsmodels.

使用拟合的结果(RegressionResults 对象)实例化一个 OLSInfluence 对象,该对象将为您计算所有这些属性。这是一个简短的例子:

import statsmodels.api as sm
from statsmodels.stats.outliers_influence import OLSInfluence

data = sm.datasets.spector.load(as_pandas=False)
X = data.exog
y = data.endog

# fit the model
model = sm.OLS(y, sm.add_constant(X, prepend=False))
fit = model.fit()

# compute the residuals and other metrics
influence = OLSInfluence(fit)