Logo

Contrasts OverviewΒΆ

Link to Notebook GitHub

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

This document is based heavily on this excellent resource from UCLA http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm

A categorical variable of K categories, or levels, usually enters a regression as a sequence of K-1 dummy variables. This amounts to a linear hypothesis on the level means. That is, each test statistic for these variables amounts to testing whether the mean for that level is statistically significantly different from the mean of the base category. This dummy coding is called Treatment coding in R parlance, and we will follow this convention. There are, however, different coding methods that amount to different sets of linear hypotheses.

In fact, the dummy coding is not technically a contrast coding. This is because the dummy variables add to one and are not functionally independent of the model's intercept. On the other hand, a set of contrasts for a categorical variable with k levels is a set of k-1 functionally independent linear combinations of the factor level means that are also independent of the sum of the dummy variables. The dummy coding isn't wrong per se. It captures all of the coefficients, but it complicates matters when the model assumes independence of the coefficients such as in ANOVA. Linear regression models do not assume independence of the coefficients and thus dummy coding is often the only coding that is taught in this context.

To have a look at the contrast matrices in Patsy, we will use data from UCLA ATS. First let's load the data.

Example Data

In [2]:
import pandas as pd
url = 'http://www.ats.ucla.edu/stat/data/hsb2.csv'
hsb2 = pd.read_table(url, delimiter=",")
---------------------------------------------------------------------------
URLError                                  Traceback (most recent call last)
<ipython-input-130-5629a4d06151> in <module>()
      1 import pandas as pd
      2 url = 'http://www.ats.ucla.edu/stat/data/hsb2.csv'
----> 3 hsb2 = pd.read_table(url, delimiter=",")

/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, float_precision, nrows, iterator, chunksize, verbose, encoding, squeeze, mangle_dupe_cols, tupleize_cols, infer_datetime_format, skip_blank_lines)
    463                     skip_blank_lines=skip_blank_lines)
    464 
--> 465         return _read(filepath_or_buffer, kwds)
    466 
    467     parser_f.__name__ = name

/usr/lib/python2.7/dist-packages/pandas/io/parsers.pyc in _read(filepath_or_buffer, kwds)
    227 
    228     filepath_or_buffer, _ = get_filepath_or_buffer(filepath_or_buffer,
--> 229                                                    encoding)
    230 
    231     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, 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 http_open(self, req)
   1225 
   1226     def http_open(self, req):
-> 1227         return self.do_open(httplib.HTTPConnection, req)
   1228 
   1229     http_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 [3]:
hsb2.head(10)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-131-de7a77e8eee0> in <module>()
----> 1 hsb2.head(10)

NameError: name 'hsb2' is not defined

It will be instructive to look at the mean of the dependent variable, write, for each level of race ((1 = Hispanic, 2 = Asian, 3 = African American and 4 = Caucasian)).

In [4]:
hsb2.groupby('race')['write'].mean()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-132-6fcbdca7af3c> in <module>()
----> 1 hsb2.groupby('race')['write'].mean()

NameError: name 'hsb2' is not defined

Treatment (Dummy) Coding

Dummy coding is likely the most well known coding scheme. It compares each level of the categorical variable to a base reference level. The base reference level is the value of the intercept. It is the default contrast in Patsy for unordered categorical factors. The Treatment contrast matrix for race would be

In [5]:
from patsy.contrasts import Treatment
levels = [1,2,3,4]
contrast = Treatment(reference=0).code_without_intercept(levels)
print(contrast.matrix)
[[ 0.  0.  0.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]

Here we used reference=0, which implies that the first level, Hispanic, is the reference category against which the other level effects are measured. As mentioned above, the columns do not sum to zero and are thus not independent of the intercept. To be explicit, let's look at how this would encode the race variable.

In [6]:
hsb2.race.head(10)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-134-d0c7690f6d8e> in <module>()
----> 1 hsb2.race.head(10)

NameError: name 'hsb2' is not defined
In [7]:
print(contrast.matrix[hsb2.race-1, :][:20])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-135-4232c81f1f7a> in <module>()
----> 1 print(contrast.matrix[hsb2.race-1, :][:20])

NameError: name 'hsb2' is not defined
In [8]:
sm.categorical(hsb2.race.values)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-136-3f329f3c5b26> in <module>()
----> 1 sm.categorical(hsb2.race.values)

NameError: name 'hsb2' is not defined

This is a bit of a trick, as the race category conveniently maps to zero-based indices. If it does not, this conversion happens under the hood, so this won't work in general but nonetheless is a useful exercise to fix ideas. The below illustrates the output using the three contrasts above

In [9]:
from statsmodels.formula.api import ols
mod = ols("write ~ C(race, Treatment)", data=hsb2)
res = mod.fit()
print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-137-3392279797aa> in <module>()
      1 from statsmodels.formula.api import ols
----> 2 mod = ols("write ~ C(race, Treatment)", data=hsb2)
      3 res = mod.fit()
      4 print(res.summary())

NameError: name 'hsb2' is not defined

We explicitly gave the contrast for race; however, since Treatment is the default, we could have omitted this.

Simple Coding

Like Treatment Coding, Simple Coding compares each level to a fixed reference level. However, with simple coding, the intercept is the grand mean of all the levels of the factors. Patsy doesn't have the Simple contrast included, but you can easily define your own contrasts. To do so, write a class that contains a code_with_intercept and a code_without_intercept method that returns a patsy.contrast.ContrastMatrix instance

In [10]:
from patsy.contrasts import ContrastMatrix

def _name_levels(prefix, levels):
    return ["[%s%s]" % (prefix, level) for level in levels]

class Simple(object):
    def _simple_contrast(self, levels):
        nlevels = len(levels)
        contr = -1./nlevels * np.ones((nlevels, nlevels-1))
        contr[1:][np.diag_indices(nlevels-1)] = (nlevels-1.)/nlevels
        return contr

    def code_with_intercept(self, levels):
        contrast = np.column_stack((np.ones(len(levels)),
                                    self._simple_contrast(levels)))
        return ContrastMatrix(contrast, _name_levels("Simp.", levels))

    def code_without_intercept(self, levels):
        contrast = self._simple_contrast(levels)
        return ContrastMatrix(contrast, _name_levels("Simp.", levels[:-1]))
In [11]:
hsb2.groupby('race')['write'].mean().mean()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-139-05e782082dc3> in <module>()
----> 1 hsb2.groupby('race')['write'].mean().mean()

NameError: name 'hsb2' is not defined
In [12]:
contrast = Simple().code_without_intercept(levels)
print(contrast.matrix)
[[-0.25 -0.25 -0.25]
 [ 0.75 -0.25 -0.25]
 [-0.25  0.75 -0.25]
 [-0.25 -0.25  0.75]]

In [13]:
mod = ols("write ~ C(race, Simple)", data=hsb2)
res = mod.fit()
print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-141-850aff9ee781> in <module>()
----> 1 mod = ols("write ~ C(race, Simple)", data=hsb2)
      2 res = mod.fit()
      3 print(res.summary())

NameError: name 'hsb2' is not defined

Sum (Deviation) Coding

Sum coding compares the mean of the dependent variable for a given level to the overall mean of the dependent variable over all the levels. That is, it uses contrasts between each of the first k-1 levels and level k In this example, level 1 is compared to all the others, level 2 to all the others, and level 3 to all the others.

In [14]:
from patsy.contrasts import Sum
contrast = Sum().code_without_intercept(levels)
print(contrast.matrix)
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]
 [-1. -1. -1.]]

In [15]:
mod = ols("write ~ C(race, Sum)", data=hsb2)
res = mod.fit()
print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-143-327c496e007a> in <module>()
----> 1 mod = ols("write ~ C(race, Sum)", data=hsb2)
      2 res = mod.fit()
      3 print(res.summary())

NameError: name 'hsb2' is not defined

This corresponds to a parameterization that forces all the coefficients to sum to zero. Notice that the intercept here is the grand mean where the grand mean is the mean of means of the dependent variable by each level.

In [16]:
hsb2.groupby('race')['write'].mean().mean()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-144-05e782082dc3> in <module>()
----> 1 hsb2.groupby('race')['write'].mean().mean()

NameError: name 'hsb2' is not defined

Backward Difference Coding

In backward difference coding, the mean of the dependent variable for a level is compared with the mean of the dependent variable for the prior level. This type of coding may be useful for a nominal or an ordinal variable.

In [17]:
from patsy.contrasts import Diff
contrast = Diff().code_without_intercept(levels)
print(contrast.matrix)
[[-0.75 -0.5  -0.25]
 [ 0.25 -0.5  -0.25]
 [ 0.25  0.5  -0.25]
 [ 0.25  0.5   0.75]]

In [18]:
mod = ols("write ~ C(race, Diff)", data=hsb2)
res = mod.fit()
print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-146-c356f47654a2> in <module>()
----> 1 mod = ols("write ~ C(race, Diff)", data=hsb2)
      2 res = mod.fit()
      3 print(res.summary())

NameError: name 'hsb2' is not defined

For example, here the coefficient on level 1 is the mean of write at level 2 compared with the mean at level 1. Ie.,

In [19]:
res.params["C(race, Diff)[D.1]"]
hsb2.groupby('race').mean()["write"][2] - \
     hsb2.groupby('race').mean()["write"][1]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-147-e1e60ba22026> in <module>()
----> 1 res.params["C(race, Diff)[D.1]"]
      2 hsb2.groupby('race').mean()["write"][2] -      hsb2.groupby('race').mean()["write"][1]

/usr/lib/python2.7/dist-packages/pandas/core/series.pyc in __getitem__(self, key)
    506     def __getitem__(self, key):
    507         try:
--> 508             result = self.index.get_value(self, key)
    509 
    510             if not np.isscalar(result):

/usr/lib/python2.7/dist-packages/pandas/core/index.pyc in get_value(self, series, key)
   1429                     raise InvalidIndexError(key)
   1430                 else:
-> 1431                     raise e1
   1432             except Exception:  # pragma: no cover
   1433                 raise e1

KeyError: 'C(race, Diff)[D.1]'

Helmert Coding

Our version of Helmert coding is sometimes referred to as Reverse Helmert Coding. The mean of the dependent variable for a level is compared to the mean of the dependent variable over all previous levels. Hence, the name 'reverse' being sometimes applied to differentiate from forward Helmert coding. This comparison does not make much sense for a nominal variable such as race, but we would use the Helmert contrast like so:

In [20]:
from patsy.contrasts import Helmert
contrast = Helmert().code_without_intercept(levels)
print(contrast.matrix)
[[-1. -1. -1.]
 [ 1. -1. -1.]
 [ 0.  2. -1.]
 [ 0.  0.  3.]]

In [21]:
mod = ols("write ~ C(race, Helmert)", data=hsb2)
res = mod.fit()
print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-149-06401510608d> in <module>()
----> 1 mod = ols("write ~ C(race, Helmert)", data=hsb2)
      2 res = mod.fit()
      3 print(res.summary())

NameError: name 'hsb2' is not defined

To illustrate, the comparison on level 4 is the mean of the dependent variable at the previous three levels taken from the mean at level 4

In [22]:
grouped = hsb2.groupby('race')
grouped.mean()["write"][4] - grouped.mean()["write"][:3].mean()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-150-668c90a5ef42> in <module>()
----> 1 grouped = hsb2.groupby('race')
      2 grouped.mean()["write"][4] - grouped.mean()["write"][:3].mean()

NameError: name 'hsb2' is not defined

As you can see, these are only equal up to a constant. Other versions of the Helmert contrast give the actual difference in means. Regardless, the hypothesis tests are the same.

In [23]:
k = 4
1./k * (grouped.mean()["write"][k] - grouped.mean()["write"][:k-1].mean())
k = 3
1./k * (grouped.mean()["write"][k] - grouped.mean()["write"][:k-1].mean())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-151-03b13aa43b4c> in <module>()
      1 k = 4
----> 2 1./k * (grouped.mean()["write"][k] - grouped.mean()["write"][:k-1].mean())
      3 k = 3
      4 1./k * (grouped.mean()["write"][k] - grouped.mean()["write"][:k-1].mean())

NameError: name 'grouped' is not defined

Orthogonal Polynomial Coding

The coefficients taken on by polynomial coding for k=4 levels are the linear, quadratic, and cubic trends in the categorical variable. The categorical variable here is assumed to be represented by an underlying, equally spaced numeric variable. Therefore, this type of encoding is used only for ordered categorical variables with equal spacing. In general, the polynomial contrast produces polynomials of order k-1. Since race is not an ordered factor variable let's use read as an example. First we need to create an ordered categorical from read.

In [24]:
hsb2['readcat'] = pd.cut(hsb2.read, bins=3)
hsb2.groupby('readcat').mean()['write']
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-152-280cfaa4de3e> in <module>()
----> 1 hsb2['readcat'] = pd.cut(hsb2.read, bins=3)
      2 hsb2.groupby('readcat').mean()['write']

NameError: name 'hsb2' is not defined
In [25]:
from patsy.contrasts import Poly
levels = hsb2.readcat.unique().tolist()
contrast = Poly().code_without_intercept(levels)
print(contrast.matrix)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-153-ab27ccaad41a> in <module>()
      1 from patsy.contrasts import Poly
----> 2 levels = hsb2.readcat.unique().tolist()
      3 contrast = Poly().code_without_intercept(levels)
      4 print(contrast.matrix)

NameError: name 'hsb2' is not defined
In [26]:
mod = ols("write ~ C(readcat, Poly)", data=hsb2)
res = mod.fit()
print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-154-57d07f3aa5e4> in <module>()
----> 1 mod = ols("write ~ C(readcat, Poly)", data=hsb2)
      2 res = mod.fit()
      3 print(res.summary())

NameError: name 'hsb2' is not defined

As you can see, readcat has a significant linear effect on the dependent variable write but not a significant quadratic or cubic effect.

This Page