Logo

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-323-0b450e8cdfce> in <module>()
----> 1 dta = sm.datasets.get_rdataset("Guerry", "HistData", cache=True)

/build/buildd/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/buildd/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/buildd/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)
    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>
In [7]:
df = dta.data[['Lottery', 'Literacy', 'Wealth', 'Region']].dropna()
df.head()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-324-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)
   1940                 return self[name]
   1941             raise AttributeError("'%s' object has no attribute '%s'" %
-> 1942                                  (type(self).__name__, name))
   1943 
   1944     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-325-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-326-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-327-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-328-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-329-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-330-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-331-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-332-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.103
Model:                            OLS   Adj. R-squared:                  0.084
Method:                 Least Squares   F-statistic:                     5.578
Date:                Wed, 24 Dec 2014   Prob (F-statistic):           0.000285
Time:                        13:10:04   Log-Likelihood:                -1323.8
No. Observations:                 200   AIC:                             2658.
Df Residuals:                     195   BIC:                             2674.
Df Model:                           4
Covariance Type:            nonrobust
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
const        101.8655     13.073      7.792      0.000        76.084   127.647
x1            -0.4142      1.155     -0.359      0.720        -2.692     1.864
x2             3.8872      1.159      3.355      0.001         1.602     6.172
x3             2.9217      1.115      2.619      0.010         0.722     5.122
x4            -1.5714      1.131     -1.390      0.166        -3.801     0.658
==============================================================================
Omnibus:                       39.261   Durbin-Watson:                   2.115
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               58.584
Skew:                           1.326   Prob(JB):                     1.90e-13
Kurtosis:                       3.021   Cond. No.                         12.4
==============================================================================

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

This Page