Regression

Elements of Data Science

by Allen Downey

MIT License

Goals

In the previous notebook we used simple regression to quantify the relationship between two variables.

In this notebook we'll get farther into regression, including multiple regression and one of my all-time favorite tools, logistic regression.

These tools will allow us to explore relationships among sets of variables. As an example, we will use data from the GSS to explore the relationship between income, education, age, and sex.

But first let's understand the limits of single regression.

In [1]:
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/

import sys
IN_COLAB = 'google.colab' in sys.modules

if IN_COLAB:
    !pip install empiricaldist

Limits of single regression

In a previous exercise, you made a scatter plot of vegetable consumption as a function of income, and plotted a line of best fit.

Here's what it looks like:

The slope of the line is 0.07, which means that the difference between the lowest and highest income brackets is about 0.49 servings per day.

So that's not a very big difference.

But it was an arbitrary choice to plot vegetables as a function of income. We could have plotted it the other way around, like this.

The slope of this line is about 0.2, which means that the difference between 0 and 10 servings per day is about 2 income levels, roughly from level 5 to level 7.

And the difference between income levels 5 and 7 is about $30,000 per year, which is substantial.

So if we use vegetable consumption to predict income, we see a big difference. But when we used income to predict vegetable consumption, we saw a small difference.

This example shows that regression is not symmetric; the regression of A onto B is not the same as the regression of B onto A.

We can see that more clearly by putting the two figures side by side and plotting both regression lines on both figures.

They are different because they are based on different assumptions.

  • On the left, we treat income as a known quantity and vegetable consumption as random.

  • On the right, vegetable consumption is known and income is random.

When you run a regression model, you make decisions about how to treat the data, and those decisions affect the results you get.

This example is meant to demonstrate another point, which is that regression doesn't tell you much about causation.

If you think people with lower income can't afford vegetables, you might look at the figure on the left and conclude that it doesn't make much difference.

If you think better diet increases income, the figure on the right might make you think it does.

But in general, regression can't tell you what causes what. If you see a relationship between any two variables, A and B, the reason for the relationship might be that A causes B, B causes A, or there might be other factors that cause both A and B.

Regression alone can't tell you which way it goes.

However, we have tools for teasing apart relationships among multiple variables; one of the most important is multiple regression.

SciPy doesn't do multiple regression, so we'll to switch to a new library, StatsModels. Here's the import statement.

In [2]:
import statsmodels.formula.api as smf

For the first example, we'll load data from the Behavioral Risk Factor Surveillance Survey (BRFSS), which we saw in the previous notebook.

In [3]:
# Get the data file

import os

if not os.path.exists('brfss.hdf5'):
    !wget https://github.com/AllenDowney/ElementsOfDataScience/raw/master/brfss.hdf5
In [4]:
import pandas as pd

brfss = pd.read_hdf('brfss.hdf5', 'brfss')

Now we can use StatsModels to fit a regression mode. The name of the function is ols, which stands for "ordinary least squares", another name for regression.

In [5]:
results = smf.ols('INCOME2 ~ _VEGESU1', data=brfss).fit()

The first argument is a formula string that specifies that we want to regress income as a function of vegetable consumption.

The second argument is the BRFSS DataFrame. The names in the formula correspond to columns in the DataFrame.

The result from ols() represents the model; then we run fit() to get the results.

In [6]:
type(results)

Results is a RegressionResultsWrapper, which contains a lot of information, but the first thing we'll look at is the attribute params, which contains the estimated intercept and the slope associated with _VEGESU1.

In [7]:
results.params

And we get the same results we got from SciPy, so that's good!

In the next section we'll move on to multiple regression. But first, some exercises.

Exercise: In the BRFSS dataset, there is a strong relationship between vegetable consumption and income. The income of people who eat 8 servings of vegetables per day is double the income of people who eat none, on average.

Which of the following conclusions can we draw from this data?

A. Eating a good diet leads to better health and higher income.

B. People with higher income can afford a better diet.

C. People with high income are more likely to be vegetarians.

In [8]:
# Solution goes here

Exercise: Let's run a regression using SciPy and StatsModels, and confirm we get the same results.

  • Compute the regression of _VEGESU1 as a function of INCOME2 using SciPy's linregress().

  • Compute the regression of _VEGESU1 as a function of INCOME2 using StatsModels' smf.ols().

In [9]:
# Solution goes here
In [10]:
# Solution goes here

Multiple regression

Now that we have StatsModels, getting from single to multiple regression is easy.

As an example, we'll use data from the General Social Survey, which we saw in Notebook 7, and we'll explore variables that are related to income.

First, let's load the GSS data.

In [11]:
# Get the data file

import os

if not os.path.exists('gss.hdf5'):
    !wget https://github.com/AllenDowney/ElementsOfDataScience/raw/master/gss.hdf5
In [12]:
import pandas as pd

gss = pd.read_hdf('gss.hdf5', 'gss')

Then we run a regression of real income as a function of years of education. The first argument of ols() is a formula that specifies the variables in the regression:

In [13]:
results = smf.ols('realinc ~ educ', data=gss).fit()
results.params

On the left, "real income" is the variable we are trying to predict; on the right, "education" is the variable we are using to inform the predictions.

And here are the results. The estimated slope is almost 3600, which means that each additional year of education is associated with an additional $3600 of income.

But income also depends on age, so it would be good to include that in the model, too.

Here's how:

In [14]:
results = smf.ols('realinc ~ educ + age', data=gss).fit()
results.params

On the right side of the formula, you can list as many variables as you like, in this case, education and age.

The plus sign indicates that we expect the contributions of the two variables to be additive, which is a common assumption for models like this.

The estimated slope for education is a little higher than what we saw before, about $3650 per year.

The estimated slope for age is only about $80 per year, which is surprisingly small.

To see what's going on, let's look more closely at the relationship between income and age.

Groupby

I'll use groupby(), which is a Pandas feature we have not seen before, to divide the DataFrame into age groups. The result is a GroupBy object that contains one group for each value of age.

In [15]:
grouped = gss.groupby('age')
type(grouped)

The GroupBy object behaves like a DataFrame in many ways. You can use brackets to select a column, like realinc in this example, and then invoke a method like mean().

In [16]:
mean_income_by_age = grouped['realinc'].mean()

The result is a Pandas series that contains the mean income for each age group, which we can plot like this.

In [17]:
import matplotlib.pyplot as plt

plt.plot(mean_income_by_age, 'o', alpha=0.5)
plt.xlabel('Age (years)')
plt.ylabel('Income (1986 $)')
plt.title('Average income, grouped by age');

Average income increases from age 20 to age 50, then starts to fall.

And that explains why the estimated slope is so small, because the relationship is non-linear. Remember that correlation and single regression can't measure non-linear relationships.

But multiple regression can! To describe a non-linear relationship, one option is to add a new variable that is a non-linear combination of other variables.

As an example, I'll create a new variable called age2 that equals age squared.

In [18]:
gss['age2'] = gss['age']**2

Now we can run a regression with both age and age2 on the right side.

In [19]:
model = smf.ols('realinc ~ educ + age + age2', data=gss)
results = model.fit()
results.params

The slope associated with age is substantial, about $1700 per year.

The slope associated with age2 is about -$17, but that's harder to interpret.

In the next section, we'll see methods to interpret multivariate models and visualize the results. But first, let's practice multiple regression.

Exercise: To get a closer look at the relationship between income and education, let's use the variable educ to group the data, then plot mean income in each group.

  • Group gss by educ. Store the result in grouped.

  • From grouped, extract realinc and compute the mean.

  • Plot mean income in each education group as a scatter plot.

What can you say about the relationship between education and income? Does it look like a linear relationship?

In [20]:
# Solution goes here

Exercise: The graph in the previous exercise suggests that the relationship between income and education is non-linear. So let's try fitting a non-linear model.

  • Add a column named educ2 to the gss DataFrame; it should contain the values from educ squared.

  • Run a regression model that uses educ, educ2, age, and age2 to predict realinc.

In [21]:
# Solution goes here

Visualizing regression results

In the previous section we ran a multiple regression model to characterize the relationships between income, age, and education.

Because the model includes quadratic terms, the parameters are hard to interpret. For example, you might notice that the parameter for educ is negative, and that might be a surprise, because it suggests that higher education is associated with lower income.

But the parameter for educ2 is positive, and that makes a big difference. In this section we'll see a way to interpret the model visually and validate it against data.

Here's the model from the previous exercise.

In [22]:
gss['age2'] = gss['age']**2
gss['educ2'] = gss['educ']**2

model = smf.ols('realinc ~ educ + educ2 + age + age2', data=gss)
results = model.fit()
results.params

Sometimes we can understand a model by looking at its parameters, but often it is better to look at its predictions.

The regression results provide a method called predict() that uses the model to generate predictions.

It takes a DataFrame as a parameter and returns a Series with a prediction for each row in the DataFrame.

To use it, I'll create a new DataFrame with age running from 18 to 89, and age2 set to age squared.

In [24]:
import numpy as np

df = pd.DataFrame()
df['age'] = np.linspace(18, 89)
df['age2'] = df['age']**2

Next, I'll pick a level for educ, like 12 years, which is the most common value. When you assign a single value to a column in a DataFrame, Pandas makes a copy for each respondent.

In [25]:
df['educ'] = 12
df['educ2'] = df['educ']**2

Then we can use results to predict the average income for each age group, holding education constant.

In [26]:
pred12 = results.predict(df)

The result from predict() is a Series with one prediction for each row. So we can plot it with age on the x axis and the predicted income for each age group on the y axis.

And we can plot the data for comparison.

In [27]:
plt.plot(mean_income_by_age, 'o', alpha=0.5)

plt.plot(df['age'], pred12, label='High school', color='C4')

plt.xlabel('Age (years)')
plt.ylabel('Income (1986 $)')
plt.title('Income versus age, grouped by education level')
plt.legend();

The blue dots show the average income in each age group.

The orange line shows the predictions generated by the model, holding education constant.

This plot shows the shape of the model, a downward-facing parabola.

We can do the same thing with other levels of education, like 14 years, which is the nominal time to each an Associate's degree, and 16 years, which is the nominal time to earn a Bachelor's degree.

In [28]:
plt.plot(mean_income_by_age, 'o', alpha=0.5)

df['educ'] = 16
df['educ2'] = df['educ']**2
pred16 = results.predict(df)
plt.plot(df['age'], pred16, label='Bachelor')

df['educ'] = 14
df['educ2'] = df['educ']**2
pred14 = results.predict(df)
plt.plot(df['age'], pred14, label='Associate')

plt.plot(df['age'], pred12, label='High school', color='C4')

plt.xlabel('Age (years)')
plt.ylabel('Income (1986 $)')
plt.title('Income versus age, grouped by education level')
plt.legend();

The lines show mean income, as predicted by the model, as a function of age, for three levels of education.

This visualization helps validate the model, since we can compare the predictions with the data. And it helps us interpret the model since we can see the separate contributions of age and education.

In the exercises, you'll have a chance to run a multiple regression, generate predictions, and visualize the results.

Exercise: At this point, we have a model that predicts income using age, education, and sex.

Let's see what it predicts for different levels of education, holding age constant.

  • Create an empty DataFrame named df.

  • Using np.linspace(), add a variable named educ to df with a range of values from 0 to 20.

  • Add a variable named age with the constant value 30.

  • Use df to generate predicted income as a function of education.

In [29]:
# Solution goes here
In [30]:
# Solution goes here

Exercise: Now let's visualize the results from the previous exercise!

  • Group the GSS data by educ and compute the mean income in each education group.

  • Plot mean income for each education group as a scatter plot.

  • Plot the predictions from the previous exercise.

How do the predictions compare with the data?

In [31]:
# Solution goes here

Optional Exercise: Extend the previous exercise to include predictions for a few other age levels.

Logistic regression

At last we have come to one of my favorite topics, logistic regression.

To understand logistic regression, we have to start with categorical variables.

Most of the variables we have used so far --- like income, age, and education --- are numerical.

But variables like sex and race are categorical; that is, each respondent belongs to one of a specified set of categories.

With StatsModels, it is easy to include a categorical variable as part of a regression model.

Here's how. In the formula string, the letter C indicates that sex is a categorical variable.

In [32]:
formula = 'realinc ~ educ + educ2 + age + age2 + C(sex)'
results = smf.ols(formula, data=gss).fit()
results.params

The regression treats the value sex=1, which is male, as the default, and reports the difference associated with the value sex=2, which is female.

So this result indicates that income for women is about $4100 less than for men, after controlling for age and education.

If a categorical variable has only two values, it's called a boolean variable. For example, one of the questions in the General Social Survey asks "Would you favor or oppose a law which would require a person to obtain a police permit before he or she could buy a gun?"

The column is called gunlaw, and here are the values. '1' means yes and 2 means no, so most respondents are in favor.

To explore the relationship between this variable and factors like age, sex, and education, we can use logistic regression.

StatsModels provides logistic regression, but to use it, we have to recode the variable so 1 means yes and 0 means no. We can do that by replacing 2 with 0.

In [33]:
gss['gunlaw'].value_counts()
In [34]:
gss['gunlaw'].replace([2], [0], inplace=True)

The keyword argument inplace=True means that this function modifies the gunlaw column "in place"; that is, it modifies the column in the DataFrame rather than making a new Series.

And we can check the results.

In [35]:
gss['gunlaw'].value_counts()

Now we can run the regression. Instead of ols(), we use logit(), which is named for the logit function, which is related to logistic regression.

In [36]:
formula = 'gunlaw ~ age + age2 + educ + educ2 + C(sex)'
results = smf.logit(formula, data=gss).fit()

Estimating the parameters for the logistic model is an iterative process, so the output contains information about the number of iterations.

Other than that, everything is the same as what we have seen before.

And here are the results.

In [37]:
results.params

The parameters are in the form of "log odds", which you may or may not be familiar with. I won't explain them in detail here, except to say that positive values are associated with things that make the outcome more likely; negative values make the outcome less likely.

For example, the parameter associated with sex=2 is 0.75, which indicates that women are more likely to support this form of gun control. To see how much more likely, we can generate and predict distributions, as we did with linear regression.

As an example, I'll generate predictions for different ages and sexes, with education held constant.

First we need a DataFrame with age and educ.

In [38]:
df = pd.DataFrame()
df['age'] = np.linspace(18, 89)
df['educ'] = 12

Then we can compute age2 and educ2.

In [39]:
df['age2'] = df['age']**2
df['educ2'] = df['educ']**2

We can generate predictions for men like this.

In [40]:
df['sex'] = 1
pred1 = results.predict(df)

And for women like this.

In [41]:
df['sex'] = 2
pred2 = results.predict(df)

Now, to visualize the results, I start by plotting the data. As we've done before, we'll divide the respondents into age groups and compute the mean in each group. The mean of a binary variable is the fraction of people in favor.

Then we can plot the predictions, for men and women, as a function of age.

In [42]:
grouped = gss.groupby('age')
favor_by_age = grouped['gunlaw'].mean()
plt.plot(favor_by_age, 'o', alpha=0.5)

plt.plot(df['age'], pred2, label='Female')
plt.plot(df['age'], pred1, label='Male')

plt.xlabel('Age')
plt.ylabel('Probability of favoring gun law')
plt.title('Support for gun law versus age, grouped by sex')
plt.legend();

According to the model, people near age 50 are least likely to support gun control (at least as this questions was posed).

And women are more likely to support it than men, by almost 15 percentage points.

Logistic regression is a powerful tool for exploring relationships between a binary variable and the factors that predict it.

In the exercises, you'll explore the factors that predict support for legalizing marijuana.

Exercise: Let's use logistic regression to predict a binary variable. Specifically, we'll use age, sex, and education level to predict support for legalizing cannabis (marijuana) in the U.S.

In the GSS dataset, the variable grass records the answer to the question "Do you think the use of marijuana should be made legal or not?"

  1. First, use replace to recode the grass column so that 1 means yes and 0 means no. Use value_counts to check.

  2. Next, use smf.logit() to predict grass using the variables age, age2, educ, and educ2, along with sex as a categorical variable. Display the parameters. Are men or women more likely to support legalization?

  3. To generate predictions, start with an empty DataFrame. Add a column called age that contains a sequence of values from 18 to 89. Add a column called educ and set it to 12 years. Then compute a column, age2, which is the square of age, and a column, educ2, which is the square of educ.

  4. Use predict to generate predictions for men (sex=1) and women (sex=2).

  5. Generate a plot that shows (1) the average level of support for legalizing marijuana in each age group, (2) the level of support the model predicts for men as a function of age, and (3) the level of support predicted for women as a function of age.

In [43]:
# Solution goes here
In [44]:
# Solution goes here
In [45]:
# Solution goes here
In [46]:
# Solution goes here
In [47]:
# Solution goes here

Summary

At this point, I'd like to summarize the topics we've covered so far, and make some connections that might clarify the big picture.

A central theme of this course is "exploratory data analysis", which is a process and a set of techniques for working with data, especially in the early stages of a project, or when you are working with a new data set.

The last four notebooks demonstrate the steps of this process:

  • Notebook 7 is about importing and cleaning the data, and checking for errors and other special conditions. This might not be the most exciting part of the process, but if you skip these steps, it can come back to haunt you. Time spent cleaning and validating data can save you from embarrassing, and sometimes expensive, errors.

  • Notebook 8 is about exploring variables one at a time, visualizing distributions using PMFs, CDFs, and KDE, and choosing appropriate summary statistics.

  • In Notebook 9 we explored relationships between variables two at a time, using scatter plots and other visualizations; and we quantified those relationships using correlation and simple regression.

  • Finally, in Notebook 10, we explored multivariate relationships using multiple regression and logistic regression.

From Notebook 7, you might remember that we looked at the distribution of birth weights from the National Survey of Family Growth.

If you only remember one thing, remember the 99 pound babies, and how much it can mess up your results if you don't validate the data.

In Notebook 8 we looked at the distributions of age, income, and other variables from the General Social Survey.

I recommended using CDFs as the best way to explore distributions.

But when you present to audiences that are not familiar with CDFs, you can use PMFs if there are a small number of unique values, and KDE if there are a lot.

In Notebook 9 we looked at heights and weights from the BRFSS, and developed several ways to visualize relationships between variables, including scatter plots, violin plots, and box plots like this one.

We used the coefficient of correlation to quantify the strength of a relationship. We also used simple regression to estimate slope, which is often what we care more about, not correlation.

But remember that both of these methods only capture linear relationships; if the relationship is non-linear, they can be misleading. Always look at a visualization, like a scatter plot, before computing correlation or simple regression.

In Notebook 10 we used multiple regression to add control variables and to describe non-linear relationships. And finally we used logistic regression to explain and predict binary variables.

We moved through a lot of material quickly, but if you practice and apply these methods to other questions and other dataset, you will learn more as you go.

Also, I am happy to report that you now have the prerequisites you need to appreciate this xkcd cartoon.

In [ ]: