{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Chapter 11\n", "\n", "Examples and Exercises from Think Stats, 2nd Edition\n", "\n", "http://thinkstats2.com\n", "\n", "Copyright 2016 Allen B. Downey\n", "\n", "MIT License: https://opensource.org/licenses/MIT\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from os.path import basename, exists\n", "\n", "\n", "def download(url):\n", " filename = basename(url)\n", " if not exists(filename):\n", " from urllib.request import urlretrieve\n", "\n", " local, _ = urlretrieve(url, filename)\n", " print(\"Downloaded \" + local)\n", "\n", "\n", "download(\"https://github.com/AllenDowney/ThinkStats2/raw/master/code/thinkstats2.py\")\n", "download(\"https://github.com/AllenDowney/ThinkStats2/raw/master/code/thinkplot.py\")" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "\n", "import numpy as np\n", "import pandas as pd\n", "\n", "import thinkstats2\n", "import thinkplot" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiple regression\n", "\n", "Let's load up the NSFG data again." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "download(\"https://github.com/AllenDowney/ThinkStats2/raw/master/code/nsfg.py\")\n", "download(\"https://github.com/AllenDowney/ThinkStats2/raw/master/code/first.py\")\n", "\n", "download(\"https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemPreg.dct\")\n", "download(\n", " \"https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemPreg.dat.gz\"\n", ")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "import first\n", "\n", "live, firsts, others = first.MakeFrames()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's birth weight as a function of mother's age (which we saw in the previous chapter)." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "import statsmodels.formula.api as smf\n", "\n", "formula = 'totalwgt_lb ~ agepreg'\n", "model = smf.ols(formula, data=live)\n", "results = model.fit()\n", "results.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can extract the parameters." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "inter = results.params['Intercept']\n", "slope = results.params['agepreg']\n", "inter, slope" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And the p-value of the slope estimate." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "slope_pvalue = results.pvalues['agepreg']\n", "slope_pvalue" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And the coefficient of determination." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "results.rsquared" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The difference in birth weight between first babies and others." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "diff_weight = firsts.totalwgt_lb.mean() - others.totalwgt_lb.mean()\n", "diff_weight" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The difference in age between mothers of first babies and others." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "diff_age = firsts.agepreg.mean() - others.agepreg.mean()\n", "diff_age" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The age difference plausibly explains about half of the difference in weight." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "slope * diff_age" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Running a single regression with a categorical variable, `isfirst`:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "live['isfirst'] = live.birthord == 1\n", "formula = 'totalwgt_lb ~ isfirst'\n", "results = smf.ols(formula, data=live).fit()\n", "results.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now finally running a multiple regression:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "formula = 'totalwgt_lb ~ isfirst + agepreg'\n", "results = smf.ols(formula, data=live).fit()\n", "results.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As expected, when we control for mother's age, the apparent difference due to `isfirst` is cut in half.\n", "\n", "If we add age squared, we can control for a quadratic relationship between age and weight." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "live['agepreg2'] = live.agepreg**2\n", "formula = 'totalwgt_lb ~ isfirst + agepreg + agepreg2'\n", "results = smf.ols(formula, data=live).fit()\n", "results.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we do that, the apparent effect of `isfirst` gets even smaller, and is no longer statistically significant.\n", "\n", "These results suggest that the apparent difference in weight between first babies and others might be explained by difference in mothers' ages, at least in part." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data Mining\n", "\n", "We can use `join` to combine variables from the preganancy and respondent tables." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "download(\"https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemResp.dct\")\n", "download(\"https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemResp.dat.gz\")" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "import nsfg\n", "\n", "live = live[live.prglngth>30]\n", "resp = nsfg.ReadFemResp()\n", "resp.index = resp.caseid\n", "join = live.join(resp, on='caseid', rsuffix='_r')\n", "join.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And we can search for variables with explanatory power.\n", "\n", "Because we don't clean most of the variables, we are probably missing some good ones." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "import patsy\n", "\n", "def GoMining(df):\n", " \"\"\"Searches for variables that predict birth weight.\n", "\n", " df: DataFrame of pregnancy records\n", "\n", " returns: list of (rsquared, variable name) pairs\n", " \"\"\"\n", " variables = []\n", " for name in df.columns:\n", " try:\n", " if df[name].var() < 1e-7:\n", " continue\n", "\n", " formula = 'totalwgt_lb ~ agepreg + ' + name\n", " model = smf.ols(formula, data=df)\n", " if model.nobs < len(df)/2:\n", " continue\n", "\n", " results = model.fit()\n", " except (ValueError, TypeError, patsy.PatsyError) as e:\n", " continue\n", " \n", " variables.append((results.rsquared, name))\n", "\n", " return variables" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "variables = GoMining(join)\n", "variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following functions report the variables with the highest values of $R^2$." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "import re\n", "\n", "def ReadVariables():\n", " \"\"\"Reads Stata dictionary files for NSFG data.\n", "\n", " returns: DataFrame that maps variables names to descriptions\n", " \"\"\"\n", " vars1 = thinkstats2.ReadStataDct('2002FemPreg.dct').variables\n", " vars2 = thinkstats2.ReadStataDct('2002FemResp.dct').variables\n", "\n", " all_vars = vars1.append(vars2)\n", " all_vars.index = all_vars.name\n", " return all_vars\n", "\n", "def MiningReport(variables, n=30):\n", " \"\"\"Prints variables with the highest R^2.\n", "\n", " t: list of (R^2, variable name) pairs\n", " n: number of pairs to print\n", " \"\"\"\n", " all_vars = ReadVariables()\n", "\n", " variables.sort(reverse=True)\n", " for r2, name in variables[:n]:\n", " key = re.sub('_r$', '', name)\n", " try:\n", " desc = all_vars.loc[key].desc\n", " if isinstance(desc, pd.Series):\n", " desc = desc[0]\n", " print(name, r2, desc)\n", " except (KeyError, IndexError):\n", " print(name, r2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some of the variables that do well are not useful for prediction because they are not known ahead of time." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "MiningReport(variables)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Combining the variables that seem to have the most explanatory power." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "formula = ('totalwgt_lb ~ agepreg + C(race) + babysex==1 + '\n", " 'nbrnaliv>1 + paydu==1 + totincr')\n", "results = smf.ols(formula, data=join).fit()\n", "results.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Logistic regression\n", "\n", "Example: suppose we are trying to predict `y` using explanatory variables `x1` and `x2`." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "y = np.array([0, 1, 0, 1])\n", "x1 = np.array([0, 0, 0, 1])\n", "x2 = np.array([0, 1, 1, 1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "According to the logit model the log odds for the $i$th element of $y$ is\n", "\n", "$\\log o = \\beta_0 + \\beta_1 x_1 + \\beta_2 x_2 $\n", "\n", "So let's start with an arbitrary guess about the elements of $\\beta$:\n", "\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "beta = [-1.5, 2.8, 1.1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plugging in the model, we get log odds." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "log_o = beta[0] + beta[1] * x1 + beta[2] * x2\n", "log_o" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Which we can convert to odds." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "o = np.exp(log_o)\n", "o" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And then convert to probabilities." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "p = o / (o+1)\n", "p" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The likelihoods of the actual outcomes are $p$ where $y$ is 1 and $1-p$ where $y$ is 0. " ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "likes = np.where(y, p, 1-p)\n", "likes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The likelihood of $y$ given $\\beta$ is the product of `likes`:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "like = np.prod(likes)\n", "like" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Logistic regression works by searching for the values in $\\beta$ that maximize `like`.\n", "\n", "Here's an example using variables in the NSFG respondent file to predict whether a baby will be a boy or a girl." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "import first\n", "live, firsts, others = first.MakeFrames()\n", "live = live[live.prglngth>30]\n", "live['boy'] = (live.babysex==1).astype(int)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The mother's age seems to have a small effect." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "model = smf.logit('boy ~ agepreg', data=live)\n", "results = model.fit()\n", "results.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here are the variables that seemed most promising." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "formula = 'boy ~ agepreg + hpagelb + birthord + C(race)'\n", "model = smf.logit(formula, data=live)\n", "results = model.fit()\n", "results.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To make a prediction, we have to extract the exogenous and endogenous variables." ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "endog = pd.DataFrame(model.endog, columns=[model.endog_names])\n", "exog = pd.DataFrame(model.exog, columns=model.exog_names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The baseline prediction strategy is to guess \"boy\". In that case, we're right almost 51% of the time." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "actual = endog['boy']\n", "baseline = actual.mean()\n", "baseline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we use the previous model, we can compute the number of predictions we get right." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "predict = (results.predict() >= 0.5)\n", "true_pos = predict * actual\n", "true_neg = (1 - predict) * (1 - actual)\n", "sum(true_pos), sum(true_neg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And the accuracy, which is slightly higher than the baseline." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "acc = (sum(true_pos) + sum(true_neg)) / len(actual)\n", "acc" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To make a prediction for an individual, we have to get their information into a `DataFrame`." ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "columns = ['agepreg', 'hpagelb', 'birthord', 'race']\n", "new = pd.DataFrame([[35, 39, 3, 2]], columns=columns)\n", "y = results.predict(new)\n", "y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This person has a 51% chance of having a boy (according to the model)." ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Exercises" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "**Exercise:** Suppose one of your co-workers is expecting a baby and you are participating in an office pool to predict the date of birth. Assuming that bets are placed during the 30th week of pregnancy, what variables could you use to make the best prediction? You should limit yourself to variables that are known before the birth, and likely to be available to the people in the pool." ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "import first\n", "live, firsts, others = first.MakeFrames()\n", "live = live[live.prglngth>30]" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** The Trivers-Willard hypothesis suggests that for many mammals the sex ratio depends on “maternal condition”; that is, factors like the mother’s age, size, health, and social status. See https://en.wikipedia.org/wiki/Trivers-Willard_hypothesis\n", "\n", "Some studies have shown this effect among humans, but results are mixed. In this chapter we tested some variables related to these factors, but didn’t find any with a statistically significant effect on sex ratio.\n", "\n", "As an exercise, use a data mining approach to test the other variables in the pregnancy and respondent files. Can you find any factors with a substantial effect?" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** If the quantity you want to predict is a count, you can use Poisson regression, which is implemented in StatsModels with a function called `poisson`. It works the same way as `ols` and `logit`. As an exercise, let’s use it to predict how many children a woman has born; in the NSFG dataset, this variable is called `numbabes`.\n", "\n", "Suppose you meet a woman who is 35 years old, black, and a college graduate whose annual household income exceeds $75,000. How many children would you predict she has born?" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can predict the number of children for a woman who is 35 years old, black, and a college\n", "graduate whose annual household income exceeds $75,000" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** If the quantity you want to predict is categorical, you can use multinomial logistic regression, which is implemented in StatsModels with a function called `mnlogit`. As an exercise, let’s use it to guess whether a woman is married, cohabitating, widowed, divorced, separated, or never married; in the NSFG dataset, marital status is encoded in a variable called `rmarital`.\n", "\n", "Suppose you meet a woman who is 25 years old, white, and a high school graduate whose annual household income is about $45,000. What is the probability that she is married, cohabitating, etc?" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Make a prediction for a woman who is 25 years old, white, and a high\n", "school graduate whose annual household income is about $45,000." ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11" } }, "nbformat": 4, "nbformat_minor": 1 }