在 Python 中轻松访问标准化残差、厨师值、价值(杠杆)等?
Access standardized residuals, cook's values, hatvalues (leverage) etc. easily in Python?
我正在寻找拟合线性回归后的影响统计数据。在 R 中,我可以像这样(例如)获得它们:
hatvalues(fitted_model) #hatvalues (leverage)
cooks.distance(fitted_model) #Cook's D values
rstandard(fitted_model) #standardized residuals
rstudent(fitted_model) #studentized residuals
等等
如何在 Python 中使用 statsmodels 在拟合这样的模型后获得相同的统计数据:
#import statsmodels
import statsmodels.api as sm
#Fit linear model to any dataset
model = sm.OLS(Y,X)
results = model.fit()
#Creating a dataframe that includes the studentized residuals
sm.regression.linear_model.OLSResults.outlier_test(results)
编辑:请参阅下面的答案...
我在这里找到它:
OLSInfluence.summary_frame()
虽然接受的答案是正确的,但我发现在拟合模型后将统计信息作为影响实例 (statsmodels.regression.linear_model.OLSResults.get_influence
) 的实例属性单独访问很有帮助。这使我不必为 summary_frame
编制索引,因为我只对其中一个统计数据感兴趣,而不是对所有统计数据感兴趣。所以也许这对其他人有帮助:
import statsmodels.api as sm
#Fit linear model to any dataset
model = sm.OLS(Y,X)
results = model.fit()
#create instance of influence
influence = results.get_influence()
#leverage (hat values)
leverage = influence.hat_matrix_diag
#Cook's D values (and p-values) as tuple of arrays
cooks_d = influence.cooks_distance
#standardized residuals
standardized_residuals = influence.resid_studentized_internal
#studentized residuals
studentized_residuals = influence.resid_studentized_external
我正在寻找拟合线性回归后的影响统计数据。在 R 中,我可以像这样(例如)获得它们:
hatvalues(fitted_model) #hatvalues (leverage)
cooks.distance(fitted_model) #Cook's D values
rstandard(fitted_model) #standardized residuals
rstudent(fitted_model) #studentized residuals
等等
如何在 Python 中使用 statsmodels 在拟合这样的模型后获得相同的统计数据:
#import statsmodels
import statsmodels.api as sm
#Fit linear model to any dataset
model = sm.OLS(Y,X)
results = model.fit()
#Creating a dataframe that includes the studentized residuals
sm.regression.linear_model.OLSResults.outlier_test(results)
编辑:请参阅下面的答案...
我在这里找到它:
OLSInfluence.summary_frame()
虽然接受的答案是正确的,但我发现在拟合模型后将统计信息作为影响实例 (statsmodels.regression.linear_model.OLSResults.get_influence
) 的实例属性单独访问很有帮助。这使我不必为 summary_frame
编制索引,因为我只对其中一个统计数据感兴趣,而不是对所有统计数据感兴趣。所以也许这对其他人有帮助:
import statsmodels.api as sm
#Fit linear model to any dataset
model = sm.OLS(Y,X)
results = model.fit()
#create instance of influence
influence = results.get_influence()
#leverage (hat values)
leverage = influence.hat_matrix_diag
#Cook's D values (and p-values) as tuple of arrays
cooks_d = influence.cooks_distance
#standardized residuals
standardized_residuals = influence.resid_studentized_internal
#studentized residuals
studentized_residuals = influence.resid_studentized_external