{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Contrasts Overview" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:32.647611Z", "iopub.status.busy": "2021-02-02T06:56:32.646316Z", "iopub.status.idle": "2021-02-02T06:56:35.557269Z", "shell.execute_reply": "2021-02-02T06:56:35.557997Z" } }, "outputs": [], "source": [ "import numpy as np\n", "import statsmodels.api as sm" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This document is based heavily on this excellent resource from UCLA http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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.\n", "\n", "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 is not 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.\n", "\n", "To have a look at the contrast matrices in Patsy, we will use data from UCLA ATS. First let's load the data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Example Data" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:35.573790Z", "iopub.status.busy": "2021-02-02T06:56:35.572961Z", "iopub.status.idle": "2021-02-02T06:56:35.867178Z", "shell.execute_reply": "2021-02-02T06:56:35.868479Z" } }, "outputs": [], "source": [ "import pandas as pd\n", "url = 'https://stats.idre.ucla.edu/stat/data/hsb2.csv'\n", "hsb2 = pd.read_table(url, delimiter=\",\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:35.881101Z", "iopub.status.busy": "2021-02-02T06:56:35.872579Z", "iopub.status.idle": "2021-02-02T06:56:35.966214Z", "shell.execute_reply": "2021-02-02T06:56:35.966837Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
idfemaleracesesschtypprogreadwritemathsciencesocst
070041115752414757
1121142136859536361
286043114433545831
3141043136344475356
4172042124752575361
5113042124452516361
650032115059425361
711012123446453936
884042116357545851
948032125755525051
\n", "
" ], "text/plain": [ " id female race ses schtyp prog read write math science socst\n", "0 70 0 4 1 1 1 57 52 41 47 57\n", "1 121 1 4 2 1 3 68 59 53 63 61\n", "2 86 0 4 3 1 1 44 33 54 58 31\n", "3 141 0 4 3 1 3 63 44 47 53 56\n", "4 172 0 4 2 1 2 47 52 57 53 61\n", "5 113 0 4 2 1 2 44 52 51 63 61\n", "6 50 0 3 2 1 1 50 59 42 53 61\n", "7 11 0 1 2 1 2 34 46 45 39 36\n", "8 84 0 4 2 1 1 63 57 54 58 51\n", "9 48 0 3 2 1 2 57 55 52 50 51" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hsb2.head(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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))." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:35.981727Z", "iopub.status.busy": "2021-02-02T06:56:35.980935Z", "iopub.status.idle": "2021-02-02T06:56:35.991452Z", "shell.execute_reply": "2021-02-02T06:56:35.992119Z" } }, "outputs": [ { "data": { "text/plain": [ "race\n", "1 46.458333\n", "2 58.000000\n", "3 48.200000\n", "4 54.055172\n", "Name: write, dtype: float64" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hsb2.groupby('race')['write'].mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Treatment (Dummy) Coding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:35.999072Z", "iopub.status.busy": "2021-02-02T06:56:35.998224Z", "iopub.status.idle": "2021-02-02T06:56:36.011120Z", "shell.execute_reply": "2021-02-02T06:56:36.011793Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0. 0. 0.]\n", " [1. 0. 0.]\n", " [0. 1. 0.]\n", " [0. 0. 1.]]\n" ] } ], "source": [ "from patsy.contrasts import Treatment\n", "levels = [1,2,3,4]\n", "contrast = Treatment(reference=0).code_without_intercept(levels)\n", "print(contrast.matrix)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.018516Z", "iopub.status.busy": "2021-02-02T06:56:36.017745Z", "iopub.status.idle": "2021-02-02T06:56:36.028456Z", "shell.execute_reply": "2021-02-02T06:56:36.029111Z" } }, "outputs": [ { "data": { "text/plain": [ "0 4\n", "1 4\n", "2 4\n", "3 4\n", "4 4\n", "5 4\n", "6 3\n", "7 1\n", "8 4\n", "9 3\n", "Name: race, dtype: int64" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hsb2.race.head(10)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.034639Z", "iopub.status.busy": "2021-02-02T06:56:36.033837Z", "iopub.status.idle": "2021-02-02T06:56:36.045137Z", "shell.execute_reply": "2021-02-02T06:56:36.045947Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 1. 0.]\n", " [0. 0. 0.]\n", " [0. 0. 1.]\n", " [0. 1. 0.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 1. 0.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]\n", " [0. 0. 1.]]\n" ] } ], "source": [ "print(contrast.matrix[hsb2.race-1, :][:20])" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.053293Z", "iopub.status.busy": "2021-02-02T06:56:36.052556Z", "iopub.status.idle": "2021-02-02T06:56:36.092117Z", "shell.execute_reply": "2021-02-02T06:56:36.092928Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
1234
00001
10001
20001
30001
40001
...............
1950100
1960001
1970001
1980001
1990001
\n", "

200 rows × 4 columns

\n", "
" ], "text/plain": [ " 1 2 3 4\n", "0 0 0 0 1\n", "1 0 0 0 1\n", "2 0 0 0 1\n", "3 0 0 0 1\n", "4 0 0 0 1\n", ".. .. .. .. ..\n", "195 0 1 0 0\n", "196 0 0 0 1\n", "197 0 0 0 1\n", "198 0 0 0 1\n", "199 0 0 0 1\n", "\n", "[200 rows x 4 columns]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.get_dummies(hsb2.race.values, drop_first=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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 will not work in general but nonetheless is a useful exercise to fix ideas. The below illustrates the output using the three contrasts above" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.096360Z", "iopub.status.busy": "2021-02-02T06:56:36.095621Z", "iopub.status.idle": "2021-02-02T06:56:36.180066Z", "shell.execute_reply": "2021-02-02T06:56:36.178887Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " OLS Regression Results \n", "==============================================================================\n", "Dep. Variable: write R-squared: 0.107\n", "Model: OLS Adj. R-squared: 0.093\n", "Method: Least Squares F-statistic: 7.833\n", "Date: Tue, 02 Feb 2021 Prob (F-statistic): 5.78e-05\n", "Time: 06:56:36 Log-Likelihood: -721.77\n", "No. Observations: 200 AIC: 1452.\n", "Df Residuals: 196 BIC: 1465.\n", "Df Model: 3 \n", "Covariance Type: nonrobust \n", "===========================================================================================\n", " coef std err t P>|t| [0.025 0.975]\n", "-------------------------------------------------------------------------------------------\n", "Intercept 46.4583 1.842 25.218 0.000 42.825 50.091\n", "C(race, Treatment)[T.2] 11.5417 3.286 3.512 0.001 5.061 18.022\n", "C(race, Treatment)[T.3] 1.7417 2.732 0.637 0.525 -3.647 7.131\n", "C(race, Treatment)[T.4] 7.5968 1.989 3.820 0.000 3.675 11.519\n", "==============================================================================\n", "Omnibus: 10.487 Durbin-Watson: 1.779\n", "Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031\n", "Skew: -0.551 Prob(JB): 0.00402\n", "Kurtosis: 2.670 Cond. No. 8.25\n", "==============================================================================\n", "\n", "Notes:\n", "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n" ] } ], "source": [ "from statsmodels.formula.api import ols\n", "mod = ols(\"write ~ C(race, Treatment)\", data=hsb2)\n", "res = mod.fit()\n", "print(res.summary())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We explicitly gave the contrast for race; however, since Treatment is the default, we could have omitted this." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simple Coding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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 does not 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" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.196197Z", "iopub.status.busy": "2021-02-02T06:56:36.195356Z", "iopub.status.idle": "2021-02-02T06:56:36.204942Z", "shell.execute_reply": "2021-02-02T06:56:36.206034Z" } }, "outputs": [], "source": [ "from patsy.contrasts import ContrastMatrix\n", "\n", "def _name_levels(prefix, levels):\n", " return [\"[%s%s]\" % (prefix, level) for level in levels]\n", "\n", "class Simple(object):\n", " def _simple_contrast(self, levels):\n", " nlevels = len(levels)\n", " contr = -1./nlevels * np.ones((nlevels, nlevels-1))\n", " contr[1:][np.diag_indices(nlevels-1)] = (nlevels-1.)/nlevels\n", " return contr\n", "\n", " def code_with_intercept(self, levels):\n", " contrast = np.column_stack((np.ones(len(levels)),\n", " self._simple_contrast(levels)))\n", " return ContrastMatrix(contrast, _name_levels(\"Simp.\", levels))\n", "\n", " def code_without_intercept(self, levels):\n", " contrast = self._simple_contrast(levels)\n", " return ContrastMatrix(contrast, _name_levels(\"Simp.\", levels[:-1]))" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.210566Z", "iopub.status.busy": "2021-02-02T06:56:36.209129Z", "iopub.status.idle": "2021-02-02T06:56:36.225735Z", "shell.execute_reply": "2021-02-02T06:56:36.226798Z" } }, "outputs": [ { "data": { "text/plain": [ "51.67837643678162" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hsb2.groupby('race')['write'].mean().mean()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.231913Z", "iopub.status.busy": "2021-02-02T06:56:36.230431Z", "iopub.status.idle": "2021-02-02T06:56:36.238677Z", "shell.execute_reply": "2021-02-02T06:56:36.239719Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-0.25 -0.25 -0.25]\n", " [ 0.75 -0.25 -0.25]\n", " [-0.25 0.75 -0.25]\n", " [-0.25 -0.25 0.75]]\n" ] } ], "source": [ "contrast = Simple().code_without_intercept(levels)\n", "print(contrast.matrix)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.244257Z", "iopub.status.busy": "2021-02-02T06:56:36.242756Z", "iopub.status.idle": "2021-02-02T06:56:36.313933Z", "shell.execute_reply": "2021-02-02T06:56:36.315060Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " OLS Regression Results \n", "==============================================================================\n", "Dep. Variable: write R-squared: 0.107\n", "Model: OLS Adj. R-squared: 0.093\n", "Method: Least Squares F-statistic: 7.833\n", "Date: Tue, 02 Feb 2021 Prob (F-statistic): 5.78e-05\n", "Time: 06:56:36 Log-Likelihood: -721.77\n", "No. Observations: 200 AIC: 1452.\n", "Df Residuals: 196 BIC: 1465.\n", "Df Model: 3 \n", "Covariance Type: nonrobust \n", "===========================================================================================\n", " coef std err t P>|t| [0.025 0.975]\n", "-------------------------------------------------------------------------------------------\n", "Intercept 51.6784 0.982 52.619 0.000 49.741 53.615\n", "C(race, Simple)[Simp.1] 11.5417 3.286 3.512 0.001 5.061 18.022\n", "C(race, Simple)[Simp.2] 1.7417 2.732 0.637 0.525 -3.647 7.131\n", "C(race, Simple)[Simp.3] 7.5968 1.989 3.820 0.000 3.675 11.519\n", "==============================================================================\n", "Omnibus: 10.487 Durbin-Watson: 1.779\n", "Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031\n", "Skew: -0.551 Prob(JB): 0.00402\n", "Kurtosis: 2.670 Cond. No. 7.03\n", "==============================================================================\n", "\n", "Notes:\n", "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n" ] } ], "source": [ "mod = ols(\"write ~ C(race, Simple)\", data=hsb2)\n", "res = mod.fit()\n", "print(res.summary())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sum (Deviation) Coding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.320249Z", "iopub.status.busy": "2021-02-02T06:56:36.318646Z", "iopub.status.idle": "2021-02-02T06:56:36.336558Z", "shell.execute_reply": "2021-02-02T06:56:36.337945Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1. 0. 0.]\n", " [ 0. 1. 0.]\n", " [ 0. 0. 1.]\n", " [-1. -1. -1.]]\n" ] } ], "source": [ "from patsy.contrasts import Sum\n", "contrast = Sum().code_without_intercept(levels)\n", "print(contrast.matrix)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.342654Z", "iopub.status.busy": "2021-02-02T06:56:36.341199Z", "iopub.status.idle": "2021-02-02T06:56:36.402319Z", "shell.execute_reply": "2021-02-02T06:56:36.401188Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " OLS Regression Results \n", "==============================================================================\n", "Dep. Variable: write R-squared: 0.107\n", "Model: OLS Adj. R-squared: 0.093\n", "Method: Least Squares F-statistic: 7.833\n", "Date: Tue, 02 Feb 2021 Prob (F-statistic): 5.78e-05\n", "Time: 06:56:36 Log-Likelihood: -721.77\n", "No. Observations: 200 AIC: 1452.\n", "Df Residuals: 196 BIC: 1465.\n", "Df Model: 3 \n", "Covariance Type: nonrobust \n", "=====================================================================================\n", " coef std err t P>|t| [0.025 0.975]\n", "-------------------------------------------------------------------------------------\n", "Intercept 51.6784 0.982 52.619 0.000 49.741 53.615\n", "C(race, Sum)[S.1] -5.2200 1.631 -3.200 0.002 -8.437 -2.003\n", "C(race, Sum)[S.2] 6.3216 2.160 2.926 0.004 2.061 10.582\n", "C(race, Sum)[S.3] -3.4784 1.732 -2.008 0.046 -6.895 -0.062\n", "==============================================================================\n", "Omnibus: 10.487 Durbin-Watson: 1.779\n", "Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031\n", "Skew: -0.551 Prob(JB): 0.00402\n", "Kurtosis: 2.670 Cond. No. 6.72\n", "==============================================================================\n", "\n", "Notes:\n", "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n" ] } ], "source": [ "mod = ols(\"write ~ C(race, Sum)\", data=hsb2)\n", "res = mod.fit()\n", "print(res.summary())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.409854Z", "iopub.status.busy": "2021-02-02T06:56:36.409060Z", "iopub.status.idle": "2021-02-02T06:56:36.424055Z", "shell.execute_reply": "2021-02-02T06:56:36.422910Z" } }, "outputs": [ { "data": { "text/plain": [ "51.67837643678162" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hsb2.groupby('race')['write'].mean().mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Backward Difference Coding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.431304Z", "iopub.status.busy": "2021-02-02T06:56:36.430509Z", "iopub.status.idle": "2021-02-02T06:56:36.435907Z", "shell.execute_reply": "2021-02-02T06:56:36.436523Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-0.75 -0.5 -0.25]\n", " [ 0.25 -0.5 -0.25]\n", " [ 0.25 0.5 -0.25]\n", " [ 0.25 0.5 0.75]]\n" ] } ], "source": [ "from patsy.contrasts import Diff\n", "contrast = Diff().code_without_intercept(levels)\n", "print(contrast.matrix)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.449623Z", "iopub.status.busy": "2021-02-02T06:56:36.448815Z", "iopub.status.idle": "2021-02-02T06:56:36.522591Z", "shell.execute_reply": "2021-02-02T06:56:36.523226Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " OLS Regression Results \n", "==============================================================================\n", "Dep. Variable: write R-squared: 0.107\n", "Model: OLS Adj. R-squared: 0.093\n", "Method: Least Squares F-statistic: 7.833\n", "Date: Tue, 02 Feb 2021 Prob (F-statistic): 5.78e-05\n", "Time: 06:56:36 Log-Likelihood: -721.77\n", "No. Observations: 200 AIC: 1452.\n", "Df Residuals: 196 BIC: 1465.\n", "Df Model: 3 \n", "Covariance Type: nonrobust \n", "======================================================================================\n", " coef std err t P>|t| [0.025 0.975]\n", "--------------------------------------------------------------------------------------\n", "Intercept 51.6784 0.982 52.619 0.000 49.741 53.615\n", "C(race, Diff)[D.1] 11.5417 3.286 3.512 0.001 5.061 18.022\n", "C(race, Diff)[D.2] -9.8000 3.388 -2.893 0.004 -16.481 -3.119\n", "C(race, Diff)[D.3] 5.8552 2.153 2.720 0.007 1.610 10.101\n", "==============================================================================\n", "Omnibus: 10.487 Durbin-Watson: 1.779\n", "Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031\n", "Skew: -0.551 Prob(JB): 0.00402\n", "Kurtosis: 2.670 Cond. No. 8.30\n", "==============================================================================\n", "\n", "Notes:\n", "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n" ] } ], "source": [ "mod = ols(\"write ~ C(race, Diff)\", data=hsb2)\n", "res = mod.fit()\n", "print(res.summary())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For example, here the coefficient on level 1 is the mean of `write` at level 2 compared with the mean at level 1. Ie.," ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.531402Z", "iopub.status.busy": "2021-02-02T06:56:36.530622Z", "iopub.status.idle": "2021-02-02T06:56:36.557490Z", "shell.execute_reply": "2021-02-02T06:56:36.558122Z" } }, "outputs": [ { "data": { "text/plain": [ "11.541666666666664" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "res.params[\"C(race, Diff)[D.1]\"]\n", "hsb2.groupby('race').mean()[\"write\"][2] - \\\n", " hsb2.groupby('race').mean()[\"write\"][1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Helmert Coding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.565415Z", "iopub.status.busy": "2021-02-02T06:56:36.563151Z", "iopub.status.idle": "2021-02-02T06:56:36.568538Z", "shell.execute_reply": "2021-02-02T06:56:36.569782Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-1. -1. -1.]\n", " [ 1. -1. -1.]\n", " [ 0. 2. -1.]\n", " [ 0. 0. 3.]]\n" ] } ], "source": [ "from patsy.contrasts import Helmert\n", "contrast = Helmert().code_without_intercept(levels)\n", "print(contrast.matrix)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.600789Z", "iopub.status.busy": "2021-02-02T06:56:36.599977Z", "iopub.status.idle": "2021-02-02T06:56:36.653349Z", "shell.execute_reply": "2021-02-02T06:56:36.654442Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " OLS Regression Results \n", "==============================================================================\n", "Dep. Variable: write R-squared: 0.107\n", "Model: OLS Adj. R-squared: 0.093\n", "Method: Least Squares F-statistic: 7.833\n", "Date: Tue, 02 Feb 2021 Prob (F-statistic): 5.78e-05\n", "Time: 06:56:36 Log-Likelihood: -721.77\n", "No. Observations: 200 AIC: 1452.\n", "Df Residuals: 196 BIC: 1465.\n", "Df Model: 3 \n", "Covariance Type: nonrobust \n", "=========================================================================================\n", " coef std err t P>|t| [0.025 0.975]\n", "-----------------------------------------------------------------------------------------\n", "Intercept 51.6784 0.982 52.619 0.000 49.741 53.615\n", "C(race, Helmert)[H.2] 5.7708 1.643 3.512 0.001 2.530 9.011\n", "C(race, Helmert)[H.3] -1.3431 0.867 -1.548 0.123 -3.054 0.368\n", "C(race, Helmert)[H.4] 0.7923 0.372 2.130 0.034 0.059 1.526\n", "==============================================================================\n", "Omnibus: 10.487 Durbin-Watson: 1.779\n", "Prob(Omnibus): 0.005 Jarque-Bera (JB): 11.031\n", "Skew: -0.551 Prob(JB): 0.00402\n", "Kurtosis: 2.670 Cond. No. 7.26\n", "==============================================================================\n", "\n", "Notes:\n", "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified." ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "mod = ols(\"write ~ C(race, Helmert)\", data=hsb2)\n", "res = mod.fit()\n", "print(res.summary())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.659113Z", "iopub.status.busy": "2021-02-02T06:56:36.657630Z", "iopub.status.idle": "2021-02-02T06:56:36.680950Z", "shell.execute_reply": "2021-02-02T06:56:36.681985Z" } }, "outputs": [ { "data": { "text/plain": [ "3.169061302681982" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "grouped = hsb2.groupby('race')\n", "grouped.mean()[\"write\"][4] - grouped.mean()[\"write\"][:3].mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.686776Z", "iopub.status.busy": "2021-02-02T06:56:36.685294Z", "iopub.status.idle": "2021-02-02T06:56:36.711345Z", "shell.execute_reply": "2021-02-02T06:56:36.712395Z" } }, "outputs": [ { "data": { "text/plain": [ "-1.3430555555555561" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "k = 4\n", "1./k * (grouped.mean()[\"write\"][k] - grouped.mean()[\"write\"][:k-1].mean())\n", "k = 3\n", "1./k * (grouped.mean()[\"write\"][k] - grouped.mean()[\"write\"][:k-1].mean())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Orthogonal Polynomial Coding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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`." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.717107Z", "iopub.status.busy": "2021-02-02T06:56:36.715633Z", "iopub.status.idle": "2021-02-02T06:56:36.754520Z", "shell.execute_reply": "2021-02-02T06:56:36.753355Z" } }, "outputs": [ { "data": { "text/plain": [ "readcat\n", "(27.952, 44.0] 45.000000\n", "(44.0, 60.0] 53.356436\n", "(60.0, 76.0] 60.127660\n", "Name: write, dtype: float64" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hsb2['readcat'] = np.asarray(pd.cut(hsb2.read, bins=3))\n", "hsb2.groupby('readcat').mean()['write']" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.762064Z", "iopub.status.busy": "2021-02-02T06:56:36.761261Z", "iopub.status.idle": "2021-02-02T06:56:36.766515Z", "shell.execute_reply": "2021-02-02T06:56:36.767546Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-7.07106781e-01 4.08248290e-01]\n", " [-4.43378006e-17 -8.16496581e-01]\n", " [ 7.07106781e-01 4.08248290e-01]]\n" ] } ], "source": [ "from patsy.contrasts import Poly\n", "levels = hsb2.readcat.unique().tolist()\n", "contrast = Poly().code_without_intercept(levels)\n", "print(contrast.matrix)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "execution": { "iopub.execute_input": "2021-02-02T06:56:36.778159Z", "iopub.status.busy": "2021-02-02T06:56:36.777294Z", "iopub.status.idle": "2021-02-02T06:56:36.832218Z", "shell.execute_reply": "2021-02-02T06:56:36.831069Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " OLS Regression Results \n", "==============================================================================\n", "Dep. Variable: write R-squared: 0.320\n", "Model: OLS Adj. R-squared: 0.313\n", "Method: Least Squares F-statistic: 46.32\n", "Date: Tue, 02 Feb 2021 Prob (F-statistic): 3.25e-17\n", "Time: 06:56:36 Log-Likelihood: -694.55\n", "No. Observations: 200 AIC: 1395.\n", "Df Residuals: 197 BIC: 1405.\n", "Df Model: 2 \n", "Covariance Type: nonrobust \n", "==============================================================================================\n", " coef std err t P>|t| [0.025 0.975]\n", "----------------------------------------------------------------------------------------------\n", "Intercept 52.8280 0.588 89.845 0.000 51.668 53.988\n", "C(readcat, Poly).Linear 10.6969 1.118 9.567 0.000 8.492 12.902\n", "C(readcat, Poly).Quadratic -0.6472 0.908 -0.713 0.477 -2.438 1.143\n", "==============================================================================\n", "Omnibus: 9.800 Durbin-Watson: 1.698\n", "Prob(Omnibus): 0.007 Jarque-Bera (JB): 10.330\n", "Skew: -0.536 Prob(JB): 0.00571\n", "Kurtosis: 2.702 Cond. No. 2.08\n", "==============================================================================\n", "\n", "Notes:\n", "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n" ] } ], "source": [ "mod = ols(\"write ~ C(readcat, Poly)\", data=hsb2)\n", "res = mod.fit()\n", "print(res.summary())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, readcat has a significant linear effect on the dependent variable `write` but not a significant quadratic or cubic effect." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.9" } }, "nbformat": 4, "nbformat_minor": 1 }