statsmodels 패키지 소개

statsmodels 는 통계 분석을 위한 Python 패키지다. statsmodels의 메인 웹사이트는 다음과 같다.

statsmodels에서 제공하는 통계 분석 기능은 꽤 방대한 편이다.

  • 통계 (Statistics)

    • 각종 검정(test) 기능
    • 커널 밀도 추정
    • Generalized Method of Moments
  • 회귀 분석 (Linear Regression)

    • 선형 모형 (Linear Model)
    • 일반화 선형 모형 (Generalized Linear Model)
    • 강인 선형 모형 (Robust Linear Model)
    • 선형 혼합 효과 모형 (Linear Mixed Effects Model)
    • ANOVA (Analysis of Variance)
    • Discrete Dependent Variable (Logistic Regression 포함)
  • 시계열 분석 (Time Series Analysis)

    • ARMA/ARIMA Process
    • Vector ARMA Process

특히 선형 회귀분석의 경우 R-style 모형 기술을 가능하게 하는 patsy 패키지를 포함하고 있어 기존에 R을 사용하던 사람들도 쉽게 statsmodels를 쓸 수 있게 되었다.

statsmodels를 사용하여 선형 회귀 분석을 수행하는 간단한 예를 보인다.


In [9]:
import statsmodels.api as sm
import statsmodels.formula.api as smf

# 데이터 로드
dat = sm.datasets.get_rdataset("Guerry", "HistData").data
dat.tail()


Out[9]:
dept Region Department Crime_pers Crime_prop Literacy Donations Infants Suicides MainCity ... Crime_parents Infanticide Donation_clergy Lottery Desertion Instruction Prostitutes Distance Area Pop1831
81 86 W Vienne 15010 4710 25 8922 35224 21851 2:Med ... 20 1 44 40 38 65 18 170.523 6990 282.73
82 87 C Haute-Vienne 16256 6402 13 13817 19940 33497 2:Med ... 68 6 78 55 11 84 7 198.874 5520 285.13
83 88 E Vosges 18835 9044 62 4040 14978 33029 2:Med ... 58 34 5 14 85 11 43 174.477 5874 397.99
84 89 C Yonne 18006 6516 47 4276 16616 12789 2:Med ... 32 22 35 51 66 27 272 81.797 7427 352.49
85 200 NaN Corse 2199 4589 49 37015 24743 37016 2:Med ... 81 2 84 83 9 25 1 539.213 8680 195.41

5 rows × 23 columns


In [10]:
# 회귀 분석 
results = smf.ols('Lottery ~ Literacy + np.log(Pop1831)', data=dat).fit()

# 결과 출력
print(results.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                Lottery   R-squared:                       0.348
Model:                            OLS   Adj. R-squared:                  0.333
Method:                 Least Squares   F-statistic:                     22.20
Date:                Thu, 21 Apr 2016   Prob (F-statistic):           1.90e-08
Time:                        03:20:40   Log-Likelihood:                -379.82
No. Observations:                  86   AIC:                             765.6
Df Residuals:                      83   BIC:                             773.0
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
===================================================================================
                      coef    std err          t      P>|t|      [95.0% Conf. Int.]
-----------------------------------------------------------------------------------
Intercept         246.4341     35.233      6.995      0.000       176.358   316.510
Literacy           -0.4889      0.128     -3.832      0.000        -0.743    -0.235
np.log(Pop1831)   -31.3114      5.977     -5.239      0.000       -43.199   -19.424
==============================================================================
Omnibus:                        3.713   Durbin-Watson:                   2.019
Prob(Omnibus):                  0.156   Jarque-Bera (JB):                3.394
Skew:                          -0.487   Prob(JB):                        0.183
Kurtosis:                       3.003   Cond. No.                         702.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.