-
Notifications
You must be signed in to change notification settings - Fork 28
/
contrasts.py
265 lines (158 loc) · 9.23 KB
/
contrasts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=3>
# Contrasts Overview
# <codecell>
import statsmodels.api as sm
# <markdowncell>
# This document is based heavily on this excellent resource from UCLA http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm
# <rawcell>
# 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.
# <headingcell level=4>
# Example Data
# <codecell>
import pandas
url = 'http://www.ats.ucla.edu/stat/data/hsb2.csv'
hsb2 = pandas.read_table(url, delimiter=",")
# <codecell>
hsb2.head(10)
# <rawcell>
# 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)).
# <codecell>
hsb2.groupby('race')['write'].mean()
# <headingcell level=4>
# Treatment (Dummy) Coding
# <rawcell>
# 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
# <codecell>
from patsy.contrasts import Treatment
levels = [1,2,3,4]
contrast = Treatment(reference=0).code_without_intercept(levels)
print contrast.matrix
# <rawcell>
# 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.
# <codecell>
hsb2.race.head(10)
# <codecell>
print contrast.matrix[hsb2.race-1, :][:20]
# <codecell>
sm.categorical(hsb2.race.values)
# <rawcell>
# 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
# <codecell>
from statsmodels.formula.api import ols
mod = ols("write ~ C(race, Treatment)", data=hsb2)
res = mod.fit()
print res.summary()
# <rawcell>
# We explicitly gave the contrast for race; however, since Treatment is the default, we could have omitted this.
# <headingcell level=3>
# Simple Coding
# <rawcell>
# 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
# <codecell>
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]))
# <codecell>
hsb2.groupby('race')['write'].mean().mean()
# <codecell>
contrast = Simple().code_without_intercept(levels)
print contrast.matrix
# <codecell>
mod = ols("write ~ C(race, Simple)", data=hsb2)
res = mod.fit()
print res.summary()
# <headingcell level=3>
# Sum (Deviation) Coding
# <rawcell>
# 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.
# <codecell>
from patsy.contrasts import Sum
contrast = Sum().code_without_intercept(levels)
print contrast.matrix
# <codecell>
mod = ols("write ~ C(race, Sum)", data=hsb2)
res = mod.fit()
print res.summary()
# <rawcell>
# 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.
# <codecell>
hsb2.groupby('race')['write'].mean().mean()
# <headingcell level=3>
# Backward Difference Coding
# <rawcell>
# 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.
# <codecell>
from patsy.contrasts import Diff
contrast = Diff().code_without_intercept(levels)
print contrast.matrix
# <codecell>
mod = ols("write ~ C(race, Diff)", data=hsb2)
res = mod.fit()
print res.summary()
# <rawcell>
# For example, here the coefficient on level 1 is the mean of `write` at level 2 compared with the mean at level 1. Ie.,
# <codecell>
res.params["C(race, Diff)[D.1]"]
hsb2.groupby('race').mean()["write"][2] - \
hsb2.groupby('race').mean()["write"][1]
# <headingcell level=3>
# Helmert Coding
# <rawcell>
# 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:
# <codecell>
from patsy.contrasts import Helmert
contrast = Helmert().code_without_intercept(levels)
print contrast.matrix
# <codecell>
mod = ols("write ~ C(race, Helmert)", data=hsb2)
res = mod.fit()
print res.summary()
# <rawcell>
# 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
# <codecell>
grouped = hsb2.groupby('race')
grouped.mean()["write"][4] - grouped.mean()["write"][:3].mean()
# <rawcell>
# 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.
# <codecell>
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())
# <headingcell level=3>
# Orthogonal Polynomial Coding
# <rawcell>
# 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`.
# <codecell>
hsb2['readcat'] = pandas.cut(hsb2.read, bins=3)
hsb2.groupby('readcat').mean()['write']
# <codecell>
from patsy.contrasts import Poly
levels = hsb2.readcat.unique().tolist()
contrast = Poly().code_without_intercept(levels)
print contrast.matrix
# <codecell>
mod = ols("write ~ C(readcat, Poly)", data=hsb2)
res = mod.fit()
print res.summary()
# <rawcell>
# As you can see, readcat has a significant linear effect on the dependent variable `write` but not a significant quadratic or cubic effect.