Formulas: Fitting models using R-style formulasΒΆ

Link to Notebook GitHub

Since version 0.5.0, statsmodels allows users to fit statistical models using R-style formulas. Internally, statsmodels uses the patsy package to convert formulas and data to the matrices that are used in model fitting. The formula framework is quite powerful; this tutorial only scratches the surface. A full description of the formula language can be found in the patsy docs:

Loading modules and functions

In [1]:
from __future__ import print_function
import numpy as np
import statsmodels.api as sm

Import convention

You can import explicitly from statsmodels.formula.api

In [2]:
from statsmodels.formula.api import ols

Alternatively, you can just use the formula namespace of the main statsmodels.api.

In [3]:
sm.formula.ols
Out[3]:
<bound method type.from_formula of <class 'statsmodels.regression.linear_model.OLS'>>

Or you can use the following conventioin

In [4]:
import statsmodels.formula.api as smf

These names are just a convenient way to get access to each model's from_formula classmethod. See, for instance

In [5]:
sm.OLS.from_formula
Out[5]:
<bound method type.from_formula of <class 'statsmodels.regression.linear_model.OLS'>>

All of the lower case models accept formula and data arguments, whereas upper case ones take endog and exog design matrices. formula accepts a string which describes the model in terms of a patsy formula. data takes a pandas data frame or any other data structure that defines a __getitem__ for variable names like a structured array or a dictionary of variables.

dir(sm.formula) will print a list of available models.

Formula-compatible models have the following generic call signature: (formula, data, subset=None, *args, **kwargs)

OLS regression using formulas

To begin, we fit the linear model described on the Getting Started page. Download the data, subset columns, and list-wise delete to remove missing observations:

In [6]:
dta = sm.datasets.get_rdataset("Guerry", "HistData", cache=True)
---------------------------------------------------------------------------
URLError                                  Traceback (most recent call last)
<ipython-input-223-0b450e8cdfce> in <module>()
----> 1 dta = sm.datasets.get_rdataset("Guerry", "HistData", cache=True)

/build/statsmodels-0.6.1/debian/python-statsmodels/usr/lib/python2.7/dist-packages/statsmodels/datasets/utils.pyc in get_rdataset(dataname, package, cache)
    284                      "master/doc/"+package+"/rst/")
    285     cache = _get_cache(cache)
--> 286     data, from_cache = _get_data(data_base_url, dataname, cache)
    287     data = read_csv(data, index_col=0)
    288     data = _maybe_reset_index(data)

/build/statsmodels-0.6.1/debian/python-statsmodels/usr/lib/python2.7/dist-packages/statsmodels/datasets/utils.pyc in _get_data(base_url, dataname, cache, extension)
    215     url = base_url + (dataname + ".%s") % extension
    216     try:
--> 217         data, from_cache = _urlopen_cached(url, cache)
    218     except HTTPError as err:
    219         if '404' in str(err):

/build/statsmodels-0.6.1/debian/python-statsmodels/usr/lib/python2.7/dist-packages/statsmodels/datasets/utils.pyc in _urlopen_cached(url, cache)
    206     # not using the cache or didn't find it in cache
    207     if not from_cache:
--> 208         data = urlopen(url).read()
    209         if cache is not None:  # then put it in the cache
    210             _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)
    427             req = meth(req)
    428 
--> 429         response = self._open(req, data)
    430 
    431         # post-process response

/usr/lib/python2.7/urllib2.pyc in _open(self, req, data)
    445         protocol = req.get_type()
    446         result = self._call_chain(self.handle_open, protocol, protocol +
--> 447                                   '_open', req)
    448         if result:
    449             return result

/usr/lib/python2.7/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
    405             func = getattr(handler, meth_name)
    406 
--> 407             result = func(*args)
    408             if result is not None:
    409                 return result

/usr/lib/python2.7/urllib2.pyc in https_open(self, req)
   1239         def https_open(self, req):
   1240             return self.do_open(httplib.HTTPSConnection, req,
-> 1241                 context=self._context)
   1242 
   1243         https_request = AbstractHTTPHandler.do_request_

/usr/lib/python2.7/urllib2.pyc in do_open(self, http_class, req, **http_conn_args)
   1196         except socket.error, err: # XXX what error?
   1197             h.close()
-> 1198             raise URLError(err)
   1199         else:
   1200             try:

URLError: <urlopen error [Errno -3] Temporary failure in name resolution>
In [7]:
df = dta.data[['Lottery', 'Literacy', 'Wealth', 'Region']].dropna()
df.head()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-224-c86d8ac9ee04> in <module>()
----> 1 df = dta.data[['Lottery', 'Literacy', 'Wealth', 'Region']].dropna()
      2 df.head()

/usr/lib/python2.7/dist-packages/pandas/core/generic.pyc in __getattr__(self, name)
   2665             if name in self._info_axis:
   2666                 return self[name]
-> 2667             return object.__getattribute__(self, name)
   2668 
   2669     def __setattr__(self, name, value):

AttributeError: 'DataFrame' object has no attribute 'data'

Fit the model:

In [8]:
mod = ols(formula='Lottery ~ Literacy + Wealth + Region', data=df)
res = mod.fit()
print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-225-536472a0f10b> in <module>()
----> 1 mod = ols(formula='Lottery ~ Literacy + Wealth + Region', data=df)
      2 res = mod.fit()
      3 print(res.summary())

NameError: name 'df' is not defined

Categorical variables

Looking at the summary printed above, notice that patsy determined that elements of Region were text strings, so it treated Region as a categorical variable. patsy's default is also to include an intercept, so we automatically dropped one of the Region categories.

If Region had been an integer variable that we wanted to treat explicitly as categorical, we could have done so by using the C() operator:

In [9]:
res = ols(formula='Lottery ~ Literacy + Wealth + C(Region)', data=df).fit()
print(res.params)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-226-d258a68e10f8> in <module>()
----> 1 res = ols(formula='Lottery ~ Literacy + Wealth + C(Region)', data=df).fit()
      2 print(res.params)

NameError: name 'df' is not defined

Patsy's mode advanced features for categorical variables are discussed in: Patsy: Contrast Coding Systems for categorical variables

Operators

We have already seen that "~" separates the left-hand side of the model from the right-hand side, and that "+" adds new columns to the design matrix.

Removing variables

The "-" sign can be used to remove columns/variables. For instance, we can remove the intercept from a model by:

In [10]:
res = ols(formula='Lottery ~ Literacy + Wealth + C(Region) -1 ', data=df).fit()
print(res.params)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-227-c9050ef6e795> in <module>()
----> 1 res = ols(formula='Lottery ~ Literacy + Wealth + C(Region) -1 ', data=df).fit()
      2 print(res.params)

NameError: name 'df' is not defined

Multiplicative interactions

":" adds a new column to the design matrix with the interaction of the other two columns. "*" will also include the individual columns that were multiplied together:

In [11]:
res1 = ols(formula='Lottery ~ Literacy : Wealth - 1', data=df).fit()
res2 = ols(formula='Lottery ~ Literacy * Wealth - 1', data=df).fit()
print(res1.params, '\n')
print(res2.params)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-228-f906b35aeafd> in <module>()
----> 1 res1 = ols(formula='Lottery ~ Literacy : Wealth - 1', data=df).fit()
      2 res2 = ols(formula='Lottery ~ Literacy * Wealth - 1', data=df).fit()
      3 print(res1.params, '\n')
      4 print(res2.params)

NameError: name 'df' is not defined

Many other things are possible with operators. Please consult the patsy docs to learn more.

Functions

You can apply vectorized functions to the variables in your model:

In [12]:
res = smf.ols(formula='Lottery ~ np.log(Literacy)', data=df).fit()
print(res.params)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-229-023367ac1531> in <module>()
----> 1 res = smf.ols(formula='Lottery ~ np.log(Literacy)', data=df).fit()
      2 print(res.params)

NameError: name 'df' is not defined

Define a custom function:

In [13]:
def log_plus_1(x):
    return np.log(x) + 1.
res = smf.ols(formula='Lottery ~ log_plus_1(Literacy)', data=df).fit()
print(res.params)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-230-0eeba7434bb9> in <module>()
      1 def log_plus_1(x):
      2     return np.log(x) + 1.
----> 3 res = smf.ols(formula='Lottery ~ log_plus_1(Literacy)', data=df).fit()
      4 print(res.params)

NameError: name 'df' is not defined

Any function that is in the calling namespace is available to the formula.

Using formulas with models that do not (yet) support them

Even if a given statsmodels function does not support formulas, you can still use patsy's formula language to produce design matrices. Those matrices can then be fed to the fitting function as endog and exog arguments.

To generate numpy arrays:

In [14]:
import patsy
f = 'Lottery ~ Literacy * Wealth'
y,X = patsy.dmatrices(f, df, return_type='dataframe')
print(y[:5])
print(X[:5])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-231-b909ce5fd501> in <module>()
      1 import patsy
      2 f = 'Lottery ~ Literacy * Wealth'
----> 3 y,X = patsy.dmatrices(f, df, return_type='dataframe')
      4 print(y[:5])
      5 print(X[:5])

NameError: name 'df' is not defined

To generate pandas data frames:

In [15]:
f = 'Lottery ~ Literacy * Wealth'
y,X = patsy.dmatrices(f, df, return_type='dataframe')
print(y[:5])
print(X[:5])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-232-d9fd5a15051e> in <module>()
      1 f = 'Lottery ~ Literacy * Wealth'
----> 2 y,X = patsy.dmatrices(f, df, return_type='dataframe')
      3 print(y[:5])
      4 print(X[:5])

NameError: name 'df' is not defined
In [16]:
print(sm.OLS(y, X).fit().summary())
                            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:                Wed, 27 Apr 2016   Prob (F-statistic):           1.25e-23
Time:                        01:52:29   Log-Likelihood:                -68.470
No. Observations:                  50   AIC:                             140.9
Df Residuals:                      48   BIC:                             144.8
Df Model:                           1
Covariance Type:            nonrobust
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
const          5.2426      0.271     19.370      0.000         4.698     5.787
x1             0.4349      0.023     18.647      0.000         0.388     0.482
==============================================================================
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
==============================================================================

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