Evaluating Models and Multiple Regression: Bayesian

Mine Doğucu

Recap: Monday

What we did on Monday

  • How fair? How and by whom were the data collected, and for what purpose? What is the impact on individuals and society? What biases or power structures are baked in?
  • How wrong? LINE: Linearity, Independence, Normality, Equal variance. Think about independence (clusters, time); check the rest with residual plots of \(e_i\) against \(\hat{y}_i\).
  • How accurate? RMSE and \(R^2\). The average \(y\) at \(x\) (confidence interval) vs. a single new \(y\) (prediction interval).
  • More variables: slopes are interpreted holding the other variables constant; still not causal with observational data. Adjusted \(R^2\) and RMSE to compare models, Occam’s razor, and training and testing data (split first!).

Today: the same questions for Bayesian models. Some tools are the same, and some are new.

Our model from last week

bike_model <- stan_glm(rides ~ temp_feel, data = bikes,
                       prior_intercept = normal(5000, 1000),
                       prior = normal(100, 40),
                       seed = 84735, refresh = 0)

Capital Bikeshare rides and “feels like” temperature (°F) in Washington, D.C., 2011–2012.

How fair is the model?

Bikeshare

The bikes data come from Capital Bikeshare, which rents bikes from stations around Washington, D.C. Each row is a day: the number of rides that day and that day’s “feels like” temperature, temp_feel.

Discussion

  • Rides can only start at a bikeshare station. Whose rides are in the data, and whose are not? How could this change what our model says about rides and temperature?
  • temp_feel is one number for the whole city each day. Does every neighborhood feel the same temperature on the same day? Why might they differ?
  • Suppose the city used this model to decide where to add stations. Who could benefit? Who could be left out?

A model can be fair in one context and unfair in another. We evaluate the model and how it will be used.

How wrong is the model?

The same assumptions

\[Y_i \mid \beta_0, \beta_1, \sigma \sim N(\beta_0 + \beta_1 X_i, \ \sigma^2)\]

This says the same thing as Monday’s \(Y_i = \beta_0 + \beta_1 X_i + \epsilon_i\) with \(\epsilon_i \sim N(0, \sigma^2)\): the same LINE assumptions.

Independence: bikes

Each row of bikes is a day, and the days come one after another. On its own, ridership is not independent: the number of rides today is likely similar to the number of rides tomorrow.

But much of this similarity comes from the time of year, and our model includes temperature, which follows the time of year. If we know today’s and tomorrow’s temperatures, today’s rides tell us little extra about tomorrow’s rides.

So, given temperature, it is reasonable to treat the days as independent. “Reasonable” does not mean “perfect”. It means “good enough to proceed.”

This argument is from Johnson, Ott, & Dogucu (2022), Bayes Rules!, Chapter 10.

How wrong is a Bayesian model?

The residual plots are the same as on Monday. For a stan_glm() model, fitted() gives \(\hat{y}_i\) and residuals() gives \(e_i\) (using the posterior median line).

bikes |>
  mutate(fitted = fitted(bike_model), residual = residuals(bike_model)) |>
  ggplot(aes(x = fitted, y = residual)) +
  geom_point(alpha = 0.4) +
  geom_hline(yintercept = 0, linetype = "dashed")
Residual vs fitted plot for the Bayesian bikeshare model. The points are spread around 0 between about 1,500 and 5,000 fitted rides. The spread is similar from left to right.

Posterior predictive check: the idea

Remember our Bayesian model:

bike_model <- stan_glm(rides ~ temp_feel, data = bikes,
                       prior_intercept = normal(5000, 1000),
                       prior = normal(100, 40),
                       seed = 84735, refresh = 0)
bike_draws <- as.data.frame(bike_model)

Each row of bike_draws is one plausible line (\(\beta_0\), \(\beta_1\)) and one plausible \(\sigma\): how far single days typically are from the line.

The idea: if our model describes the real data well, then data simulated from the model should look like the real data.

Simulating data with one plausible line

one_line <- bike_draws |> slice(1)
one_line
  (Intercept) temp_feel   sigma
1   -1828.195   76.1461 1277.58

For each of the 500 real days, we start at this line’s value for that day’s temperature, then add random noise of about \(\sigma\):

set.seed(84735)
simulated <- bikes |>
  mutate(rides = rnorm(500,
                       mean = one_line$`(Intercept)` + one_line$temp_feel * temp_feel,
                       sd = one_line$sigma))

Real data vs. simulated data

Two scatterplots of rides against temperature with the same axes. Left: the real 500 days. Right: 500 days simulated from one plausible line. Both clouds go up with temperature and have a similar overall spread, but at low temperatures the real days are packed closer together than the simulated days.

Do the simulated data look like the real data? What looks different?

Posterior predictive check

pp_check() from {rstanarm} repeats this with 50 rows of bike_draws and compares the distributions of rides: the real rides (dark) and the 50 simulated data sets (light).

pp_check(bike_model)
Posterior predictive check for the bikeshare model. A dark curve shows the distribution of the real rides; 50 light curves show the distributions of 50 simulated data sets. The light curves have about the same center and spread as the dark curve, but the dark curve has a flatter, wider top.

Is our model reasonable? Is it perfect?

How accurate are the predictions?

And Bayesian estimates?

On Monday, the least squares estimates had formulas. The posterior has no formula: stan_glm() simulates it, combining the prior (what we believed before) and the data (through the likelihood).

Bikeshare model estimates
Parameter Least squares (lm()) Posterior mean (stan_glm())
Intercept, β₀ -2179.3 -2198.6
Slope, β₁ 81.88 82.22

With 500 days of data, the data dominate the prior, and the two are close.

Bayesian: an average day vs. a single day

On Monday: a confidence interval for the average baby vs. a prediction interval for a single baby. Bayesian version: last week, each row of bike_draws gave the typical (average) number of rides on a 75 °F day: \(\beta_0 + \beta_1 \times 75\).

A single 75 °F day also varies around the line, by about \(\sigma\). So for each row, we add random noise of about that row’s \(\sigma\), just like when we simulated data.

set.seed(84735)
predict_75 <- bike_draws |>
  mutate(average_day = `(Intercept)` + temp_feel * 75,
         single_day = rnorm(n(), mean = average_day, sd = sigma))

Simulated rides on a 75 °F day

Two side by side histograms of rides on a 75 degree day, on the same x-axis, labeled average day and single day. The green histogram of the typical (average) number of rides is very narrow, near 4,000. The pink histogram of the number of rides on a single day is centered at the same place but much wider, mostly between about 1,500 and 6,500.

The average day (left) is very certain. A single day (right) can have many more or many fewer rides.

Credible vs. posterior predictive intervals

predict_75 |>
  summarize(average_lower = quantile(average_day, 0.025),
            average_upper = quantile(average_day, 0.975))
  average_lower average_upper
1      3838.285      4096.615
predict_75 |>
  summarize(single_lower = quantile(single_day, 0.025),
            single_upper = quantile(single_day, 0.975))
  single_lower single_upper
1     1535.126     6496.355
  • 95% posterior credible interval for the average 75 °F day: 3,838 to 4,097 rides.
  • 95% posterior predictive interval for a single 75 °F day: 1,535 to 6,496 rides.

How accurate are the Bayesian predictions?

We can make a 95% posterior predictive interval for each of the 500 days in the data, at that day’s temperature. If the model is accurate, about 95% of the real days should fall inside their own intervals.

prediction_summary() from the {bayesrules} package does this for us:

set.seed(84735)
prediction_summary(bike_model, data = bikes)
       mae mae_scaled within_50 within_95
1 986.4168  0.7669226     0.436     0.966

Bayesian prediction accuracy

  • within_95: 97% of the real days fall inside their 95% posterior predictive interval (and within_50: 44% inside their 50% interval).
  • mae: the typical distance between a day’s real rides and its prediction is about 986 rides.

Exercise

Based on within_95 and within_50, are the model’s posterior predictive intervals about right? Is a typical error of about 986 rides a lot?

Bayesian multiple linear regression

Bikeshare, again

Last week: rides ~ temp_feel and rides ~ weekend, separately. Now both:

\[Y_i \mid \beta_0, \beta_1, \beta_2, \sigma \sim N(\beta_0 + \beta_1 \text{temp\_feel}_i + \beta_2 \text{weekend}_i, \ \sigma^2)\]

We need a prior for each parameter. We keep the priors from last week:

Priors for the bikeshare model
Parameter Prior
Centered intercept (an average temperature weekday) \(N(5000, 1000^2)\)
Slope of temp_feel, β₁ \(N(100, 40^2)\)
Slope of weekend, β₂ \(N(0, 1000^2)\)

Fitting the model

prior takes one normal distribution for each slope, in the same order as the variables.

bike_model_2 <- stan_glm(rides ~ temp_feel + weekend, data = bikes,
                         prior_intercept = normal(5000, 1000),
                         prior = normal(c(100, 0), c(40, 1000)),
                         seed = 84735, refresh = 0)
bike_draws_2 <- as.data.frame(bike_model_2)
head(bike_draws_2, 3)
  (Intercept) temp_feel weekendTRUE    sigma
1   -1866.107  79.83063   -774.9802 1268.241
2   -1396.788  74.02053   -479.3370 1299.355
3   -2084.841  82.23587   -778.4981 1172.328

Each row is one plausible set of \((\beta_0, \beta_1, \beta_2, \sigma)\).

Posterior plausible lines

Scatterplot of rides against temperature; weekdays are pink dots and weekends are green crosses. Fifty solid pink posterior lines for weekdays, labeled weekday, sit above fifty dashed green posterior lines for weekends, labeled weekend; within each group the lines are close together and all go up with temperature.

Two sets of parallel lines: weekdays (pink, solid) and weekends (green, dashed).

Posterior summaries

bike_draws_2 |>
  summarize(posterior_mean_b1 = mean(temp_feel),
            posterior_lower_b1 = quantile(temp_feel, 0.025),
            posterior_upper_b1 = quantile(temp_feel, 0.975))
  posterior_mean_b1 posterior_lower_b1 posterior_upper_b1
1          80.67803           70.80376           90.27475
bike_draws_2 |>
  summarize(posterior_mean_b2 = mean(weekendTRUE),
            posterior_lower_b2 = quantile(weekendTRUE, 0.025),
            posterior_upper_b2 = quantile(weekendTRUE, 0.975))
  posterior_mean_b2 posterior_lower_b2 posterior_upper_b2
1          -697.314          -950.6154          -453.8724

Your turn

Exercise

  1. Interpret the posterior mean of \(\beta_2\) (weekendTRUE) in context. Remember: holding temperature constant.
  2. Interpret the 95% posterior credible interval for \(\beta_2\).
  3. What code would find the posterior probability that \(\beta_2 < 0\)?
bike_draws_2 |>
  summarize(posterior_prob_negative = mean(weekendTRUE < 0))
  posterior_prob_negative
1                       1

How wrong is the new model?

The same tools as on Monday. Each row of bike_draws_2 gives a plausible line for weekdays, one for weekends, and \(\sigma\). pp_check() simulates 50 data sets and compares them with the real rides.

pp_check(bike_model_2)
Posterior predictive check for the model of rides with temperature and weekend. A dark curve shows the distribution of the real rides; 50 light curves show the distributions of 50 simulated data sets. The light curves have about the same center and spread as the dark curve, but the dark curve has two bumps that the light curves smooth over.

Do the simulated data sets look like the real data?

Training and testing

Training and testing: reminder

On Monday: in a real analysis, splitting the data is the first step, not the last.

  1. Before fitting any model, randomly split the data into training (80%) and testing (20%) data.
  2. Fit, check, and compare models on the training data only.
  3. At the end, check the chosen model’s predictions on the testing data.

For Bayesian models, we check the testing data against the posterior predictive intervals with prediction_summary().

Training and testing: Bayesian

Fit stan_glm() on the training data only. Then, as earlier today, check how many days in the testing data fall inside their 95% posterior predictive intervals.

set.seed(84735)
bike_split <- initial_split(bikes, prop = 0.8)
bike_train <- training(bike_split)
bike_test <- testing(bike_split)
bike_train_2 <- stan_glm(rides ~ temp_feel + weekend, data = bike_train,
                         prior_intercept = normal(5000, 1000),
                         prior = normal(c(100, 0), c(40, 1000)),
                         seed = 84735, refresh = 0)
set.seed(84735)
prediction_summary(bike_train_2, data = bike_test)
       mae mae_scaled within_50 within_95
1 931.9683  0.7416612      0.45      0.97

data = bike_test: the model never saw these days.

Comparing models on testing data

Posterior prediction on the testing data for two Bayesian bikeshare models
Explanatory variables mae (rides) within_50 within_95
temp_feel 1,006 0.39 0.97
temp_feel + weekend 932 0.45 0.97

Exercise

Which model predicts new days better? Are the posterior predictive intervals about right for both models?

Frequentist vs. Bayesian

Evaluating frequentist and Bayesian regression models
Question Frequentist (lm()) Bayesian (stan_glm())
How wrong? LINE: residual plots with augment() LINE: residual plots and pp_check()
The average y at a given x \(\hat{y}\) and a 95% confidence interval 95% posterior credible interval for \(\beta_0 + \beta_1 x\)
A single new y at a given x 95% prediction interval 95% posterior predictive interval
How accurate? RMSE and R² prediction_summary()
More variables lm(y ~ x1 + x2) stan_glm(y ~ x1 + x2), one prior per slope
New data RMSE on testing data prediction_summary() on testing data

Summary

  • Bayesian models are evaluated with the same three questions: how fair, how wrong, how accurate. The LINE assumptions are the same.
  • Posterior predictive check: simulate data sets from plausible lines (rows of the posterior draws) and compare them with the real data: pp_check().
  • The average \(y\) at \(x\) (95% posterior credible interval) vs. a single new \(y\) (95% posterior predictive interval, which also includes \(\sigma\)).
  • Accuracy: how many observations fall inside their posterior predictive intervals, and the typical prediction error: prediction_summary().
  • Multiple linear regression: stan_glm(y ~ x1 + x2, ...) with one prior per slope, prior = normal(c(...), c(...)). Slopes are interpreted holding the other variables constant.
  • Training and testing: fit on the training data, then prediction_summary(model, data = testing_data).