Logo

Getting started

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.

Loading modules and functions

After installing statsmodels and its dependencies, we load a few modules and functions:

In [1]: import statsmodels.api as sm

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 statistical models and building Design Matrices using R-like formulas.

Data

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)
---------------------------------------------------------------------------
URLError                                  Traceback (most recent call last)
<ipython-input-7-baebfb7a69e3> in <module>()
----> 1 url = urlopen(url)

/usr/lib/python2.7/urllib2.pyc in urlopen(url, data, timeout)
    125     if _opener is None:
    126         _opener = build_opener()
--> 127     return _opener.open(url, data, timeout)
    128 
    129 def install_opener(opener):

/usr/lib/python2.7/urllib2.pyc in open(self, fullurl, data, timeout)
    402             req = meth(req)
    403 
--> 404         response = self._open(req, data)
    405 
    406         # post-process response

/usr/lib/python2.7/urllib2.pyc in _open(self, req, data)
    420         protocol = req.get_type()
    421         result = self._call_chain(self.handle_open, protocol, protocol +
--> 422                                   '_open', req)
    423         if result:
    424             return result

/usr/lib/python2.7/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
    380             func = getattr(handler, meth_name)
    381 
--> 382             result = func(*args)
    383             if result is not None:
    384                 return result

/usr/lib/python2.7/urllib2.pyc in http_open(self, req)
   1212 
   1213     def http_open(self, req):
-> 1214         return self.do_open(httplib.HTTPConnection, req)
   1215 
   1216     http_request = AbstractHTTPHandler.do_request_

/usr/lib/python2.7/urllib2.pyc in do_open(self, http_class, req)
   1182         except socket.error, err: # XXX what error?
   1183             h.close()
-> 1184             raise URLError(err)
   1185         else:
   1186             try:

URLError: <urlopen error [Errno -2] Name or service not known>

In [8]: df = pandas.read_csv(url)
---------------------------------------------------------------------------
URLError                                  Traceback (most recent call last)
<ipython-input-8-4107a55c8bef> in <module>()
----> 1 df = pandas.read_csv(url)

/usr/lib/python2.7/dist-packages/pandas/io/parsers.pyc in parser_f(filepath_or_buffer, sep, dialect, compression, doublequote, escapechar, quotechar, quoting, skipinitialspace, lineterminator, header, index_col, names, prefix, skiprows, skipfooter, skip_footer, na_values, na_fvalues, true_values, false_values, delimiter, converters, dtype, usecols, engine, delim_whitespace, as_recarray, na_filter, compact_ints, use_unsigned, low_memory, buffer_lines, warn_bad_lines, error_bad_lines, keep_default_na, thousands, comment, decimal, parse_dates, keep_date_col, dayfirst, date_parser, memory_map, nrows, iterator, chunksize, verbose, encoding, squeeze, mangle_dupe_cols, tupleize_cols, infer_datetime_format)
    418                     infer_datetime_format=infer_datetime_format)
    419 
--> 420         return _read(filepath_or_buffer, kwds)
    421 
    422     parser_f.__name__ = name

/usr/lib/python2.7/dist-packages/pandas/io/parsers.pyc in _read(filepath_or_buffer, kwds)
    204 
    205     filepath_or_buffer, _ = get_filepath_or_buffer(filepath_or_buffer,
--> 206                                                    encoding)
    207 
    208     if kwds.get('date_parser', None) is not None:

/usr/lib/python2.7/dist-packages/pandas/io/common.pyc in get_filepath_or_buffer(filepath_or_buffer, encoding)
    116 
    117     if _is_url(filepath_or_buffer):
--> 118         req = _urlopen(str(filepath_or_buffer))
    119         return maybe_read_encoded_stream(req, encoding)
    120 

/usr/lib/python2.7/urllib2.pyc in urlopen(url, data, timeout)
    125     if _opener is None:
    126         _opener = build_opener()
--> 127     return _opener.open(url, data, timeout)
    128 
    129 def install_opener(opener):

/usr/lib/python2.7/urllib2.pyc in open(self, fullurl, data, timeout)
    402             req = meth(req)
    403 
--> 404         response = self._open(req, data)
    405 
    406         # post-process response

/usr/lib/python2.7/urllib2.pyc in _open(self, req, data)
    420         protocol = req.get_type()
    421         result = self._call_chain(self.handle_open, protocol, protocol +
--> 422                                   '_open', req)
    423         if result:
    424             return result

/usr/lib/python2.7/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
    380             func = getattr(handler, meth_name)
    381 
--> 382             result = func(*args)
    383             if result is not None:
    384                 return result

/usr/lib/python2.7/urllib2.pyc in http_open(self, req)
   1212 
   1213     def http_open(self, req):
-> 1214         return self.do_open(httplib.HTTPConnection, req)
   1215 
   1216     http_request = AbstractHTTPHandler.do_request_

/usr/lib/python2.7/urllib2.pyc in do_open(self, http_class, req)
   1182         except socket.error, err: # XXX what error?
   1183             h.close()
-> 1184             raise URLError(err)
   1185         else:
   1186             try:

URLError: <urlopen error [Errno -2] Name or service not known>

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]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-97b909d2ba47> in <module>()
----> 1 df = df[vars]

NameError: name 'df' is not defined

In [11]: df[-5:]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-387a2dedaa82> in <module>()
----> 1 df[-5:]

NameError: name 'df' is not defined

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()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-c783d194b823> in <module>()
----> 1 df = df.dropna()

NameError: name 'df' is not defined

In [13]: df[-5:]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-387a2dedaa82> in <module>()
----> 1 df[-5:]

NameError: name 'df' is not defined

Substantive motivation and model

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).

Design matrices (endog & exog)

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:

\hat{\beta} = (X'X)^{-1} X'y

where y is an N \times 1 column of data on lottery wagers per capita (Lottery). X is N \times 7 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')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-14-b205df6907aa> in <module>()
----> 1 y, X = dmatrices('Lottery ~ Literacy + Wealth + Region', data=df, return_type='dataframe')

NameError: name 'df' is not defined

The resulting matrices/data frames look like this:

In [15]: y[:3]
Out[15]: array([ 5.8122,  5.1196,  5.9602])

In [16]: X[:3]
Out[16]: 
array([[ 0.    ,  1.    ],
       [ 0.4082,  1.    ],
       [ 0.8163,  1.    ]])

Notice that dmatrices has

  • split the categorical Region variable into a set of indicator variables.
  • added a constant to the exogenous regressors matrix.
  • returned pandas DataFrames instead of simple numpy arrays. This is useful because DataFrames allow statsmodels to carry-over meta-data (e.g. variable names) when reporting results.

The above behavior can of course be altered. See the patsy doc pages.

Model fit and summary

Fitting a model in statsmodels typically involves 3 easy steps:

  1. Use the model class to describe the model
  2. Fit the model using a class method
  3. Inspect the results using a summary method

For OLS, this is achieved by:

In [17]: mod = sm.OLS(y, X)    # Describe model

In [18]: res = mod.fit()       # Fit model

In [19]: print res.summary()   # Summarize model
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.879
Model:                            OLS   Adj. R-squared:                  0.876
Method:                 Least Squares   F-statistic:                     347.7
Date:                Fri, 14 Mar 2014   Prob (F-statistic):           1.25e-23
Time:                        00:01:08   Log-Likelihood:                -68.470
No. Observations:                  50   AIC:                             140.9
Df Residuals:                      48   BIC:                             144.8
Df Model:                           1                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1             0.4349      0.023     18.647      0.000         0.388     0.482
const          5.2426      0.271     19.370      0.000         4.698     5.787
==============================================================================
Omnibus:                       10.697   Durbin-Watson:                   2.200
Prob(Omnibus):                  0.005   Jarque-Bera (JB):               29.315
Skew:                           0.153   Prob(JB):                     4.31e-07
Kurtosis:                       6.739   Cond. No.                         23.0
==============================================================================

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]: array([ 0.4349,  5.2426])

In [21]: res.rsquared
Out[21]: 0.87870418171230524

Type dir(res) for a full list of attributes.

For more information and examples, see the Regression doc page

Diagnostics and specification tests

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)
Out[22]: (2.9071343288437821, 0.0061298269187520125)

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

In [24]: plot_partregress(res)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-e05de258c07b> in <module>()
----> 1 plot_partregress(res)

TypeError: plot_partregress() takes at least 3 arguments (1 given)
_images/gettingstarted_0.png

More

Congratulations! You’re ready to move on to other topics in the Table of Contents