Patsy: Contrast Coding Systems for categorical variables

Note

This document is based heavily on this excellent resource from UCLA.

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 [1]: import pandas

In [2]: url = 'https://stats.idre.ucla.edu/stat/data/hsb2.csv'

In [3]: hsb2 = pandas.read_csv(url)
---------------------------------------------------------------------------
gaierror                                  Traceback (most recent call last)
/usr/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1316                 h.request(req.get_method(), req.selector, req.data, headers,
-> 1317                           encode_chunked=req.has_header('Transfer-encoding'))
   1318             except OSError as err: # timeout error

/usr/lib/python3.7/http/client.py in request(self, method, url, body, headers, encode_chunked)
   1228         """Send a complete request to the server."""
-> 1229         self._send_request(method, url, body, headers, encode_chunked)
   1230 

/usr/lib/python3.7/http/client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1274             body = _encode(body, 'body')
-> 1275         self.endheaders(body, encode_chunked=encode_chunked)
   1276 

/usr/lib/python3.7/http/client.py in endheaders(self, message_body, encode_chunked)
   1223             raise CannotSendHeader()
-> 1224         self._send_output(message_body, encode_chunked=encode_chunked)
   1225 

/usr/lib/python3.7/http/client.py in _send_output(self, message_body, encode_chunked)
   1015         del self._buffer[:]
-> 1016         self.send(msg)
   1017 

/usr/lib/python3.7/http/client.py in send(self, data)
    955             if self.auto_open:
--> 956                 self.connect()
    957             else:

/usr/lib/python3.7/http/client.py in connect(self)
   1383 
-> 1384             super().connect()
   1385 

/usr/lib/python3.7/http/client.py in connect(self)
    927         self.sock = self._create_connection(
--> 928             (self.host,self.port), self.timeout, self.source_address)
    929         self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

/usr/lib/python3.7/socket.py in create_connection(address, timeout, source_address)
    706     err = None
--> 707     for res in getaddrinfo(host, port, 0, SOCK_STREAM):
    708         af, socktype, proto, canonname, sa = res

/usr/lib/python3.7/socket.py in getaddrinfo(host, port, family, type, proto, flags)
    747     addrlist = []
--> 748     for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    749         af, socktype, proto, canonname, sa = res

gaierror: [Errno -3] Temporary failure in name resolution

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)
<ipython-input-3-4735750ff492> in <module>()
----> 1 hsb2 = pandas.read_csv(url)

/usr/lib/python3/dist-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, doublequote, delim_whitespace, low_memory, memory_map, float_precision)
    676                     skip_blank_lines=skip_blank_lines)
    677 
--> 678         return _read(filepath_or_buffer, kwds)
    679 
    680     parser_f.__name__ = name

/usr/lib/python3/dist-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
    422     compression = _infer_compression(filepath_or_buffer, compression)
    423     filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer(
--> 424         filepath_or_buffer, encoding, compression)
    425     kwds['compression'] = compression
    426 

/usr/lib/python3/dist-packages/pandas/io/common.py in get_filepath_or_buffer(filepath_or_buffer, encoding, compression, mode)
    193 
    194     if _is_url(filepath_or_buffer):
--> 195         req = _urlopen(filepath_or_buffer)
    196         content_encoding = req.headers.get('Content-Encoding', None)
    197         if content_encoding == 'gzip':

/usr/lib/python3.7/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223 
    224 def install_opener(opener):

/usr/lib/python3.7/urllib/request.py in open(self, fullurl, data, timeout)
    523             req = meth(req)
    524 
--> 525         response = self._open(req, data)
    526 
    527         # post-process response

/usr/lib/python3.7/urllib/request.py in _open(self, req, data)
    541         protocol = req.type
    542         result = self._call_chain(self.handle_open, protocol, protocol +
--> 543                                   '_open', req)
    544         if result:
    545             return result

/usr/lib/python3.7/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
    501         for handler in handlers:
    502             func = getattr(handler, meth_name)
--> 503             result = func(*args)
    504             if result is not None:
    505                 return result

/usr/lib/python3.7/urllib/request.py in https_open(self, req)
   1358         def https_open(self, req):
   1359             return self.do_open(http.client.HTTPSConnection, req,
-> 1360                 context=self._context, check_hostname=self._check_hostname)
   1361 
   1362         https_request = AbstractHTTPHandler.do_request_

/usr/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1317                           encode_chunked=req.has_header('Transfer-encoding'))
   1318             except OSError as err: # timeout error
-> 1319                 raise URLError(err)
   1320             r = h.getresponse()
   1321         except:

URLError: <urlopen error [Errno -3] Temporary failure in name resolution>

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

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 [4]: from patsy.contrasts import Treatment

In [5]: levels = [1,2,3,4]

In [6]: contrast = Treatment(reference=0).code_without_intercept(levels)

In [7]: 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 [8]: contrast.matrix[hsb2.race-1, :][:20]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-eae0b0d66a00> in <module>()
----> 1 contrast.matrix[hsb2.race-1, :][:20]

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

In [10]: mod = ols("write ~ C(race, Treatment)", data=hsb2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-3bdf176f3042> in <module>()
----> 1 mod = ols("write ~ C(race, Treatment)", data=hsb2)

NameError: name 'hsb2' is not defined

In [11]: res = mod.fit()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-fa3ccf53f431> in <module>()
----> 1 res = mod.fit()

NameError: name 'mod' is not defined

In [12]: print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-ba064a039ab1> in <module>()
----> 1 print(res.summary())

NameError: name 'res' 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. See User-Defined Coding for how to implement the Simple contrast.

In [13]: contrast = Simple().code_without_intercept(levels)

In [14]: 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 [15]: mod = ols("write ~ C(race, Simple)", data=hsb2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-15-6ce0487a5b61> in <module>()
----> 1 mod = ols("write ~ C(race, Simple)", data=hsb2)

NameError: name 'hsb2' is not defined

In [16]: res = mod.fit()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-fa3ccf53f431> in <module>()
----> 1 res = mod.fit()

NameError: name 'mod' is not defined

In [17]: print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-17-ba064a039ab1> in <module>()
----> 1 print(res.summary())

NameError: name 'res' 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 [18]: from patsy.contrasts import Sum

In [19]: contrast = Sum().code_without_intercept(levels)

In [20]: print(contrast.matrix)
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]
 [-1. -1. -1.]]

In [21]: mod = ols("write ~ C(race, Sum)", data=hsb2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-21-fcaa6b96ccfd> in <module>()
----> 1 mod = ols("write ~ C(race, Sum)", data=hsb2)

NameError: name 'hsb2' is not defined

In [22]: res = mod.fit()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-22-fa3ccf53f431> in <module>()
----> 1 res = mod.fit()

NameError: name 'mod' is not defined

In [23]: print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-ba064a039ab1> in <module>()
----> 1 print(res.summary())

NameError: name 'res' is not defined

This correspons 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 [24]: hsb2.groupby('race')['write'].mean().mean()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-24-b21947de62cb> 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 [25]: from patsy.contrasts import Diff

In [26]: contrast = Diff().code_without_intercept(levels)

In [27]: 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 [28]: mod = ols("write ~ C(race, Diff)", data=hsb2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-28-e28888f23177> in <module>()
----> 1 mod = ols("write ~ C(race, Diff)", data=hsb2)

NameError: name 'hsb2' is not defined

In [29]: res = mod.fit()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-29-fa3ccf53f431> in <module>()
----> 1 res = mod.fit()

NameError: name 'mod' is not defined

In [30]: print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-30-ba064a039ab1> in <module>()
----> 1 print(res.summary())

NameError: name 'res' 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 [31]: res.params["C(race, Diff)[D.1]"]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-31-f27d60ed9ed4> in <module>()
----> 1 res.params["C(race, Diff)[D.1]"]

NameError: name 'res' is not defined

In [32]: hsb2.groupby('race').mean()["write"][2] - \
   ....:      hsb2.groupby('race').mean()["write"][1]
   ....: 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-32-a4a72e9facd2> in <module>()
----> 1 hsb2.groupby('race').mean()["write"][2] -      hsb2.groupby('race').mean()["write"][1]

NameError: name 'hsb2' is not defined

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 [33]: from patsy.contrasts import Helmert

In [34]: contrast = Helmert().code_without_intercept(levels)

In [35]: print(contrast.matrix)
[[-1. -1. -1.]
 [ 1. -1. -1.]
 [ 0.  2. -1.]
 [ 0.  0.  3.]]

In [36]: mod = ols("write ~ C(race, Helmert)", data=hsb2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-36-c991b20b1c77> in <module>()
----> 1 mod = ols("write ~ C(race, Helmert)", data=hsb2)

NameError: name 'hsb2' is not defined

In [37]: res = mod.fit()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-37-fa3ccf53f431> in <module>()
----> 1 res = mod.fit()

NameError: name 'mod' is not defined

In [38]: print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-38-ba064a039ab1> in <module>()
----> 1 print(res.summary())

NameError: name 'res' 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 [39]: grouped = hsb2.groupby('race')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-39-717e908ca802> in <module>()
----> 1 grouped = hsb2.groupby('race')

NameError: name 'hsb2' is not defined

In [40]: grouped.mean()["write"][4] - grouped.mean()["write"][:3].mean()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-40-a29d75116d4c> in <module>()
----> 1 grouped.mean()["write"][4] - grouped.mean()["write"][:3].mean()

NameError: name 'grouped' 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 [41]: k = 4

In [42]: 1./k * (grouped.mean()["write"][k] - grouped.mean()["write"][:k-1].mean())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-42-8956699e0a60> in <module>()
----> 1 1./k * (grouped.mean()["write"][k] - grouped.mean()["write"][:k-1].mean())

NameError: name 'grouped' is not defined

In [43]: k = 3

In [44]: 1./k * (grouped.mean()["write"][k] - grouped.mean()["write"][:k-1].mean())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-44-8956699e0a60> in <module>()
----> 1 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 [45]: _, bins = np.histogram(hsb2.read, 3)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-45-55fa0c232e59> in <module>()
----> 1 _, bins = np.histogram(hsb2.read, 3)

NameError: name 'hsb2' is not defined

In [46]: try: # requires numpy master
   ....:     readcat = np.digitize(hsb2.read, bins, True)
   ....: except:
   ....:     readcat = np.digitize(hsb2.read, bins)
   ....: 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-46-f9e0ed2fa528> in <module>()
      1 try: # requires numpy master
----> 2     readcat = np.digitize(hsb2.read, bins, True)
      3 except:

NameError: name 'hsb2' is not defined

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-46-f9e0ed2fa528> in <module>()
      2     readcat = np.digitize(hsb2.read, bins, True)
      3 except:
----> 4     readcat = np.digitize(hsb2.read, bins)
      5 

NameError: name 'hsb2' is not defined

In [47]: hsb2['readcat'] = readcat
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-47-e199b94a103d> in <module>()
----> 1 hsb2['readcat'] = readcat

NameError: name 'readcat' is not defined

In [48]: hsb2.groupby('readcat').mean()['write']
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-48-97d196c364b0> in <module>()
----> 1 hsb2.groupby('readcat').mean()['write']

NameError: name 'hsb2' is not defined
In [49]: from patsy.contrasts import Poly

In [50]: levels = hsb2.readcat.unique().tolist()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-50-4d972b7909b9> in <module>()
----> 1 levels = hsb2.readcat.unique().tolist()

NameError: name 'hsb2' is not defined

In [51]: contrast = Poly().code_without_intercept(levels)

In [52]: print(contrast.matrix)
[[-0.6708  0.5    -0.2236]
 [-0.2236 -0.5     0.6708]
 [ 0.2236 -0.5    -0.6708]
 [ 0.6708  0.5     0.2236]]

In [53]: mod = ols("write ~ C(readcat, Poly)", data=hsb2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-53-e9324312786f> in <module>()
----> 1 mod = ols("write ~ C(readcat, Poly)", data=hsb2)

NameError: name 'hsb2' is not defined

In [54]: res = mod.fit()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-54-fa3ccf53f431> in <module>()
----> 1 res = mod.fit()

NameError: name 'mod' is not defined

In [55]: print(res.summary())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-55-ba064a039ab1> in <module>()
----> 1 print(res.summary())

NameError: name 'res' 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.

User-Defined Coding

If you want to use your own coding, you must do so by writing a coding class that contains a code_with_intercept and a code_without_intercept method that return a patsy.contrast.ContrastMatrix instance.

In [56]: from patsy.contrasts import ContrastMatrix

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

In [58]: 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
   ....: 

In [59]: 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))
   ....: