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
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.
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]: df = sm.datasets.get_rdataset("Guerry", "HistData").data
---------------------------------------------------------------------------
URLError Traceback (most recent call last)
<ipython-input-4-8e82bb04cf4f> in <module>()
----> 1 df = sm.datasets.get_rdataset("Guerry", "HistData").data
/build/statsmodels-0.8.0~rc1+git43-g1ac3f11/debian/python-statsmodels/usr/lib/python2.7/dist-packages/statsmodels/datasets/utils.pyc in get_rdataset(dataname, package, cache)
287 "master/doc/"+package+"/rst/")
288 cache = _get_cache(cache)
--> 289 data, from_cache = _get_data(data_base_url, dataname, cache)
290 data = read_csv(data, index_col=0)
291 data = _maybe_reset_index(data)
/build/statsmodels-0.8.0~rc1+git43-g1ac3f11/debian/python-statsmodels/usr/lib/python2.7/dist-packages/statsmodels/datasets/utils.pyc in _get_data(base_url, dataname, cache, extension)
218 url = base_url + (dataname + ".%s") % extension
219 try:
--> 220 data, from_cache = _urlopen_cached(url, cache)
221 except HTTPError as err:
222 if '404' in str(err):
/build/statsmodels-0.8.0~rc1+git43-g1ac3f11/debian/python-statsmodels/usr/lib/python2.7/dist-packages/statsmodels/datasets/utils.pyc in _urlopen_cached(url, cache)
209 # not using the cache or didn't find it in cache
210 if not from_cache:
--> 211 data = urlopen(url).read()
212 if cache is not None: # then put it in the cache
213 _cache_it(data, cache_path)
/usr/lib/python2.7/urllib2.pyc in urlopen(url, data, timeout, cafile, capath, cadefault, context)
152 else:
153 opener = _opener
--> 154 return opener.open(url, data, timeout)
155
156 def install_opener(opener):
/usr/lib/python2.7/urllib2.pyc in open(self, fullurl, data, timeout)
429 req = meth(req)
430
--> 431 response = self._open(req, data)
432
433 # post-process response
/usr/lib/python2.7/urllib2.pyc in _open(self, req, data)
447 protocol = req.get_type()
448 result = self._call_chain(self.handle_open, protocol, protocol +
--> 449 '_open', req)
450 if result:
451 return result
/usr/lib/python2.7/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
407 func = getattr(handler, meth_name)
408
--> 409 result = func(*args)
410 if result is not None:
411 return result
/usr/lib/python2.7/urllib2.pyc in https_open(self, req)
1238 def https_open(self, req):
1239 return self.do_open(httplib.HTTPSConnection, req,
-> 1240 context=self._context)
1241
1242 https_request = AbstractHTTPHandler.do_request_
/usr/lib/python2.7/urllib2.pyc in do_open(self, http_class, req, **http_conn_args)
1195 except socket.error, err: # XXX what error?
1196 h.close()
-> 1197 raise URLError(err)
1198 else:
1199 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 [5]: vars = ['Department', 'Lottery', 'Literacy', 'Wealth', 'Region']
In [6]: df = df[vars]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-97b909d2ba47> in <module>()
----> 1 df = df[vars]
NameError: name 'df' is not defined
In [7]: df[-5:]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-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 [8]: df = df.dropna()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-c783d194b823> in <module>()
----> 1 df = df.dropna()
NameError: name 'df' is not defined
In [9]: df[-5:]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-387a2dedaa82> in <module>()
----> 1 df[-5:]
NameError: name 'df' is not defined
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:
\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 [10]: y, X = dmatrices('Lottery ~ Literacy + Wealth + Region', data=df, return_type='dataframe')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-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 [11]: y[:3]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-319cfe32a629> in <module>()
----> 1 y[:3]
NameError: name 'y' is not defined
In [12]: X[:3]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-12-a0b703194835> in <module>()
----> 1 X[:3]
NameError: name 'X' is not defined
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 [13]: mod = sm.OLS(y, X) # Describe model
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-13-c6e56946df97> in <module>()
----> 1 mod = sm.OLS(y, X) # Describe model
NameError: name 'y' is not defined
In [14]: res = mod.fit() # Fit model
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-14-6ff53364a7be> in <module>()
----> 1 res = mod.fit() # Fit model
NameError: name 'mod' is not defined
In [15]: print res.summary() # Summarize model
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-15-6ef19fe76b73> in <module>()
----> 1 print res.summary() # Summarize model
NameError: name 'res' is not defined
The res object has many useful attributes. For example, we can extract parameter estimates and r-squared by typing:
In [16]: res.params
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-16-cdb8a4b8734e> in <module>()
----> 1 res.params
NameError: name 'res' is not defined
In [17]: res.rsquared
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-17-375327da2eb6> in <module>()
----> 1 res.rsquared
NameError: name 'res' is not defined
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 [18]: sm.stats.linear_rainbow(res)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-18-d01346ddcfd4> in <module>()
----> 1 sm.stats.linear_rainbow(res)
NameError: name 'res' 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 [19]: sm.graphics.plot_partregress('Lottery', 'Wealth', ['Region', 'Literacy'],
....: data=df, obs_labels=False)
....:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-19-e6a287f2a415> in <module>()
1 sm.graphics.plot_partregress('Lottery', 'Wealth', ['Region', 'Literacy'],
----> 2 data=df, obs_labels=False)
NameError: name 'df' is not defined
Congratulations! You’re ready to move on to other topics in the Table of Contents