library(tidyverse)
library(tidymodels)13-regression
Course Announcements
Due Dates:
- ⌨️ Lab 06 due today (11:59 PM)
- 📄 Final Project Proposal due Sun
- 🔘 Lecture Participation survey “due” after class
Agenda
- Simple linear regression (review)
- Multiple linear regression
- Model Comparison
- Backward Selection
Suggested Reading
Linear Regression
Setup
Data
# in your CS02 repo, the file is at "data/pm25_data.csv"
pm <- read_csv("OCS_data/data/raw/pm25_data.csv") |>
# these are ID codes, not measurements
mutate(across(c(id, fips, zcta), as.factor))Rows: 876 Columns: 50
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (3): state, county, city
dbl (47): id, value, fips, lat, lon, CMAQ, zcta, zcta_area, zcta_pop, imp_a5...
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Starting Question
What is the relationship between the EPA’s CMAQ and PM2.5 values?
Reminder: Community Multiscale Air Quality (CMAQ) is the EPA’s air pollution model. The data do NOT use PM2.5 measures
Quick Look
ggplot(pm, aes(x=CMAQ, y=value)) +
geom_point()
Single predictor
Regression model
\[ \hat{y} = b_0 + b_1~x_1 \]
- \(\hat{y}\) | outcome
- \(x_1\) | predictor
- \(b_0\) | y-intercept
- \(b_1\) | slope (effect size)
Step 1: Specify model
linear_reg()Linear Regression Model Specification (regression)
Computational engine: lm
Step 2: Set model fitting engine
lin_mod <- linear_reg() |>
set_engine("lm") # lm: linear modelStep 3: Fit model & estimate parameters
… using formula syntax
# fit model
mod_cmaq_value <- lin_mod |>
fit(value ~ CMAQ, data = pm)
# display results
mod_cmaq_value |>
tidy()# A tibble: 2 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 7.40 0.232 31.9 1.81e-148
2 CMAQ 0.405 0.0260 15.6 1.83e- 48
. . .
\[\widehat{PM2.5}_{i} = 7.40 + 0.405 \times CMAQ_{i}\]
Visualizing the model
ggplot(data = pm, aes(x = CMAQ, y = value)) +
geom_point(alpha = 0.4) +
geom_smooth(method = "lm", fullrange = TRUE, color = "#8E2C90", se = FALSE)
Q&A {.scrollable .smaller} (Mon 11/9)
A: The question is what differs first (prediction vs. quantifying a relationship.). Then, sometimes the model used differs. In the case of linear regression, the model is the same. But for prediction, the approach will differ (training vs. validation vs. test set - we’ll talk about this soon!). In other cases, models are built for prediction and only used to make predictions. We’ll get to this too.
Course Announcements
Due Dates:
- Lab 7 due Friday (11:59 PM) <- not CS02 based
- 🔘 Lecture Participation survey “due” after class
Notes:
- No lecture Wed
Slope and intercept
\[\widehat{PM2.5}_{i} = 7.40 + 0.405 \times CMAQ_{i}\]
. . .
- Slope: For each one unit increase in CMAQ, we expect PM2.5 to increase, on average, by 0.405 ug/m^3.
. . .
- Intercept: Monitors in areas with a CMAQ of zero are expected to have PM2.5 values of 7.4 ug/m^3, on average. (Recall: WHO exposure guideline is < 10 ug/m^3 on average annually for PM2.5)
Model Understanding
\[\widehat{PM2.5}_{i} = 7.40 + 0.405 \times CMAQ_{i}\]
❓ What would we expect the PM2.5 value to be in an area with a CMAQ of 2?
❗️Prediction vs. extrapolation
❓ What would we expect the PM2.5 value to be in an area with a CMAQ of 100? \[\widehat{PM2.5}_{i} = 7.40 + 0.405 \times 100\]
. . .

Measuring the strength of the fit
The strength of the fit of a linear model is most commonly evaluated using \(R^2\).
It tells us what percent of variability in the response variable is explained by the model.
The remainder of the variability is explained by variables not included in the model.
\(R^2\) is sometimes called the coefficient of determination.
Obtaining \(R^2\) in R
glance(mod_cmaq_value)# A tibble: 1 × 12
r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.217 0.216 2.29 243. 1.83e-48 1 -1966. 3939. 3953.
# ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>
glance(mod_cmaq_value)$r.squared # extract R-squared[1] 0.2172969
Roughly 21.7% of the variability in PM2.5 values can be explained by CMAQ.
. . .
…suggests that we can do better to explain the variance in PM2.5 values
Multiple predictors (MLR)
MLR
- Sample model that we use to estimate the population model:
\[ \hat{y} = b_0 + b_1~x_1 + b_2~x_2 + \cdots + b_k~x_k \]
Updated question
What is the relationship between CMAQ & population density (predictors) and and PM2.5 values (outcome)?
- Response variable:
value(PM2.5) - Explanatory variables:
CMAQand Population Density hi/low
Creating a low/high population density variable
pm <- pm |>
mutate(popdens = case_when(
popdens_zcta >= median(pm$popdens_zcta) ~ "hi",
popdens_zcta < median(pm$popdens_zcta) ~ "low"
))❓ What is this accomplishing?
PM2.5 & Poulation density

ggplot(data = pm, aes(x = value, fill = popdens)) +
geom_histogram(binwidth = 2.5) +
facet_grid(popdens ~ .) +
scale_fill_manual(values = c("#071381", "#E48957")) +
guides(fill = "none") +
labs(x = "PM2.5", y = NULL) Two ways to model
- Main effects: Assuming relationship between CMAQ and PM2.5 does not vary by whether it’s a low or high population density monitor.
- Interaction effects: Assuming relationship between CMAQ and PM2. varies by whether or not it’s a low or high population density monitor.
Interacting explanatory variables
- Including an interaction effect in the model allows for different slopes, i.e. nonparallel lines.
- This implies that the regression coefficient for an explanatory variable would change as another explanatory variable changes.
- This can be accomplished by adding an interaction variable: the product of two explanatory variables.
Two ways to model
- Main effects: Assuming relationship between CMAQ and PM2.5 does not vary by whether it’s a low or high population density monitor.
- Interaction effects: Assuming relationship between CMAQ and PM2. varies by whether or not it’s a low or high population density monitor.

. . .
❓ Which does your intuition/knowledge of the data suggest is more appropriate?
Put a green sticky if you think main; pink if you think interaction.
Fit model with main effects
pm_main_fit <- lin_mod |>
fit(value ~ CMAQ + popdens, data = pm)
pm_main_fit |> tidy()# A tibble: 3 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 7.70 0.272 28.3 1.02e-125
2 CMAQ 0.389 0.0270 14.4 1.89e- 42
3 popdenslow -0.345 0.160 -2.15 3.17e- 2
. . .
\[\widehat{PM2.5} = 7.70 + 0.389 \times CMAQ - 0.345 \times popdens\]
. . .
❓ How do we interpret this model?
Solving the model
- High-population density: Plug in 0 for
popdens
\[\widehat{PM2.5} = 7.70 + 0.389 \times CMAQ - 0.345 \times 0\]
\(= 7.70 + 0.389 \times CMAQ\)
. . .
- Low-population density: Plug in 1 for
popdens
\[\widehat{PM2.5} = 7.70 + 0.389 \times CMAQ - 0.345 \times 1\]
\(= 7.355 + 0.389 \times CMAQ\)
Visualizing main effects
- Same slope: Rate of change in PM2.5 as CMAQ increases does not vary between low- and high-population density monitor areas.
- Different intercept: Areas of low density have consistently lower PM2.5 values relative to high-population density areas

Interpreting main effects
pm_main_fit |>
tidy() |>
select(term, estimate)# A tibble: 3 × 2
term estimate
<chr> <dbl>
1 (Intercept) 7.70
2 CMAQ 0.389
3 popdenslow -0.345
- All else held constant, for each 1 unit increase in CMAQ, PM2.5 would expect to increase by 0.389.
- All else held constant, areas of low density have PM2.5 values, on average, that are 0.345 lower than in high density areas
- PM2.5 values in high-density areas with a CMAQ of zero, would expect to have a PM2.5 value of 7.7.
Interaction: CMAQ * popdens

Fit model with interaction effects
- Response variable:
value(PM2.5) - Explanatory variables:
CMAQ,popdens, and their interaction
pm_int_fit <- lin_mod |>
fit(value ~ CMAQ * popdens, data = pm)Linear model with interaction effects
# A tibble: 4 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 8.35 0.381 21.9 4.63e-85
2 CMAQ 0.319 0.0396 8.05 2.69e-15
3 popdenslow -1.45 0.485 -3.00 2.79e- 3
4 CMAQ:popdenslow 0.131 0.0540 2.42 1.56e- 2
\[\widehat{PM2.5} = 8.35 + 0.32 \times CMAQ - 1.45 \times popdens + 0.13 \times CMAQ * popdens\]
Interpretation of interaction effects
- Rate of change in PM2.5 as CMAQ increases varies depending upon PopDens (different slopes & intercepts)
. . .

Comparing models
R-squared
- \(R^2\) is the percentage of variability in the response variable explained by the regression model.
glance(mod_cmaq_value)$r.squared #single predictor[1] 0.2172969
glance(pm_main_fit)$r.squared[1] 0.2214237
glance(pm_int_fit)$r.squared[1] 0.2266283
. . .
- The model with interactions has a slightly higher \(R^2\).
. . .
- However using \(R^2\) for model selection in models with multiple explanatory variables is not a good idea as \(R^2\) increases when any variable is added to the model.
Adjusted R-squared
Adjusted R-squared adjusts for number of terms in the model
glance(pm_main_fit)$adj.r.squared[1] 0.21964
glance(pm_int_fit)$adj.r.squared[1] 0.2239676
It appears that adding the interaction actually increased adjusted \(R^2\), so we should indeed use the model with the interactions.
In pursuit of Occam’s razor
Occam’s Razor states that among competing hypotheses that predict equally well, the one with the fewest assumptions should be selected.
Model selection follows this principle.
We only want to add another variable to the model if the addition of that variable brings something valuable in terms of predictive power to the model.
In other words, we prefer the simplest best model, i.e. parsimonious model.
Backward selection
Backward selection
For this demo, we’ll ignore interaction effects…and just model main effects:
First, keep only columns that make sense as predictors:
pm_model <- pm |>
# ID codes & names with (nearly) one level per monitor
select(-id, -fips, -zcta, -county, -city) |>
# hs_orless = nohs + somehs + hs, so it adds no information
select(-hs_orless)❓ What would happen if we left city (607 different values) in the model?
. . .
pm_full <- lin_mod |>
fit(value ~ ., data = pm_model) - Adjusted \(R^2\) (full): 0.5726
. . .
Remove zcta_area
pm_noarea <- lin_mod |>
fit(value ~ . -zcta_area, data = pm_model)
glance(pm_noarea)$adj.r.squared[1] 0.5731684
. . .
- Adjusted \(R^2\) (full): 0.5726
- Adjusted \(R^2\) (no
zcta_area): 0.5732
…Increased improved variance explained, so remove variable
. . .
… continue to remove one variable at a time until adjusted \(R^2\) stops improving. (You’ll do this yourself in Lab 07.)
Why this matters for CS02
❓ How does this maybe inform our ultimate goal (building a prediction model)?
Recap
- Can you model and interpret linear models with multiple predictors?
- Can you explain the difference in a model with main effects vs. interaction effects?
- Can you compare different models and determine how to proceed?
- Can you carry out and explain backward selection?