This very simple case-study is designed to get you up-and-running quickly with statsmodels. Starting from raw data, we will show the steps needed to estimate a statistical model and to draw a diagnostic plot. We will only use functions provided by statsmodels or its pandas and patsy dependencies.
After installing statsmodels and its dependencies, we load a few modules and functions:
In [1]: import statsmodels.api as sm
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-6030a6549dc0> in <module>()
----> 1 import statsmodels.api as sm
/builddir/build/BUILD/statsmodels-0.5.0/statsmodels/api.py in <module>()
10 from .discrete.discrete_model import (Poisson, Logit, Probit, MNLogit,
11 NegativeBinomial)
---> 12 from .tsa import api as tsa
13 from .nonparametric import api as nonparametric
14 import distributions
/builddir/build/BUILD/statsmodels-0.5.0/statsmodels/tsa/api.py in <module>()
----> 1 from .ar_model import AR
2 from .arima_model import ARMA, ARIMA
3 import vector_ar as var
4 from .vector_ar.var_model import VAR
5 from .vector_ar.svar_model import SVAR
/builddir/build/BUILD/statsmodels-0.5.0/statsmodels/tsa/ar_model.py in <module>()
16 from statsmodels.tools.numdiff import (approx_fprime, approx_hess,
17 approx_hess_cs)
---> 18 from statsmodels.tsa.kalmanf.kalmanfilter import KalmanFilter
19 import statsmodels.base.wrapper as wrap
20 from statsmodels.tsa.vector_ar import util
/builddir/build/BUILD/statsmodels-0.5.0/statsmodels/tsa/kalmanf/__init__.py in <module>()
----> 1 from kalmanfilter import KalmanFilter
/builddir/build/BUILD/statsmodels-0.5.0/statsmodels/tsa/kalmanf/kalmanfilter.py in <module>()
30 from numpy.linalg import inv, pinv
31 from statsmodels.tools.tools import chain_dot
---> 32 from . import kalman_loglike
33
34 #Fast filtering and smoothing for multivariate state space models
ImportError: cannot import name kalman_loglike
In [2]: import pandas
In [3]: from patsy import dmatrices
pandas builds on numpy arrays to provide rich data structures and data analysis tools. The pandas.DataFrame function provides labelled arrays of (potentially heterogenous) data, similar to the R “data.frame”. The pandas.read_csv function can be used to convert a comma-separated values file to a DataFrame object.
patsy is a Python library for describing satistical models and building Design Matrices using R-like formulas.
We download the Guerry dataset, a collection of historical data used in support of Andre-Michel Guerry’s 1833 Essay on the Moral Statistics of France. The data set is hosted online in comma-separated values format (CSV) by the Rdatasets repository. We could download the file locally and then load it using read_csv, but pandas takes care of all of this automatically for us:
In [4]: url = "http://vincentarelbundock.github.com/Rdatasets/csv/HistData/Guerry.csv"
...: #the next two lines are not necessary with a recent version of pandas
...:
In [6]: from urllib2 import urlopen
In [7]: url = urlopen(url)
In [8]: df = pandas.read_csv(url)
The Input/Output doc page shows how to import from various other formats.
We select the variables of interest and look at the bottom 5 rows:
In [9]: vars = ['Department', 'Lottery', 'Literacy', 'Wealth', 'Region']
In [10]: df = df[vars]
In [11]: df[-5:]
Out[11]:
Department Lottery Literacy Wealth Region
81 Vienne 40 25 68 W
82 Haute-Vienne 55 13 67 C
83 Vosges 14 62 82 E
84 Yonne 51 47 30 C
85 Corse 83 49 37 NaN
Notice that there is one missing observation in the Region column. We eliminate it using a DataFrame method provided by pandas:
In [12]: df = df.dropna()
In [13]: df[-5:]
Out[13]:
Department Lottery Literacy Wealth Region
80 Vendee 68 28 56 W
81 Vienne 40 25 68 W
82 Haute-Vienne 55 13 67 C
83 Vosges 14 62 82 E
84 Yonne 51 47 30 C
We want to know whether literacy rates in the 86 French departments are associated with per capita wagers on the Royal Lottery in the 1820s. We need to control for the level of wealth in each department, and we also want to include a series of dummy variables on the right-hand side of our regression equation to control for unobserved heterogeneity due to regional effects. The model is estimated using ordinary least squares regression (OLS).
To fit most of the models covered by statsmodels, you will need to create two design matrices. The first is a matrix of endogenous variable(s) (i.e. dependent, response, regressand, etc.). The second is a matrix of exogenous variable(s) (i.e. independent, predictor, regressor, etc.). The OLS coefficient estimates are calculated as usual:
where is an
column of data on lottery wagers per
capita (Lottery).
is
with an intercept, the
Literacy and Wealth variables, and 4 region binary variables.
The patsy module provides a convenient function to prepare design matrices using R-like formulas. You can find more information here: http://patsy.readthedocs.org
We use patsy‘s dmatrices function to create design matrices:
In [14]: y, X = dmatrices('Lottery ~ Literacy + Wealth + Region', data=df, return_type='dataframe')
The resulting matrices/data frames look like this:
In [15]: y[:3]
Out[15]:
Lottery
0 41
1 38
2 66
In [16]: X[:3]
Out[16]:
Intercept Region[T.E] Region[T.N] Region[T.S] Region[T.W] Literacy \
0 1 1 0 0 0 37
1 1 0 1 0 0 51
2 1 0 0 0 0 13
Wealth
0 73
1 22
2 61
Notice that dmatrices has
The above behavior can of course be altered. See the patsy doc pages.
Fitting a model in statsmodels typically involves 3 easy steps:
For OLS, this is achieved by:
In [17]: mod = sm.OLS(y, X) # Describe model
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-17-c6e56946df97> in <module>()
----> 1 mod = sm.OLS(y, X) # Describe model
NameError: name 'sm' is not defined
In [18]: res = mod.fit() # Fit model
In [19]: print res.summary() # Summarize model
OLS Regression Results
==============================================================================
Dep. Variable: write R-squared: 0.107
Model: OLS Adj. R-squared: 0.093
Method: Least Squares F-statistic: 7.833
Date: Mon, 21 Jul 2014 Prob (F-statistic): 5.78e-05
Time: 23:39:26 Log-Likelihood: -721.77
No. Observations: 200 AIC: 1452.
Df Residuals: 196 BIC: 1465.
Df Model: 3
===========================================================================================
coef std err t P>|t| [95.0% Conf. Int.]
-------------------------------------------------------------------------------------------
Intercept 51.6784 0.982 52.619 0.000 49.741 53.615
C(race, Simple)[Simp.1] 11.5417 3.286 3.512 0.001 5.061 18.022
C(race, Simple)[Simp.2] 1.7417 2.732 0.637 0.525 -3.647 7.131
C(race, Simple)[Simp.3] 7.5968 1.989 3.820 0.000 3.675 11.519
==============================================================================
Omnibus: 10.487 Durbin-Watson: 1.779
Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031
Skew: -0.551 Prob(JB): 0.00402
Kurtosis: 2.670 Cond. No. 7.03
==============================================================================
The res object has many useful attributes. For example, we can extract parameter estimates and r-squared by typing:
In [20]: res.params
Out[20]:
Intercept 51.678376
C(race, Simple)[Simp.1] 11.541667
C(race, Simple)[Simp.2] 1.741667
C(race, Simple)[Simp.3] 7.596839
dtype: float64
In [21]: res.rsquared
Out[21]: 0.10706255544473642
Type dir(res) for a full list of attributes.
For more information and examples, see the Regression doc page
statsmodels allows you to conduct a range of useful regression diagnostics and specification tests. For instance, apply the Rainbow test for linearity (the null hypothesis is that the relationship is properly modelled as linear):
In [22]: sm.stats.linear_rainbow(res)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-22-d01346ddcfd4> in <module>()
----> 1 sm.stats.linear_rainbow(res)
NameError: name 'sm' is not defined
Admittedly, the output produced above is not very verbose, but we know from reading the docstring (also, print sm.stats.linear_rainbow.__doc__) that the first number is an F-statistic and that the second is the p-value.
statsmodels also provides graphics functions. For example, we can draw a plot of partial regression for a set of regressors by:
In [23]: from statsmodels.graphics.regressionplots import plot_partregress
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-23-be48e8d8a761> in <module>()
----> 1 from statsmodels.graphics.regressionplots import plot_partregress
/builddir/build/BUILD/statsmodels-0.5.0/statsmodels/graphics/regressionplots.py in <module>()
17 from statsmodels.sandbox.regression.predstd import wls_prediction_std
18 from statsmodels.graphics import utils
---> 19 from statsmodels.nonparametric.smoothers_lowess import lowess
20 from statsmodels.tools.tools import maybe_unwrap_results
21
/builddir/build/BUILD/statsmodels-0.5.0/statsmodels/nonparametric/smoothers_lowess.py in <module>()
9
10 import numpy as np
---> 11 from ._smoothers_lowess import lowess as _lowess
12
13 def lowess(endog, exog, frac=2.0/3.0, it=3, delta=0.0, is_sorted=False,
ImportError: No module named _smoothers_lowess
In [24]: plot_partregress(res)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-24-e05de258c07b> in <module>()
----> 1 plot_partregress(res)
NameError: name 'plot_partregress' is not defined
Congratulations! You’re ready to move on to other topics in the Table of Contents