<jupyter_start><jupyter_text>Regression Think Bayes, Second EditionCopyright 2020 <NAME>License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)<jupyter_code># 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
# Get utils.py and create directories

import os

if not os.path.exists('utils.py'):
    !wget https://github.com/AllenDowney/ThinkBayes2/raw/master/soln/utils.py
from utils import set_pyplot_params
set_pyplot_params()<jupyter_output><empty_output><jupyter_text>In the previous chapter we saw several examples of logistic regression, which is based on the assumption that the likelihood of an outcome, expressed in the form of log odds, is a linear function of some quantity (continuous or discrete).In this chapter we'll work on examples of simple linear regression, which models the relationship between two quantities.  Specifically, we'll look at changes over time in snowfall and the marathon world record.The models we'll use have three parameters, so you might want to review the tools we used for the three-parameter model in >.  More Snow?I am under the impression that we don't get as much snow around here as we used to.  By "around here" I mean Norfolk County, Massachusetts, where I was born, grew up, and currently live.  And by "used to" I mean compared to when I was young, like in 1978 when we got [27 inches of snow](https://en.wikipedia.org/wiki/Northeastern_United_States_blizzard_of_1978) and I didn't have to go to school for a couple of weeks.Fortunately, we can test my conjecture with data.  Norfolk County happens to be the location of the [Blue Hill Meteorological Observatory](https://en.wikipedia.org/wiki/Blue_Hill_Meteorological_Observatory), which keeps the oldest continuous weather record in North America.Data from this and many other weather stations is available from the [National Oceanic and Atmospheric Administration](https://www.ncdc.noaa.gov/cdo-web/search) (NOAA).  I collected data from the Blue Hill Observatory from May 11, 1967 to May 11, 2020.   The following cell downloads the data as a CSV file.<jupyter_code>import os

datafile = '2239075.csv'
if not os.path.exists(datafile):
    !wget https://github.com/AllenDowney/ThinkBayes2/raw/master/data/2239075.csv<jupyter_output><empty_output><jupyter_text>We can use Pandas to read the data into `DataFrame`:<jupyter_code>import pandas as pd

df = pd.read_csv('2239075.csv', parse_dates=[2])<jupyter_output><empty_output><jupyter_text>Here's what the last few rows look like.<jupyter_code>df.tail(3)<jupyter_output><empty_output><jupyter_text>The columns we'll use are:* `DATE`, which is the date of each observation,* `SNOW`, which is the total snowfall in inches.I'll add a column that contains just the year part of the dates.<jupyter_code>df['YEAR'] = df['DATE'].dt.year<jupyter_output><empty_output><jupyter_text>And use `groupby` to add up the total snowfall in each year.<jupyter_code>snow = df.groupby('YEAR')['SNOW'].sum()<jupyter_output><empty_output><jupyter_text>The first and last years are not complete, so I'll drop them.<jupyter_code>snow = snow.iloc[1:-1]
len(snow)<jupyter_output><empty_output><jupyter_text>The following figure shows total snowfall during each of the complete years in my lifetime.<jupyter_code>from utils import decorate

snow.plot(style='o', alpha=0.5)

decorate(xlabel='Year',
         ylabel='Total annual snowfall (inches)',
         title='Total annual snowfall in Norfolk County, MA')<jupyter_output><empty_output><jupyter_text>Looking at this plot, it's hard to say whether snowfall is increasing, decreasing, or unchanged.  In the last decade, we've had several years with more snow than 1978, including 2015, which was the snowiest winter in the Boston area in modern history, with a total of 141 inches.This kind of question -- looking at noisy data and wondering whether it is going up or down -- is precisely the question we can answer with Bayesian regression.<jupyter_code>snow.loc[[1978, 1996, 2015]]<jupyter_output><empty_output><jupyter_text>Regression ModelThe foundation of regression (Bayesian or not) is the assumption that a time series like this is the sum of two parts:1. A linear function of time, and2. A series of random values drawn from a distribution that is not changing over time.Mathematically, the regression model is$$y = a x + b + \epsilon$$where $y$ is the series of measurements (snowfall in this example), $x$ is the series of times (years) and $\epsilon$ is the series of random values.$a$ and $b$ are the slope and intercept of the line through the data.  They are unknown parameters, so we will use the data to estimate them.We don't know the distribution of $\epsilon$, so we'll make the additional assumption that it is a normal distribution with mean 0 and unknown standard deviation, $\sigma$.  To see whether this assumption is reasonable, I'll plot the distribution of total snowfall and a normal model with the same mean and standard deviation.Here's a `Pmf` object that represents the distribution of snowfall.<jupyter_code>from empiricaldist import Pmf

pmf_snowfall = Pmf.from_seq(snow)<jupyter_output><empty_output><jupyter_text>And here are the mean and standard deviation of the data.<jupyter_code>mean, std = pmf_snowfall.mean(), pmf_snowfall.std()
mean, std<jupyter_output><empty_output><jupyter_text>I'll use the `norm` object from SciPy to compute the CDF of the a normal distribution with the same mean and standard deviation.<jupyter_code>from scipy.stats import norm

dist = norm(mean, std)
qs = pmf_snowfall.qs
ps = dist.cdf(qs)<jupyter_output><empty_output><jupyter_text>Here's what the distribution of the data looks like compared to the normal model.<jupyter_code>import matplotlib.pyplot as plt

plt.plot(qs, ps, color='C5', label='model')
pmf_snowfall.make_cdf().plot(label='data')

decorate(xlabel='Total snowfall (inches)',
         ylabel='CDF',
         title='Normal model of variation in snowfall')<jupyter_output><empty_output><jupyter_text>We've had more winters below the mean than expected, but overall this looks like a reasonable model.  Least Squares RegressionOur regression model has three parameters: slope, intercept, and standard deviation of $\epsilon$.Before we can estimate them, we have to choose priors.To help with that, I'll use StatsModel to fit a line to the data by [least squares regression](https://en.wikipedia.org/wiki/Least_squares).First, I'll use `reset_index` to convert `snow`, which is a `Series`, to a `DataFrame`.<jupyter_code>data = snow.reset_index()
data.head(3)<jupyter_output><empty_output><jupyter_text>The result is a `DataFrame` with two columns, `YEAR` and `SNOW`, in a format we can use with StatsModels.As we did in the previous chapter, I'll center the data by subtracting off the mean.<jupyter_code>offset = data['YEAR'].mean().round()
data['x'] = data['YEAR'] - offset
offset<jupyter_output><empty_output><jupyter_text>And I'll add a column to `data` so the dependent variable has a standard name.<jupyter_code>data['y'] = data['SNOW']<jupyter_output><empty_output><jupyter_text>Now, we can use StatsModels to compute the least squares fit to the data and estimate `slope` and `intercept`.<jupyter_code>import statsmodels.formula.api as smf

formula = 'y ~ x'
results = smf.ols(formula, data=data).fit()
results.params<jupyter_output><empty_output><jupyter_text>The intercept, about 64 inches, is the expected snowfall when `x=0`, which is the beginning of 1994.The estimated slope indicates that total snowfall is increasing at a rate of about 0.5 inches per year.  `results` also provides `resid`, which is an array of residuals, that is, the differences between the data and the fitted line.The standard deviation of the residuals is an estimate of `sigma`.<jupyter_code>results.resid.std()<jupyter_output><empty_output><jupyter_text>We'll use these estimates to choose prior distributions for the parameters.  PriorsI'll use uniform distributions for all three parameters.<jupyter_code>import numpy as np
from utils import make_uniform

qs = np.linspace(-0.5, 1.5, 51)
prior_slope = make_uniform(qs, 'Slope')
qs = np.linspace(54, 75, 41)
prior_inter = make_uniform(qs, 'Intercept')
qs = np.linspace(20, 35, 31)
prior_sigma = make_uniform(qs, 'Sigma')<jupyter_output><empty_output><jupyter_text>I made the prior distributions different lengths for two reasons.  First, if we make a mistake and use the wrong distribution, it will be easier to catch the error if they are all different lengths.Second, it provides more precision for the most important parameter, `slope`, and spends less computational effort on the least important, `sigma`.In > we made a joint distribution with three parameters.  I'll wrap that process in a function:<jupyter_code>from utils import make_joint

def make_joint3(pmf1, pmf2, pmf3):
    """Make a joint distribution with three parameters."""
    joint2 = make_joint(pmf2, pmf1).stack()
    joint3 = make_joint(pmf3, joint2).stack()
    return Pmf(joint3)<jupyter_output><empty_output><jupyter_text>And use it to make a `Pmf` that represents the joint distribution of the three parameters.<jupyter_code>prior = make_joint3(prior_slope, prior_inter, prior_sigma)
prior.head(3)<jupyter_output><empty_output><jupyter_text>The index of `Pmf` has three columns, containing values of `slope`, `inter`, and `sigma`, in that order.With three parameters, the size of the joint distribution starts to get big.  Specifically, it is the product of the lengths of the prior distributions.  In this example, the prior distributions have 51, 41, and 31 values, so the length of the joint prior is 64,821.<jupyter_code>len(prior_slope), len(prior_inter), len(prior_sigma)
len(prior_slope) * len(prior_inter) * len(prior_sigma)
len(prior)<jupyter_output><empty_output><jupyter_text>LikelihoodNow we'll compute the likelihood of the data.To demonstrate the process, let's assume temporarily that the parameters are known.<jupyter_code>inter = 64
slope = 0.51
sigma = 25<jupyter_output><empty_output><jupyter_text>I'll extract the `xs` and `ys` from `data` as `Series` objects:<jupyter_code>xs = data['x']
ys = data['y']<jupyter_output><empty_output><jupyter_text>And compute the "residuals", which are the differences between the actual values, `ys`, and the values we expect based on `slope` and `inter`.<jupyter_code>expected = slope * xs + inter
resid = ys - expected<jupyter_output><empty_output><jupyter_text>According to the model, the residuals should follow a normal distribution with mean 0 and standard deviation `sigma`.  So we can compute the likelihood of each residual value using `norm` from SciPy.<jupyter_code>densities = norm(0, sigma).pdf(resid)<jupyter_output><empty_output><jupyter_text>The result is an array of probability densities, one for each element of the dataset; their product is the likelihood of the data.<jupyter_code>likelihood = densities.prod()
likelihood<jupyter_output><empty_output><jupyter_text>As we saw in the previous chapter, the likelihood of any particular dataset tends to be small.If it's too small, we might exceed the limits of floating-point arithmetic.When that happens, we can avoid the problem by computing likelihoods under a log transform.But in this example that's not necessary.  The UpdateNow we're ready to do the update.  First, we need to compute the likelihood of the data for each possible set of parameters.<jupyter_code>likelihood = prior.copy()

for slope, inter, sigma in prior.index:
    expected = slope * xs + inter
    resid = ys - expected
    densities = norm.pdf(resid, 0, sigma)
    likelihood[slope, inter, sigma] = densities.prod()<jupyter_output><empty_output><jupyter_text>This computation takes longer than many of the previous examples.We are approaching the limit of what we can do with grid approximations.Nevertheless, we can do the update in the usual way:<jupyter_code>posterior = prior * likelihood
posterior.normalize()<jupyter_output><empty_output><jupyter_text>The result is a `Pmf` with a three-level index containing values of `slope`, `inter`, and `sigma`.To get the marginal distributions from the joint posterior, we can use `Pmf.marginal`, which we saw in >.<jupyter_code>posterior_slope = posterior.marginal(0)
posterior_inter = posterior.marginal(1)
posterior_sigma = posterior.marginal(2)<jupyter_output><empty_output><jupyter_text>Here's the posterior distribution for `sigma`:<jupyter_code>posterior_sigma.plot()

decorate(xlabel='$\sigma$, standard deviation of $\epsilon$',
         ylabel='PDF',
         title='Posterior marginal distribution of $\sigma$')<jupyter_output><empty_output><jupyter_text>The most likely values for `sigma` are near 26 inches, which is consistent with our estimate based on the standard deviation of the data.However, to say whether snowfall is increasing or decreasing, we don't really care about `sigma`.  It is a "nuisance parameter", so-called because we have to estimate it as part of the model, but we don't need it to answer the questions we are interested in.Nevertheless, it is good to check the marginal distributions to make sure * The location is consistent with our expectations, and * The posterior probabilities are near 0 at the extremes of the range, which indicates that the prior distribution covers all parameters with non-negligible probability.In this example, the posterior distribution of `sigma` looks fine. Here's the posterior distribution of `inter`:<jupyter_code>posterior_inter.plot(color='C1')
decorate(xlabel='intercept (inches)',
         ylabel='PDF',
         title='Posterior marginal distribution of intercept')
from utils import summarize
    
summarize(posterior_inter)<jupyter_output><empty_output><jupyter_text>The posterior mean is about 64 inches, which is the expected amount of snow during the year at the midpoint of the range, 1994.And finally, here's the posterior distribution of `slope`:<jupyter_code>posterior_slope.plot(color='C4')
decorate(xlabel='Slope (inches per year)',
         ylabel='PDF',
         title='Posterior marginal distribution of slope')
summarize(posterior_slope)<jupyter_output><empty_output><jupyter_text>The posterior mean is about 0.51 inches, which is consistent with the estimate we got from least squared regression.  The 90% credible interval is from 0.1 to 0.9, which indicates that our uncertainty about this estimate is pretty high.  In fact, there is still a small posterior probability (about 2\%) that the slope is negative.<jupyter_code>posterior_slope.make_cdf()(0)<jupyter_output><empty_output><jupyter_text>However, it is more likely that my conjecture was wrong: we are actually getting more snow around here than we used to, increasing at a rate of about a half-inch per year, which is substantial.  On average, we get an additional 25 inches of snow per year than we did when I was young.This example shows that with slow-moving trends and noisy data, your instincts can be misleading.  Now, you might suspect that I overestimate the amount of snow when I was young because I enjoyed it, and underestimate it now because I don't.  But you would be mistaken.During the Blizzard of 1978, we did not have a snowblower and my brother and I had to shovel.  My sister got a pass for no good reason.  Our driveway was about 60 feet long and three cars wide near the garage.  And we had to shovel <NAME>'s driveway, too, for which we were not allowed to accept payment.  Furthermore, as I recall it was during this excavation that I accidentally hit my brother with a shovel on the head, and it bled a lot because, you know, scalp wounds.Anyway, the point is that I don't think I overestimate the amount of snow when I was young because I have fond memories of it.   OptimizationThe way we computed the likelihood in the previous section was pretty slow.  The problem is that we looped through every possible set of parameters in the prior distribution, and there were more than 60,000 of them.If we can do more work per iteration, and run the loop fewer times, we expect it to go faster.In order to do that, I'll unstack the prior distribution:<jupyter_code>joint3 = prior.unstack()
joint3.head(3)<jupyter_output><empty_output><jupyter_text>The result is a `DataFrame` with `slope` and `intercept` down the rows and `sigmas` across the columns.The following is a version of `likelihood_regression` that takes the joint prior distribution in this form and returns the posterior distribution in the same form.<jupyter_code>from utils import normalize

def update_optimized(prior, data):
    """Posterior distribution of regression parameters
    `slope`, `inter`, and `sigma`.
    
    prior: Pmf representing the joint prior
    data: DataFrame with columns `x` and `y`
    
    returns: Pmf representing the joint posterior
    """
    xs = data['x']
    ys = data['y']
    sigmas = prior.columns    
    likelihood = prior.copy()

    for slope, inter in prior.index:
        expected = slope * xs + inter
        resid = ys - expected
        resid_mesh, sigma_mesh = np.meshgrid(resid, sigmas)
        densities = norm.pdf(resid_mesh, 0, sigma_mesh)
        likelihood.loc[slope, inter] = densities.prod(axis=1)
        
    posterior = prior * likelihood
    normalize(posterior)
    return posterior<jupyter_output><empty_output><jupyter_text>This version loops through all possible pairs of `slope` and `inter`, so the loop runs about 2000 times.<jupyter_code>len(prior_slope) * len(prior_inter)<jupyter_output><empty_output><jupyter_text>Each time through the loop, it uses a grid mesh to compute the likelihood of the data for all values of `sigma`.  The result is an array with one column for each data point and one row for each value of `sigma`.  Taking the product across the columns (`axis=1`) yields the probability of the data for each value of sigma, which we assign as a row in `likelihood`.<jupyter_code>%time posterior_opt = update_optimized(joint3, data)<jupyter_output><empty_output><jupyter_text>We get the same result either way.<jupyter_code>np.allclose(posterior, posterior_opt.stack())<jupyter_output><empty_output><jupyter_text>But this version is about 25 times faster than the previous version.  This optimization works because many functions in NumPy and SciPy are written in C, so they run fast compared to Python.  If you can do more work each time you call these functions, and less time running the loop in Python, your code will often run substantially faster.In this version of the posterior distribution, `slope` and `inter` run down the rows and `sigma` runs across the columns.  So we can use `marginal` to get the posterior joint distribution of `slope` and `intercept`.<jupyter_code>from utils import marginal

posterior2 = marginal(posterior_opt, 1)
posterior2.head(3)<jupyter_output><empty_output><jupyter_text>The result is a `Pmf` with two columns in the index.To plot it, we have to unstack it.<jupyter_code>joint_posterior = posterior2.unstack().transpose()
joint_posterior.head(3)<jupyter_output><empty_output><jupyter_text>Here's what it looks like.<jupyter_code>from utils import plot_contour

plot_contour(joint_posterior)
decorate(title='Posterior joint distribution of slope and intercept')<jupyter_output><empty_output><jupyter_text>The ovals in the contour plot are aligned with the axes, which indicates that there is no correlation between `slope` and `inter` in the posterior distribution, which is what we expect since we centered the values.In this example, the motivating question is about the slope of the line, so we answered it by looking at the posterior distribution of slope.In the next example, the motivating question is about prediction, so we'll use the joint posterior distribution to generate predictive distributions.  Marathon World RecordFor many running events, if you plot the world record pace over time, the result is a remarkably straight line.  People, [including me](http://allendowney.blogspot.com/2011/04/two-hour-marathon-in-2045.html), have speculated about possible reasons for this phenomenon.People have also speculated about when, if ever, the world record time for the marathon will be less than two hours.(Note: In 2019 <NAME> ran the marathon distance in under two hours, which is an astonishing achievement that I fully appreciate, but for several reasons it did not count as a world record).So, as a second example of Bayesian regression, we'll consider the world record progression for the marathon (for male runners), estimate the parameters of a linear model, and use the model to predict when a runner will break the two-hour barrier.   The following cell downloads a web page from Wikipedia that includes a table of marathon world records, and uses Pandas to put the data in a `DataFrame`.<jupyter_code>url = 'https://en.wikipedia.org/wiki/Marathon_world_record_progression#Men'
tables = pd.read_html(url)
len(tables)<jupyter_output><empty_output><jupyter_text>If that doesn't work, I have made a copy of this page available.  The following cell downloads and parses it.<jupyter_code>#import os

#datafile = 'Marathon_world_record_progression.html'
#if not os.path.exists(datafile):
#    !wget https://github.com/AllenDowney/ThinkBayes2/raw/master/data/Marathon_world_record_progression.html

#tables = pd.read_html(datafile)
#len(tables)<jupyter_output><empty_output><jupyter_text>The first table is the one we want.<jupyter_code>table = tables[0]
table.head(3)<jupyter_output><empty_output><jupyter_text>We can use Pandas to parse the dates.A few of them include notes that cause parsing problems, but the argument `errors='coerce'` tells Pandas to fill invalid dates with `NaT`, which is a version of `NaN` that represents "not a time".<jupyter_code>table['date'] = pd.to_datetime(table['Date'], errors='coerce')
table['date'].head()<jupyter_output><empty_output><jupyter_text>We can also use Pandas to parse the record times.<jupyter_code>table['time'] = pd.to_timedelta(table['Time'])<jupyter_output><empty_output><jupyter_text>And convert the times to paces in miles per hour.<jupyter_code>table['y'] = 26.2 / table['time'].dt.total_seconds() * 3600
table['y'].head()<jupyter_output><empty_output><jupyter_text>The following function plots the results.<jupyter_code>def plot_speeds(df):
    """Plot marathon world record speed as a function of time.
    
    df: DataFrame with date and mph
    """
    plt.axhline(13.1, color='C5', linestyle='dashed')
    plt.plot(df['date'], df['y'], 'o', 
             label='World record speed', 
             color='C1', alpha=0.5)
    
    decorate(xlabel='Date',
             ylabel='Speed (mph)')<jupyter_output><empty_output><jupyter_text>Here's what the results look like.The dashed line shows the speed required for a two-hour marathon, 13.1 miles per hour.<jupyter_code>plot_speeds(table)<jupyter_output><empty_output><jupyter_text>It's not a perfectly straight line.  In the early years of the marathon, the record speed increased quickly; since about 1970, it has been increasing more slowly.For our analysis, let's focus on the recent progression, starting in 1970.<jupyter_code>recent = table['date'] > pd.to_datetime('1970')
data = table.loc[recent].copy()
data.head()<jupyter_output><empty_output><jupyter_text>In the notebook for this chapter, you can see how I loaded and cleaned the data.  The result is a `DataFrame` that contains the following columns (and additional information we won't use:* `date`, which is a Pandas `Timestamp` representing the date when the world record was broken, and* `speed`, which records the record-breaking pace in mph.Here's what the results look like, starting in 1970:<jupyter_code>plot_speeds(data)<jupyter_output><empty_output><jupyter_text>The data points fall approximately on a line, although it's possible that the slope is increasing.To prepare the data for regression, I'll subtract away the approximate midpoint of the time interval, 1995.<jupyter_code>offset = pd.to_datetime('1995')
timedelta = table['date'] - offset<jupyter_output><empty_output><jupyter_text>When we subtract two `Timestamp` objects, the result is a "time delta", which we can convert to seconds and then to years.<jupyter_code>data['x'] = timedelta.dt.total_seconds() / 3600 / 24 / 365.24
data['x'].describe()<jupyter_output><empty_output><jupyter_text>As in the previous example, I'll use least squares regression to compute point estimates for the parameters, which will help with choosing priors.<jupyter_code>import statsmodels.formula.api as smf

formula = 'y ~ x'
results = smf.ols(formula, data=data).fit()
results.params<jupyter_output><empty_output><jupyter_text>The estimated intercept is about 12.5 mph, which is the interpolated world record pace for 1995.  The estimated slope is about 0.015 mph per year, which is rate the world record pace is increasing, according to the model.Again, we can use the standard deviation of the residuals as a point estimate for `sigma`.<jupyter_code>results.resid.std()<jupyter_output><empty_output><jupyter_text>These parameters give us a good idea where we should put the prior distributions.  The PriorsHere are the prior distributions I chose for `slope`, `intercept`, and `sigma`.<jupyter_code>qs = np.linspace(0.012, 0.018, 51)
prior_slope = make_uniform(qs, 'Slope')
qs = np.linspace(12.4, 12.5, 41)
prior_inter = make_uniform(qs, 'Intercept')
qs = np.linspace(0.01, 0.21, 31)
prior_sigma = make_uniform(qs, 'Sigma')<jupyter_output><empty_output><jupyter_text>And here's the joint prior distribution.<jupyter_code>prior = make_joint3(prior_slope, prior_inter, prior_sigma)
prior.head()<jupyter_output><empty_output><jupyter_text>Now we can compute likelihoods as in the previous example:<jupyter_code>xs = data['x']
ys = data['y']
likelihood = prior.copy()

for slope, inter, sigma in prior.index:
    expected = slope * xs + inter
    resid = ys - expected
    densities = norm.pdf(resid, 0, sigma)
    likelihood[slope, inter, sigma] = densities.prod()<jupyter_output><empty_output><jupyter_text>Now we can do the update in the usual way.<jupyter_code>posterior = prior * likelihood
posterior.normalize()<jupyter_output><empty_output><jupyter_text>And unpack the marginals:<jupyter_code>posterior_slope = posterior.marginal(0)
posterior_inter = posterior.marginal(1)
posterior_sigma = posterior.marginal(2)
posterior_sigma.plot();<jupyter_output><empty_output><jupyter_text>Here's the posterior distribution of `inter`:<jupyter_code>posterior_inter.plot(color='C1')
decorate(xlabel='intercept',
         ylabel='PDF',
         title='Posterior marginal distribution of intercept')
summarize(posterior_inter)<jupyter_output><empty_output><jupyter_text>The posterior mean is about 12.5 mph, which is the world record marathon pace the model predicts for the midpoint of the date range, 1994.And here's the posterior distribution of `slope`.<jupyter_code>posterior_slope.plot(color='C4')
decorate(xlabel='Slope',
         ylabel='PDF',
         title='Posterior marginal distribution of slope')
summarize(posterior_slope)<jupyter_output><empty_output><jupyter_text>The posterior mean is about 0.015 mph per year, or 0.15 mph per decade.That's interesting, but it doesn't answer the question we're interested in: when will there be a two-hour marathon.  To answer that, we have to make predictions.  PredictionTo generate predictions, I'll draw a sample from the posterior distribution of parameters, then use the regression equation to combine the parameters with the data.`Pmf` provides `choice`, which we can use to draw a random sample with replacement, using the posterior probabilities as weights.<jupyter_code>np.random.seed(17)
sample = posterior.choice(101)<jupyter_output><empty_output><jupyter_text>The result is an array of tuples.  Looping through the sample, we can use the regression equation to generate predictions for a range of `xs`.<jupyter_code>xs = np.arange(-25, 50, 2)
pred = np.empty((len(sample), len(xs)))

for i, (slope, inter, sigma) in enumerate(sample):
    epsilon = norm(0, sigma).rvs(len(xs))
    pred[i] = inter + slope * xs + epsilon<jupyter_output><empty_output><jupyter_text>Each prediction is an array with the same length as `xs`, which I store as a row in `pred`.  So the result has one row for each sample and one column for each value of `x`.We can use `percentile` to compute the 5th, 50th, and 95th percentiles in each column.<jupyter_code>low, median, high = np.percentile(pred, [5, 50, 95], axis=0)<jupyter_output><empty_output><jupyter_text>To show the results, I'll plot the median of the predictions as a line and the 90% credible interval as a shaded area.<jupyter_code>times = pd.to_timedelta(xs*365.24, unit='days') + offset

plt.fill_between(times, low, high, 
                 color='C2', alpha=0.1)
plt.plot(times, median, color='C2')

plot_speeds(data)<jupyter_output><empty_output><jupyter_text>The dashed line show the two-hour marathon pace, which is 13.1 miles per hour.Visually we can estimate that the prediction line hits the target pace between 2030 and 2040.To make this more precise, we can use interpolation to see when the predictions cross the finish line.  SciPy provides `interp1d`, which does linear interpolation by default.<jupyter_code>from scipy.interpolate import interp1d

future = np.array([interp1d(high, xs)(13.1),
                   interp1d(median, xs)(13.1),
                   interp1d(low, xs)(13.1)])
dts = pd.to_timedelta(future*365.24, unit='day') + offset
pd.DataFrame(dict(datetime=dts),
             index=['early', 'median', 'late'])<jupyter_output><empty_output><jupyter_text>The median prediction is 2036, with 90% credible interval from 2032 to 2043.  So there is about a 5% chance we'll see a two-hour marathon before 2032.  SummaryThis chapter introduces Bayesian regression, which is based on the same model as least squares regression; the difference is that it produces a posterior distribution for the parameters rather than point estimates.In the first example, we looked at changes in snowfall in Norfolk County, Massachusetts, and concluded that we get more snowfall now than when I was young, contrary to my expectation.In the second example, we looked at the progression of world record pace for the men's marathon, computed the joint posterior distribution of the regression parameters, and used it to generate predictions for the next 20 years.These examples have three parameters, so it takes a little longer to compute the likelihood of the data.With more than three parameters, it becomes impractical to use grid algorithms.  In the next few chapters, we'll explore other algorithms that reduce the amount of computation we need to do a Bayesian update, which makes it possible to use models with more parameters.But first, you might want to work on these exercises.  Exercises **Exercise:** I am under the impression that it is warmer around here than it used to be.  In this exercise, you can put my conjecture to the test.We'll use the same dataset we used to model snowfall; it also includes daily low and high temperatures in Norfolk County, Massachusetts during my lifetime. Here's the data.<jupyter_code>df = pd.read_csv('2239075.csv', parse_dates=[2])
df.head(3)<jupyter_output><empty_output><jupyter_text>Again, I'll create a column that contains the year part of the dates.<jupyter_code>df['YEAR'] = df['DATE'].dt.year<jupyter_output><empty_output><jupyter_text>This dataset includes `TMIN` and `TMAX`, which are the daily low and high temperatures in degrees F.I'll create a new column with the daily midpoint of the low and high temperatures.<jupyter_code>df['TMID'] = (df['TMIN'] + df['TMAX']) / 2<jupyter_output><empty_output><jupyter_text>Now we can group by year and compute the mean of these daily temperatures.<jupyter_code>tmid = df.groupby('YEAR')['TMID'].mean()
len(tmid)<jupyter_output><empty_output><jupyter_text>Again, I'll drop the first and last years, which are incomplete.<jupyter_code>complete = tmid.iloc[1:-1]
len(complete)<jupyter_output><empty_output><jupyter_text>Here's what the time series looks like.<jupyter_code>complete.plot(style='o', alpha=0.5)

decorate(xlabel='Year',
         ylabel='Annual average of daily temperature (deg F)')<jupyter_output><empty_output><jupyter_text>As we did with the snow data, I'll convert the `Series` to a `DataFrame` to prepare it for regression.<jupyter_code>data = complete.reset_index()
data.head()
offset = data['YEAR'].mean().round()
offset
data['x'] = data['YEAR'] - offset
data['x'].mean()
data['y'] = data['TMID']
data['y'].std()<jupyter_output><empty_output><jupyter_text>Now we can use StatsModels to estimate the parameters.<jupyter_code>import statsmodels.formula.api as smf

formula = 'y ~ x'
results = smf.ols(formula, data=data).fit()
results.params<jupyter_output><empty_output><jupyter_text>And compute the standard deviation of the parameters.<jupyter_code>results.resid.std()<jupyter_output><empty_output><jupyter_text>According to the least squares regression model, annual average temperature is increasing by about 0.044 degrees F per year.To quantify the uncertainty of these parameters and generate predictions for the future, we can use Bayesian regression. 1. Use StatsModels to generate point estimates for the regression parameters.2. Choose priors for `slope`, `intercept`, and `sigma` based on these estimates, and use `make_joint3` to make a joint prior distribution.3. Compute the likelihood of the data and compute the posterior distribution of the parameters.4. Extract the posterior distribution of `slope`.  How confident are we that temperature is increasing?5. Draw a sample of parameters from the posterior distribution and use it to generate predictions up to 2067.6. Plot the median of the predictions and a 90% credible interval along with the observed data.  Does the model fit the data well?  How much do we expect annual average temperatures to increase over my (expected) lifetime?<jupyter_code># Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here
# Solution goes here<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08410074659384714, 'fraction_numerical': 0.013043604566714115, 'mean_word_length': 5.530829064693607, 'pattern_counts': {'":': 0, '<': 316, '<?xml version=': 0, '>': 320, 'https://': 10, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '78', 'dir': 'jupyter-structured-clean-dedup', 'id': '36217', 'license': 'MIT', 'n_tokens_mistral': 10502, 'n_tokens_neox': 9798, 'n_words': 4000, 'path': 'notebooks/chap17.ipynb', 'repo_name': 'yuanquan010/ThinkBayes2', 'size': '34445'}