{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Distributions\n",
"\n",
"Elements of Data Science\n",
"\n",
"by [Allen Downey](https://allendowney.com)\n",
"\n",
"[MIT License](https://opensource.org/licenses/MIT)\n",
"\n",
"### Goals\n",
"\n",
"In this noteboook we'll see three ways to describe a set of values:\n",
"\n",
"* A probability mass function (PMF), which represents a set of values and the number of times each one appears in a dataset.\n",
"\n",
"* A cumulative distribution function (CDF), which contains the same information as a PMF in a form that makes it easier to visualize, compare distributions, and perform some computations.\n",
"\n",
"* A kernel density estimate (KDE), which is like a smooth, continuous version of a histogram.\n",
"\n",
"We will also see ways to compare distributions and compare real data to a mathematical model.\n",
"\n",
"For examples, we'll use data from the General Social Survey (GSS) to look at distributions of age and income, and to explore the relationship between income and education."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# Get the data file\n",
"\n",
"import os\n",
"\n",
"if not os.path.exists('gss.hdf5'):\n",
" !wget https://github.com/AllenDowney/ElementsOfDataScience/raw/master/gss.hdf5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following cell installs one of the libraries we will use in this notebook, `empiricaldist`. The details are not important, but if you are curious:\n",
"\n",
"* It uses the `sys` library to check whether this notebook is running on Colab.\n",
"\n",
"* It uses `pip` to install the library. `pip` is not part of the Python language; the `!` indicates that it is a \"shell command\".\n",
"\n",
"If you are running in another Jupyter environment, you will have to make sure that this library is installed."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# If we're running on Colab, install empiricaldist\n",
"# https://pypi.org/project/empiricaldist/\n",
"\n",
"import sys\n",
"IN_COLAB = 'google.colab' in sys.modules\n",
"\n",
"if IN_COLAB:\n",
" !pip install empiricaldist"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Distributions\n",
"\n",
"A distribution is a set of values and their corresponding probabilities. For example, if you roll a six-sided die, there are six possible outcomes, the number 1 through 6, and they all have the same probability, 1/6.\n",
"\n",
"We can represent the distribution of outcomes with a table, like this:\n",
"\n",
"```\n",
"Value Probability\n",
"1 1/6\n",
"2 1/6\n",
"3 1/6\n",
"4 1/6\n",
"5 1/6\n",
"6 1/6\n",
"```\n",
"\n",
"More generally, there can be any number of values, the values can be any type, and the probabilities do not have to be equal.\n",
"\n",
"In this notebook, we explore distributions of age, income, and other quantities. We'll see two ways to represent distributions, PMFs and CDFs, and several ways to visualize them."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The General Social Survey\n",
"\n",
"In this notebook we'll work with a new dataset, the General Social Survey.\n",
"\n",
"The General Social Survey, or GSS, has run annually since 1972; it surveys a representative sample of the adult population in the U.S. and asks questions about demographics and beliefs about social and political issues.\n",
"\n",
"It is widely used by politicians, policy makers, and researchers, including me.\n",
"\n",
"The GSS dataset contains hundreds of columns; I've selected just a few. And I have already cleaned and validated them, so we just have to read the file, like this."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"gss = pd.read_hdf('gss.hdf5', 'gss')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you run `gss.head()`, you can see the first few rows."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"gss.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Probability mass functions\n",
"\n",
"To get started with this dataset, let's look at the distribution of `educ`, which records the number of years of education for each respondent. First I'll select a column from the DataFrame."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"educ = gss['educ']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We've already seen one way to visualize a distribution, a histogram. Here's the histogram of education level."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"plt.hist(educ.dropna())\n",
"plt.xlabel('Years of education')\n",
"plt.ylabel('Number of respondents')\n",
"plt.title('Histogram of education level');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that we use `dropna` to drop NaNs from `educ` before we pass it to `hist`.\n",
"\n",
"Based on the histogram, we can see the general shape of the distribution and the central tendency -- it looks like the peak is near 12 years of education.\n",
"\n",
"But a histogram is not the best way to visualize this distribution.\n",
"\n",
"An alternative is a \"probability mass function\", or PMF, that contains the unique values in the dataset and how often each one appears.\n",
"\n",
"To represent a PMF, we'll use a library called `empiricaldist`, which provides a type called `Pmf`. Notice the difference in capitalization: PMF is a mathematical concept, and `Pmf` is a type.\n",
"\n",
"To import it, I'll use a version of the `import` statement we have not seen before. The following statement imports only the `Pmf` type from the `empiricaldist` library."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"from empiricaldist import Pmf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`Pmf` provides a function called `from_seq` that takes any kind of sequence -- like a list, tuple, or Pandas Series -- and computes the PMF of the values in the sequence.\n",
"\n",
"The result is a `Pmf` value, which is actually a specialized type of Pandas Series."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"pmf_educ = Pmf.from_seq(educ, normalize=False)\n",
"type(pmf_educ)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The keyword argument `normalize=False` indicates that we don't want to normalize this PMF. I'll explain what that means soon.\n",
"\n",
"Here's what the first and last few rows of the `Pmf` look like."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"pmf_educ.head()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"pmf_educ.tail()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The left column is the set of possible values; in this example it's the reported number of years of school.\n",
"\n",
"The right column is the number of times each value appears in the sequences, which is the number of respondents who reported each value.\n",
"\n",
"In this dataset, there are 7953 respondents who report that they have 16 years of formal education, which probably means they completed college.\n",
"\n",
"You can use the bracket operator to look up a value in a Pmf and get the corresponding count:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"pmf_educ[16]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Usually when we make a PMF, we want to know the *fraction* of respondents with each value, rather than the counts. We can do that by setting `normalize=True`; then we get a normalized PMF, that is, a PMF where the values in the second column add up to 1."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"pmf_educ = Pmf.from_seq(educ, normalize=True)\n",
"\n",
"pmf_educ.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now if we use the bracket operator, the result is a fraction. \n",
"\n",
"For example, the fraction of people with 12 years of education is a little more than 30%:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"pmf_educ[12]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Each `Pmf` value provides a `.bar()` method that plots a PMF as a bar chart."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"pmf_educ.bar(label='educ')\n",
"\n",
"plt.xlabel('Years of education')\n",
"plt.ylabel('PMF')\n",
"plt.title('Distribution of years of education')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this figure, we can see that the most common value is 12 years, but there are also peaks at 14 and 16, which correspond to two and four years of college.\n",
"\n",
"For this data, the PMF is probably a better choice than the histogram. The PMF shows all unique values, so we can see where the peaks are.\n",
"\n",
"Because the histogram puts values into bins, it obscures some details. With this dataset, and the default number of bins, we couldn't see the peaks at 14 and 16 years.\n",
"\n",
"PMFs have limitations, too, as we'll see. But first, let's get some practice with PMFs."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** Let's look at another column in this DataFrame, `year`, which represents the year each respondent was interviewed.\n",
"\n",
"Make an unnormalized PMF for `year` and display the result.\n",
"How many respondents were interviewed in 2016?"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** Now let's plot a PMF for the age of the respondents in the GSS dataset. The column `age` contains respondents' age in years.\n",
"\n",
"Make a normalized PMF of `age` and plot it as a bar chart."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Cumulative distribution functions\n",
"\n",
"Now we'll see another way to represent a distribution, the cumulative distribution function, or CDF.\n",
"\n",
"CDFs are useful for some computations; they are also a great way to visualize and compare distributions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A PMF tells you -- if you draw a random value from a distribution -- what's the chance of getting `x`, for any given value of `x`.\n",
"\n",
"The CDF is similar; if you draw a random value from a distribution, it tells you the chance of getting a value less than or equal to `x`.\n",
"\n",
"As an small example, suppose the distribution only has 5 elements: 1, 2, 2, 3, and 5. The following table shows the PMF:\n",
"\n",
"```\n",
"Value Probability\n",
"1 1/5\n",
"2 2/5\n",
"3 1/5\n",
"5 1/5\n",
"\n",
"```\n",
"\n",
"The PMF says that the probability of value 1 is 1/5; the probability of value 2 is 2/5, and the probabilities for 3 and 5 are 1/5.\n",
"\n",
"The CDF is the cumulative sum of the probabilities from the PMF, shown in the following table:\n",
"\n",
"```\n",
"Value Cumulative\n",
" Probability\n",
"1 1/5\n",
"2 3/5\n",
"3 4/5\n",
"5 5/5\n",
"\n",
"```\n",
"\n",
"The CDF of 2 is three fifths, because three out of 5 values in the distribution are less than or equal to 2.\n",
"\n",
"The CDF of 5 is 1, or 100%, because all of the values in the distribution are less than or equal to 5."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `empiricaldist` library provides a `Cdf` type which is similar to the `Pmf` type we've seen, and we can import it the same way."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"from empiricaldist import Cdf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`Cdf` provides a function called `from_seq` that takes any kind of sequence and returns a new `Cdf` value.\n",
"\n",
"The following example computes the CDF of ages for respondents in the General Social Survey."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"cdf_age = Cdf.from_seq(gss['age'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The result is a `Cdf` value we assign to `cdf_age`.\n",
"\n",
"`cdf_age` has a method called `plot` that plots the CDF as a line. Here's what it looks like."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"cdf_age.plot()\n",
"\n",
"plt.xlabel('Age (years)')\n",
"plt.ylabel('CDF')\n",
"plt.title('Distribution of age');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `x` axis is the ages, from 18 to 89. The `y` axis is the cumulative probabilities, from 0 to 1.\n",
"\n",
"`cdf_age` can be used as a function, so if you give it an age, it returns the corresponding probability (in a NumPy array)."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"q = 51\n",
"p = cdf_age(q)\n",
"p"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`q` stands for \"quantity\", which is what we are looking up. `p` stands for probability, which is the result.\n",
"\n",
"In this example, the quantity is age 51, and the corresponding probability is `p`, which is 0.66.\n",
"\n",
"That means that about 66% of the respondents are 51 years old or younger.\n",
"\n",
"The arrow in the following figure shows how you could read this value from the CDF, at least approximately.\n",
"\n",
"![](https://github.com/AllenDowney/ElementsOfDataScience/raw/master/figs/cdf_forward.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The CDF is an invertible function, which means that if you have a probability, `p`, you can look up the corresponding quantity, `q`.\n",
"\n",
"Here's how:\n"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"p = 0.25\n",
"q = cdf_age.inverse(p)\n",
"q"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`cdf_age` has a method called `inverse` that computes the inverse of the cumulative distribution function.\n",
"\n",
"In this example, we look up the probability 0.25, which returns 30. \n",
"\n",
"That means that 25% of the respondents are age 30 or less. Another way to say the same thing is \"age 30 is the 25th percentile of this distribution\".\n",
"\n",
"If we look up probability 0.75, it returns 57, so 75% of the respondents are 57 or younger."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"p = 0.75\n",
"q = cdf_age.inverse(p)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the following figure, the arrows show how you could read these values from the CDF.\n",
"\n",
"![](https://github.com/AllenDowney/ElementsOfDataScience/raw/master/figs/cdf_inverse.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By the way, the distance from the 25th to the 75th percentile is called the \"interquartile range\", or IQR. It measures the spread of the distribution, so it is similar to standard deviation or variance.\n",
"\n",
"Because it is based on percentiles, it doesn't get thrown off by extreme values or outliers, the way standard deviation does. So IQR is more \"robust\" than variance, which means it works well even if there are errors in the data or extreme values."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** Using `cdf_age`, compute the fraction of the respondents in the GSS dataset that are OLDER than 65."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** The distribution of income in almost every country is long-tailed, which means there are a small number of people with very high incomes.\n",
"\n",
"In the GSS dataset, the column `realinc` represents total household income, converted to 1986 dollars. We can get a sense of the shape of this distribution by plotting the CDF.\n",
"\n",
"Select `realinc` from the `gss` dataset, make a `Cdf` called `cdf_income`, and plot it. Remember to label the axes!"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comparing distributions\n",
"\n",
"So far we've seen two ways to represent distributions, PMFs and CDFs. Now we'll use PMFs and CDFs to compare distributions, and we'll see the pros and cons of each.\n",
"\n",
"One way to compare distributions is to plot multiple PMFs on the same axes. For example, suppose we want to compare the distribution of age for male and female respondents.\n",
"\n",
"First I'll create a Boolean Series that's true for male respondents."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"male = (gss['sex'] == 1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And another that's true for female respondents."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"female = (gss['sex'] == 2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And I'll extract the `age` column."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"age = gss['age']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now I can select ages for the male and female respondents."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"male_age = age[male]\n",
"female_age = age[female]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And plot a Pmf for each."
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"Pmf.from_seq(male_age).plot(label='Male')\n",
"Pmf.from_seq(female_age).plot(label='Female')\n",
"\n",
"plt.xlabel('Age (years)') \n",
"plt.ylabel('PMF')\n",
"plt.title('Distribution of age by sex')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It looks like there are more men in their twenties, maybe. And there are more women in their 70s and 80s.\n",
"\n",
"In between, the plot is pretty noisy; most of these differences are just random variations."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's do the same thing with CDFs; everything is the same except we replace `Pmf` with `Cdf`."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"Cdf.from_seq(male_age).plot(label='Male')\n",
"Cdf.from_seq(female_age).plot(label='Female')\n",
"\n",
"plt.xlabel('Age (years)') \n",
"plt.ylabel('CDF')\n",
"plt.title('Distribution of age by sex')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In general, CDFs are smoother than PMFs. Because they smooth out randomness, we can often get a better view of real differences between distributions.\n",
"\n",
"In this case, the lines are close together over the whole range; that is, the distributions are nearly identical.\n",
"\n",
"But we can see the blue line to the left of the orange line across the distribution, which we can think of two ways:\n",
"\n",
"* Suppose there is a club called the \"Under 25 Club\", where you have to be under 25 to get in. A higher fraction of men would be able to get in, compared to the fraction of women. But that doesn't necessarily mean there would be more men; that depends on the proportions of men and women in the population.\n",
"\n",
"* Suppose there's another club called the \"25th Percentile Club\", where you have to be at or below the 25th percentile to get it. The oldest eligible man would be a little younger than the oldest eligible woman.\n",
"\n",
"In this example, the difference between the distibutions is consistent over the range of ages. So everything we said about the \"Under 25 Club\" and the \"25th Percentile Club\" would also be true for 30, or the 30th percentile, or any other age or percentile."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Income\n",
"\n",
"As another example, let's look at household income and compare the distribution before and after 1995 (I chose 1995 because it's roughly the midpoint of the survey).\n",
"\n",
"The variable `realinc` represents household income in 1986 dollars.\n",
"\n",
"I'll make a Boolean Series to select respondents interviewed before and after 1995."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"pre95 = (gss['year'] < 1995)\n",
"post95 = (gss['year'] >= 1995)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can plot the PMFs."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"income = gss['realinc']\n",
"\n",
"Pmf.from_seq(income[pre95]).plot(label='Before 1995')\n",
"Pmf.from_seq(income[post95]).plot(label='After 1995')\n",
"\n",
"plt.xlabel('Income (1986 USD)')\n",
"plt.ylabel('PMF')\n",
"plt.title('Distribution of income')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are a lot of unique values in this distribution, and none of them appear very often. As a result, the PMF is so noisy and we can't really see the shape of the distribution.\n",
"\n",
"It's also hard to compare the distributions.\n",
"It looks like there are more people with high incomes after 1995, but it's hard to tell. We can get a clearer picture with a CDF."
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [],
"source": [
"Cdf.from_seq(income[pre95]).plot(label='Before 1995')\n",
"Cdf.from_seq(income[post95]).plot(label='After 1995')\n",
"\n",
"plt.xlabel('Income (1986 USD)')\n",
"plt.ylabel('CDF')\n",
"plt.title('Distribution of income')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below $30,000 the CDFs are almost identical; above that, we can see that the orange distribution is shifted to the right.\n",
"\n",
"In other words, the fraction of people with high incomes is about the same, but the income of high earners has increased.\n",
"\n",
"In general, I recommend CDFs for exploratory analysis. They give you a clear view of the distribution, without too much noise, and they are good for comparing distributions, especially if you have more than two."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** In the previous figure, the dollar amounts are big enough that the labels on the `x` axis are crowded. Improve the figure by expressing income in 1000s of dollars (and update the `x` label accordingly)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** Let's compare incomes for different levels of education in the GSS dataset\n",
"\n",
"To do that we'll create Boolean Series to identify respondents with different levels of education.\n",
"\n",
"* In the U.S, 12 years of education usually means the respondent has completed high school (secondary education). \n",
"\n",
"* A respondent with 14 years of education has probably completed an associate degree (two years of college)\n",
"\n",
"* Someone with 16 years has probably completed a bachelor's degree (four years of college).\n",
"\n",
"Define Boolean Series named `high`, `assc`, and `bach` that are true for respondents with\n",
"\n",
"* 12 or fewer years of education,\n",
"\n",
"* 13, 14, or 15 years, and\n",
"\n",
"* 16 or more.\n",
"\n",
"Compute and plot the distribution of income for each group. Remember to label the CDFs, display a legend, and label the axes.\n",
"\n",
"Write a few sentences that describe and interpret the results."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modeling distributions\n",
"\n",
"Some distributions have names. For example, you have probably heard of the normal distribution, also called the Gaussian distribution. And you might have heard of others like the exponential distribution, binomial distribution, or maybe Poisson distribution.\n",
"\n",
"These \"distributions with names\" are called \"analytic\" because they are described by analytic mathematical functions, as contrasted with \"empirical\" distributions, which are based on data.\n",
"\n",
"It turns out that many things we measure in the world have distributions that are well approximated by a analytic distributions, so these distributions are sometimes good models for the real world. \n",
"\n",
"In this context, what I mean by a \"model\" is a simplified description of the world that is accurate enough for its intended purpose.\n",
"\n",
"In this section, you'll learn to compute the CDF of a normal distribution and compare it to an empirical distribution of data.\n",
"\n",
"\n",
"But before we work with real data, I'll start with some fake data, generated at random from an actual normal distribution."
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"sample = np.random.normal(size=1000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"NumPy provides `random.normal`, which generates values from a normal distribution with mean 0 and standard deviation 1.\n",
"\n",
"Here's what the empirical disrtribution of this fake data looks like."
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"cdf_sample = Cdf.from_seq(sample)\n",
"cdf_sample.plot(label='Random sample')\n",
"\n",
"plt.xlabel('x')\n",
"plt.ylabel('CDF')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This sigmoid shape is what we expect to see with values from a normal distribution.\n",
"\n",
"If we did not know that this sample was drawn from a normal distribution, and we wanted to check, we could compare the CDF of the data to the CDF of an ideal normal distribution, which we can use the SciPy library to compute."
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import norm\n",
"\n",
"xs = np.linspace(-3, 3)\n",
"ys = norm(0, 1).cdf(xs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First we import `norm` from `scipy.stats`, which is a collection of functions related to statistics.\n",
"\n",
"Then we use `linspace()` to create an array of equally-spaced points from -3 to 3; those are the `x` values where we will evaluate the normal CDF.\n",
"\n",
"Next, `norm(0, 1)` creates a value that represents a normal distribution with mean 0 and standard deviation 1.\n",
"\n",
"Finally, `cdf()` computes the CDF of the normal distribution, evaluated at each of the `xs`.\n",
"\n",
"I'll plot the normal CDF with a gray line and then plot the CDF of the data again."
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [],
"source": [
"plt.plot(xs, ys, color='gray', label='Normal CDF')\n",
"cdf_sample.plot(label='Random sample')\n",
"\n",
"plt.xlabel('x')\n",
"plt.ylabel('CDF')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The CDF of the random sample agrees with the normal model, but that's not surprising because the data were actually sampled from a normal distribution.\n",
"\n",
"When we collect data in the real world, we do not expect it to fit a normal distribution as well as this. In the next exercise, we'll try it and see. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** Is the normal distribution a good model for the distribution of ages in the U.S. population?\n",
"\n",
"To answer this question:\n",
"\n",
"* Compute the mean and standard deviation of ages in the GSS dataset.\n",
"\n",
"* Use `linspace` to create an array of `x` values between 18 and 89.\n",
"\n",
"* Use `norm` to create a normal distribution with the same mean and standard deviation as the data, then use it to compute the normal CDF for each `x` value.\n",
"\n",
"* Plot the normal CDF with a gray line.\n",
"\n",
"* Plot the CDF of the ages in the GSS.\n",
"\n",
"How well do the plotted CDFs agree?"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** In many datasets, the distribution of income is approximately \"lognormal\", which means that the logarithms of the incomes fit a normal distribution. We'll see whether that's true for the GSS data. \n",
"\n",
"* Extract `realinc` from `gss` and compute its logarithm using `np.log10()`.\n",
"\n",
"* Compute the mean and standard deviation of the log-transformed incomes.\n",
"\n",
"* Use `norm` to make a normal distribution with the same mean and standard deviation as the log-transformed incomes.\n",
"\n",
"* Plot the CDF of the normal distribution.\n",
"\n",
"* Compute and plot the CDF of the log-transformed incomes.\n",
"\n",
"How similar are the CDFs of the log-transformed incomes and the normal distribution?"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Probability distribution functions\n",
"\n",
"We have learned about two ways to represent distributions, PMFs and CDFs. Now we'll learn another way: a probability density function, or PDF. And we'll learn how to estimate PDFs from data.\n",
"\n",
"`norm`, which we used to compute the normal CDF, can also compute the normal PDF:"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"xs = np.linspace(-3, 3)\n",
"ys = norm(0,1).pdf(xs)\n",
"plt.plot(xs, ys, color='gray', label='Normal PDF')\n",
"\n",
"plt.xlabel('x')\n",
"plt.ylabel('PDF')\n",
"plt.title('Normal density function')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The normal PDF is the classic \"bell curve\". \n",
"\n",
"It is tempting to compare the PMF of the data to the PDF of the normal distribution, but that doesn't work.\n",
"\n",
"Let's see what happens if we try:"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"plt.plot(xs, ys, color='gray', label='Normal PDF')\n",
"\n",
"pmf_sample = Pmf.from_seq(sample)\n",
"pmf_sample.plot(label='Random sample')\n",
"\n",
"plt.xlabel('x')\n",
"plt.ylabel('PDF')\n",
"plt.title('Normal density function')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The PMF of the sample is a flat line across the bottom. In the random sample, every value is unique, so they all have the same probability, one in 1000.\n",
"\n",
"However, we can use the points in the sample to estimate the PDF of the distribution they came from.\n",
"\n",
"This process is called \"kernel density estimation\", or KDE. It's a way of getting from a PMF, a probability mass function, to a PDF, a probability density function.\n",
"\n",
"To generate a KDE plot, we'll use the Seaborn library, which I'll import as `sns`.\n",
"\n",
"Seaborn provides `kdeplot`, which takes the sample, estimates the PDF, and plots it."
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"import seaborn as sns\n",
"\n",
"sns.kdeplot(sample, label='Estimated sample PDF')\n",
"\n",
"plt.xlabel('x')\n",
"plt.ylabel('PDF')\n",
"plt.title('Normal density function')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can compare the KDE plot and the normal PDF."
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [],
"source": [
"xs = np.linspace(-3, 3)\n",
"ys = norm.pdf(xs)\n",
"plt.plot(xs, ys, color='gray', label='Normal PDF')\n",
"sns.kdeplot(sample, label='Estimated sample PDF')\n",
"\n",
"plt.xlabel('x')\n",
"plt.ylabel('PDF')\n",
"plt.title('Normal density function')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The KDE plot matches the normal PDF pretty well, although the differences look bigger when we compare PDFs than they did with the CDFs.\n",
"\n",
"On one hand, that means that the PDF is a more sensitive way to look for differences, but often it is too sensitive. It's hard to tell whether apparent differences mean anything, or if they are just random, as in this case."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** In a previous exercise, we asked \"Is the normal distribution a good model for the distribution of ages in the U.S. population?\" To answer this questions, we plotted the CDF of the data and compared it to the CDF of a normal distribution with the same mean and standard deviation.\n",
"\n",
"Now we'll compare the estimated density of the data with the normal PDF.\n",
"\n",
"* Again, compute the mean and standard deviation of ages in the GSS dataset.\n",
"\n",
"* Use `linspace` to create an array of `x` values between 18 and 89.\n",
"\n",
"* Use `norm` to create a normal distribution with the same mean and standard deviation as the data, then use it to compute the normal PDF for each `x` value.\n",
"\n",
"* Plot the normal PDF with a gray line.\n",
"\n",
"* Use `sns.kdeplot` to estimate and plot the density of the ages in the GSS. \n",
"\n",
"Note: Seaborn can't handle NaNs, so use `dropna` to drop them before calling `kdeplot`.\n",
"\n",
"How well do the PDF and KDE plots agree?"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** In the previous exercise, we used CDFs to see if the distribution of income is lognormal. We can make the same comparison using a PDF and KDE.\n",
"\n",
"* Again, extract `realinc` from `gss` and compute its logarithm using `np.log10()`.\n",
"\n",
"* Compute the mean and standard deviation of the log-transformed incomes.\n",
"\n",
"* Use `norm` to make a normal distribution with the same mean and standard deviation as the log-transformed incomes.\n",
"\n",
"* Plot the PDF of the normal distribution.\n",
"\n",
"* Use `sns.kdeplot()` to estimate and plot the density of the log-transformed incomes."
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [],
"source": [
"# Solution goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To summarize, we've seen three ways to visualize distributions, PMFs, CDFs, and KDE.\n",
"\n",
"In general, I use CDFs when I am exploring data. I think they give the best view of what's going on without getting distracted by noise.\n",
"\n",
"The biggest drawback of CDFs is that they are less well known. If I am presenting results to an audience unfamiliar with CDFs, I'll use a PMF for distributions with a small number of unique values and KDE if there are a lot of values."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}