Evaluating Models and Multiple Regression: Frequentist

Mine Doğucu

Is our model any good?

Our model from last week

model_g <- lm(bwt ~ gestation, data = babies)

Birth weight (oz) and gestation (days) of babies born in the East Bay, 1960–1967.

We can fit a model. But is it a good model?

Today: how to evaluate a regression model, and how to use more than one explanatory variable. Everything today is frequentist. On Wednesday, we do the same for Bayesian models.

Three questions

All models are wrong, but some are useful. (George Box)

To evaluate a model, we ask:

  1. How fair is the model?
  2. How wrong is the model?
  3. How accurate are the model’s predictions?

These three questions come from Johnson, Ott, & Dogucu (2022), Bayes Rules!, Chapter 10. They work for both frequentist and Bayesian models.

How fair is the model?

Questions to ask

  • How was the data collected?
  • By whom, and for what purpose?
  • How might the results of the analysis, or the data collection itself, impact individuals and society?
  • What biases or power structures might be baked into this analysis?

These questions are not answered with R code. They are answered by thinking about the context.

Baby weights

The babies data come from the Child Health and Development Studies: pregnant women in the Kaiser Foundation Health Plan in the East Bay (San Francisco area), 1960–1967.

Discussion

With your neighbor, discuss the four questions for the babies data.

  • Who is in the data? Who might be missing?
  • Our model from last Monday says babies of mothers who smoked weighed less, on average. Who could use this result, and how?
  • Would it be fair to use a model fit to these babies for babies born today? For babies born somewhere else?

How wrong is the model?

What does our model assume?

\[Y_i = \beta_0 + \beta_1 X_i + \epsilon_i \qquad \epsilon_i \sim N(0, \sigma^2)\]

The model makes four assumptions (LINE):

  • Linearity: the relationship between \(X\) and \(Y\) is linear.
  • Independence: the observations are independent of each other.
  • Normality: the errors are normally distributed around the line.
  • Equal variance: the errors have the same spread for all values of \(X\).

On Wednesday, we will see that Bayesian regression makes the same assumptions.

Independence

Two observations are independent if knowing one tells us nothing extra about the other.

Observations are often not independent when they come in groups or in a sequence:

  • Clusters: patients in the same hospital or students in the same class tend to be more alike than two random people.
  • Time: measurements one after another (today and tomorrow) tend to be similar.

Independence is about how the data were collected. We check it by thinking, not with a plot.

Independence: babies

Each row of babies is a different baby. That alone does not make the observations independent.

The babies were born at a few Kaiser hospitals. If babies born at the same hospital are more alike (same doctors, same neighborhoods, same care), then they are clustered within hospitals, and two babies from the same hospital are not independent.

Discussion

What else could make some babies in the data more alike than two randomly chosen babies?

Fitted values and residuals

For each observation \(i\):

  • The fitted value, \(\hat{y}_i\), is the value on the line at \(x_i\): the \(y\) the model expects for that \(x\).
  • The residual, \(e_i = y_i - \hat{y}_i\), is observed minus fitted: how far the point is from the line.

Fitted values and residuals in R

augment() from the {broom} package adds both to the data: .fitted is \(\hat{y}_i\) and .resid is \(e_i\).

model_g_aug <- augment(model_g)
model_g_aug |>
  select(bwt, gestation, .fitted, .resid) |>
  head(3)
# A tibble: 3 × 4
    bwt gestation .fitted .resid
  <int>     <int>   <dbl>  <dbl>
1   120       284    122.  -1.79
2   113       282    121.  -7.86
3   128       279    119.   8.53

For the first baby: \(y_1 = 120\), \(\hat{y}_1 = 121.79\), so \(e_1 = 120 - 121.79 = -1.79\) ounces.

Residuals vs. fitted values

ggplot(model_g_aug, aes(x = .fitted, y = .resid)) +
  geom_point(alpha = 0.4) +
  geom_hline(yintercept = 0, linetype = "dashed")
Scatterplot of the residuals of the birth weight model against the fitted values, with a dashed horizontal line at 0. The points form a shapeless cloud centered at 0 with roughly the same spread from left to right, except for a few points with small fitted values.

Each point is one baby: its fitted value \(\hat{y}_i\) (x-axis) and its residual \(e_i\) (y-axis). We want a shapeless cloud around 0: no curve (Linearity) and the same spread everywhere (Equal variance).

Histogram of residuals

ggplot(model_g_aug, aes(x = .resid)) +
  geom_histogram(binwidth = 5, fill = green, color = "white")
Histogram of the residuals of the birth weight model. It is unimodal, centered at 0, and roughly symmetric and bell shaped, with a few residuals far below 0.

We want it to look roughly Normal: unimodal, symmetric, centered at 0.

What does “wrong” look like?

Three residual vs fitted plots made with simulated data. Left, labeled good: a shapeless cloud around 0. Middle, labeled not linear: the residuals form a U shape, positive at both ends and negative in the middle. Right, labeled not equal variance: a fan shape, with residuals close to 0 on the left and spread out on the right.

When the conditions are not met, the estimates, p-values, and intervals may not be trustworthy. Sometimes a transformation helps.

Brain and body weight of mammals

ggplot(mammals, aes(x = body_wt, y = brain_wt)) +
  geom_point()
Scatterplot of brain weight in grams against body weight in kilograms for 62 mammals. Almost all points are crowded in the bottom left corner; two points (the elephants) are far to the right and far up, near 2,500 to 6,700 kilograms and 4,600 to 5,700 grams.

Data: mammals in the openintro package: 62 mammal species; body weight (kg) and brain weight (g).

A linear model on the original scale

Two plots for the model of brain weight on body weight. Left: the scatterplot with the least squares line; the line is pulled by the two elephants and misses most of the small mammals. Right: the residual vs fitted plot; most points are crowded at the left near 0, a few are spread widely, and the spread grows with the fitted values.

Exercise

Which conditions do not look reasonable?

Log transformation

When a variable is right-skewed (a few very large values), taking its log spreads out the small values and pulls in the large ones. log() in R is the natural log.

mammals <- mammals |>
  mutate(log_body = log(body_wt),
         log_brain = log(brain_wt))
Two histograms of mammal body weight. Left, on the original scale: extremely right skewed, with almost all values in the first bar. Right, the log of body weight: roughly symmetric, from about -5 to 9.

A linear model on the log scale

model_log <- lm(log_brain ~ log_body, data = mammals)
Two plots for the model of log brain weight on log body weight. Left: a strong linear relationship with the least squares line going through the middle of the points. Right: the residual vs fitted plot is a shapeless cloud around 0 with similar spread from left to right.

Much better!

Predicting on the log scale

tidy(model_log)
# A tibble: 2 × 5
  term        estimate std.error statistic  p.value
  <chr>          <dbl>     <dbl>     <dbl>    <dbl>
1 (Intercept)    2.13     0.0960      22.2 1.18e-30
2 log_body       0.752    0.0285      26.4 9.84e-35

\[\widehat{\log(\text{brain})} = 2.13 + 0.75 \times \log(\text{body})\]

On the log scale: as the log of body weight increases by 1 unit, the log of brain weight is expected to increase by 0.75 units.

But nobody thinks in “log kilograms” or “log grams”! Let’s go back to kilograms and grams.

Undoing the logs

Start from \(\log(\text{brain}) = 2.13 + 0.75 \times \log(\text{body})\). Raise \(e\) to the power of both sides. Since \(e^{\log(a)} = a\):

\[\text{brain} = e^{2.13 + 0.75 \times \log(\text{body})}\]

Since \(e^{a + b} = e^{a} \times e^{b}\):

\[\text{brain} = e^{2.13} \times e^{0.75 \times \log(\text{body})}\]

Since \(e^{2.13} \approx 8.4\) and \(e^{c \times \log(a)} = a^{c}\):

\[\text{brain} = 8.4 \times \text{body}^{0.75}\]

Back to grams and kilograms

\[\widehat{\text{brain}} = 8.4 \times \text{body}^{0.75}\]

Scatterplot of brain weight in grams against body weight in kilograms for the 62 mammals, with the curve brain = 8.4 times body to the power 0.75. The curve rises steeply at first and then more slowly. It passes close to most mammals and to the largest elephant, at about 6,700 kilograms, and well below the other elephant, at about 2,500 kilograms and 4,600 grams.

On the original scale, this is a curve, not a line. So “one more kilogram” does not always mean the same change in grams. Instead, we think in multiplying: if body weight doubles, the expected brain weight is multiplied by \(2^{0.75} \approx 1.68\), so it is about 68% heavier.

Prediction: a man

The man in the data (listed as “Man”) weighs 62 kg.

\[\widehat{\text{brain}} = 8.4 \times 62^{0.75} \approx 186 \text{ grams}\]

The man’s actual brain weighs 1,320 grams. The residual is

\[e = y - \hat{y} = 1,320 - 186 = 1,134 \text{ grams}\]

The man’s residual

Scatterplot of brain weight in grams against body weight in kilograms for mammals up to 300 kilograms, with the curve brain = 8.4 times body to the power 0.75. Most mammals are close to the curve. The man, labeled and shown as a large pink point at 62 kilograms and 1,320 grams, is far above the curve. A dashed pink segment connects the man to the curve at about 186 grams.

The residual is positive and large: men have a much bigger brain than expected for a mammal of their size.

Zoomed in to mammals up to 300 kg.

Prediction in R: the log scale

predict() (from the {stats} package, which comes with R) plugs new values of \(x\) into a fitted model.

  • newdata is a data frame with the new \(x\) values. Its column must have the same name as the explanatory variable in the model: here log_body, so we give it log(62).
predict(model_log, newdata = tibble(log_body = log(62)))
       1 
5.237098 

The model’s response is log_brain, so this is the prediction on the log scale: \(\widehat{\log(\text{brain})} \approx 5.24\).

Prediction in R: back to grams

exp() undoes log() and takes us back to grams:

predict(model_log, newdata = tibble(log_body = log(62))) |>
  exp()
       1 
188.1233 

188 instead of 186: R uses the unrounded estimates (2.1348 and 0.7517), while we rounded them to 2.13 and 0.75.

How accurate are the predictions?

Correlation

The correlation, \(r\), measures the strength and direction of the linear relationship between two numerical variables. It is always between \(-1\) and \(1\).

Five simulated scatterplots with correlations -0.9, -0.5, 0, 0.5, and 0.9. At -0.9 the points fall tightly around a downward line; at -0.5 the downward trend is loose; at 0 there is no trend; at 0.5 the upward trend is loose; at 0.9 the points fall tightly around an upward line.
  • The sign gives the direction (positive or negative).
  • The closer to \(-1\) or \(1\), the stronger. \(r = 0\): no linear relationship.

Correlation in R

cor(babies$gestation, babies$bwt, use = "complete.obs")
[1] 0.407854

gestation has some missing values. cor() does not have na.rm; use = "complete.obs" tells it to use only the babies with no missing values.

Careful

A correlation near 0 does not mean there is no relationship: there could be a strong curved relationship. Correlation only measures linear relationships. Always plot the data!

Where do b₀ and b₁ come from?

The least squares estimates (the ones lm() gives) can be calculated from five summary statistics:

\[b_1 = r \times \frac{s_y}{s_x} \qquad\qquad b_0 = \bar{y} - b_1 \bar{x}\]

babies |>
  summarize(mean_x = mean(gestation, na.rm = TRUE), sd_x = sd(gestation, na.rm = TRUE),
            mean_y = mean(bwt, na.rm = TRUE), sd_y = sd(bwt, na.rm = TRUE))
# A tibble: 1 × 4
  mean_x  sd_x mean_y  sd_y
   <dbl> <dbl>  <dbl> <dbl>
1   279.  16.0   120.  18.2

Calculating b₀ and b₁

\[b_1 = r \times \frac{s_y}{s_x} = 0.408 \times \frac{18.24}{16.03} = 0.464\]

\[b_0 = \bar{y} - b_1 \bar{x} = 119.58 - 0.4641 \times 279.34 = -10.1\]

These are the estimates from tidy(model_g) last week: \(b_0 = -10.1\) and \(b_1 = 0.464\).

What these formulas tell us

\[b_1 = r \times \frac{s_y}{s_x} \qquad\qquad b_0 = \bar{y} - b_1 \bar{x}\]

  • Standard deviations are always positive, so the slope has the same sign as the correlation.
  • Rearranging the second formula, \(\bar{y} = b_0 + b_1 \bar{x}\): the line always goes through the point \((\bar{x}, \bar{y})\).

Residuals measure prediction error

Each residual \(e_i = y_i - \hat{y}_i\) is a prediction error. Root mean squared error (RMSE): square the residuals, take the mean, then the square root.

\[\text{RMSE} = \sqrt{\frac{1}{n}\sum e_i^2}\]

model_g_aug |>
  summarize(rmse = sqrt(mean(.resid^2)))
# A tibble: 1 × 1
   rmse
  <dbl>
1  16.7

Our predictions of birth weight are typically off by about 16.7 ounces. RMSE is in the units of \(y\).

Variability in birth weight

Two plots of birth weight against gestation for 60 randomly chosen babies. Left, labeled total variability: a horizontal line at the mean birth weight with vertical segments from each point to it. Right, labeled left over after the model: the regression line with vertical segments from each point to the line. The segments on the right are only a little shorter than on the left.
  • Left: each pink segment is \(y_i - \bar{y}\), how far a baby is from the mean birth weight. This is the variability if we do not use gestation.
  • Right: each pink segment is the residual \(e_i = y_i - \hat{y}_i\), how far a baby is from the line. This is the variability left over after using gestation.

What do the two plots tell us?

Conclusion

The segments around the line (right) are only a little shorter than the segments around the mean (left). Gestation explains some of the variability in birth weight, but most of it is left over.

With all 1,223 babies, square each segment and add them up:

  • around the mean: \(\sum (y_i - \bar{y})^2\) = 406,753
  • around the line: \(\sum e_i^2\) = 339,092, which is 83% of the total.

The model explains the other 17%. This is \(R^2\).

R²

\[R^2 = 1 - \frac{\text{variability left over (around the line)}}{\text{total variability (around the mean)}} = 1 - \frac{\sum (y_i - \hat{y}_i)^2}{\sum (y_i - \bar{y})^2}\]

glance(model_g) |>  # glance() from {broom}: one-row model summaries
  select(r.squared)
# A tibble: 1 × 1
  r.squared
      <dbl>
1     0.166

Interpretation: 16.6% of the variability in birth weight is explained by gestation (with a linear model). For simple linear regression, \(R^2 = r^2\): \(0.408^2 = 0.166\).

R² is between 0 and 1

Exercise

  1. What would \(R^2 = 0\) mean? What would \(R^2 = 1\) mean?
  2. Only 17% of the variability in birth weight is explained by gestation. Name some other variables that could explain the rest.
  3. Is a model with a low \(R^2\) useless? Last Monday, the slope of gestation had a tiny p-value.

“Explains” does not mean “causes”

Gestation explains about 17% of the variability in birth weight. This does not mean that gestation causes birth weight.

  • babies is an observational study: nobody assigned the length of pregnancy.
  • Other variables, like the mother’s health or smoking, could be related to both gestation and birth weight.
  • Even a large \(R^2\) would not change this: \(R^2\) describes an association, not a cause.

From this model alone, we cannot conclude causation.

An average baby vs. a single baby

\(\hat{y} = -10.1 + 0.464 \times 280 \approx 120\) ounces is the expected (average) birth weight of babies born after 280 days. A single baby born after 280 days could weigh quite a bit more or less.

new_baby <- tibble(gestation = 280)
predict(model_g, newdata = new_baby, interval = "confidence")
       fit      lwr     upr
1 119.9293 118.9936 120.865
predict(model_g, newdata = new_baby, interval = "prediction")
       fit      lwr      upr
1 119.9293 87.22107 152.6376

We saw predict() with the mammals model. With interval =, it also gives an interval.

Confidence vs. prediction intervals

  • 95% confidence interval (119.0 to 120.9 oz): for the average birth weight of all babies born after 280 days.
  • 95% prediction interval (87.2 to 152.6 oz): for the birth weight of one baby born after 280 days. It is much wider because single babies vary around the line.
Scatterplot of birth weight against gestation with the regression line. A narrow dark green band around the line shows the 95% confidence intervals for the average birth weight. A much wider light pink band with dashed pink edges shows the 95% prediction intervals for a single baby; it covers most of the points. The bands are labeled confidence, the average, and prediction, one baby.

More than one explanatory variable

Back to the babies

Earlier today, gestation explained only about 17% of the variability in birth weight.

Last week, we also saw that babies of mothers who smoked weighed about 8.9 ounces less, on average.

Can we use both gestation and smoking in one model?

Multiple linear regression

\[y_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + \dots + \beta_k x_{ki} + \epsilon_i\]

  • \(k\) explanatory variables: \(x_1, x_2, \dots, x_k\)
  • one slope for each explanatory variable

For birth weight:

\[\text{bwt}_i = \beta_0 + \beta_1 \text{gestation}_i + \beta_2 \text{smoke}_i + \epsilon_i\]

Missing values

Some babies are missing some variables. Today we compare models with different variables, so every model should use the same babies.

babies <- babies |>
  drop_na()

drop_na() from the {tidyr} package (part of the tidyverse) keeps only the rows with no missing values. 1,174 of the 1,236 babies are left.

Fitting the model

In R, we add explanatory variables with +.

model_gs <- lm(bwt ~ gestation + smoke, data = babies)
tidy(model_gs)
# A tibble: 3 × 5
  term        estimate std.error statistic  p.value
  <chr>          <dbl>     <dbl>     <dbl>    <dbl>
1 (Intercept)   -3.18     8.33      -0.382 7.02e- 1
2 gestation      0.451    0.0297    15.2   9.31e-48
3 smoke         -8.37     0.973     -8.60  2.47e-17

\[\widehat{\text{bwt}} = -3.18 + 0.451 \times \text{gestation} - 8.37 \times \text{smoke}\]

Two parallel lines

smoke is 0 or 1, so the model is two lines with the same slope:

  • Did not smoke (smoke = 0): \(\widehat{\text{bwt}} = -3.18 + 0.451 \times \text{gestation}\)
  • Smoked (smoke = 1): \(\widehat{\text{bwt}} = (-3.18 - 8.37) + 0.451 \times \text{gestation}\)
Scatterplot of birth weight against gestation, with points colored by whether the mother smoked. Babies of mothers who did not smoke are green dots; babies of mothers who smoked are pink crosses. Two parallel lines are drawn and labeled; the solid green line for mothers who did not smoke is about 8.37 ounces above the dashed pink line for mothers who smoked.

Interpreting the slopes

Each slope is interpreted holding the other variables constant.

  • gestation: for babies whose mothers have the same smoking status, each additional day of gestation is associated with 0.451 ounces higher birth weight, on average.
  • smoke: for babies with the same gestation, babies of mothers who smoked are expected to weigh 8.37 ounces less, on average, than babies of mothers who did not smoke.

Your turn

Exercise

\[\widehat{\text{bwt}} = -3.18 + 0.451 \times \text{gestation} - 8.37 \times \text{smoke}\]

Predict the birth weight of a baby born after 280 days whose mother

  1. did not smoke.
  2. smoked.
  3. What is the difference between (a) and (b)? Where is it in the model?

The smoking slope changed

Slope of smoke with and without gestation in the model
Model Slope of smoke
bwt ~ smoke -9.27
bwt ~ gestation + smoke -8.37

Both models are fit to the same 1,174 babies (after drop_na()), so the first slope is a little different from last week’s.

Discussion

Why might the slope of smoke change when gestation is in the model? (Hint: do mothers who smoke tend to have shorter or longer pregnancies?)

Inference for each slope

confint(model_gs)
                  2.5 %    97.5 %
(Intercept) -19.5272245 13.157392
gestation     0.3929318  0.509404
smoke       -10.2843204 -6.464478

Exercise

Interpret the 95% confidence interval for the slope of smoke. Is there convincing evidence that smoking is associated with birth weight, after taking gestation into account?

Still not causal

“Holding gestation constant” sounds like an experiment, but it is not one.

  • babies is still an observational study: nobody assigned mothers to smoke or not.
  • Adding gestation to the model accounts for one other variable. Mothers who smoked and mothers who did not could still differ in many ways that are not in the model.

So we can say smoking is associated with lower birth weight, after taking gestation into account. From this model alone, we cannot conclude that smoking causes lower birth weight.

How many variables?

More explanatory variables

model_all <- lm(bwt ~ gestation + smoke + parity + age + height + weight,
                data = babies)
tidy(model_all)
# A tibble: 7 × 5
  term         estimate std.error statistic  p.value
  <chr>           <dbl>     <dbl>     <dbl>    <dbl>
1 (Intercept) -80.4       14.3       -5.60  2.60e- 8
2 gestation     0.444      0.0291    15.3   4.57e-48
3 smoke        -8.40       0.954     -8.81  4.54e-18
4 parity       -3.33       1.13      -2.95  3.27e- 3
5 age          -0.00895    0.0858    -0.104 9.17e- 1
6 height        1.15       0.205      5.63  2.27e- 8
7 weight        0.0502     0.0252     1.99  4.71e- 2

parity: 0 for a first pregnancy, 1 otherwise. age: mother’s age (years). height: mother’s height (inches). weight: mother’s pre-pregnancy weight (pounds).

Interpreting the six-variable model

Exercise

  1. Interpret the slope of height (1.154) in context.
  2. Which variable does not seem to be associated with birth weight, after taking the others into account?

R² never goes down

R-squared for four models of birth weight
Explanatory variables R²
gestation 0.166
gestation + smoke 0.216
all six variables 0.258
all six + random 0.259

random is a column of simulated random numbers: mutate(random = rnorm(n())). It has nothing to do with birth weight, but \(R^2\) still went up!

Adding a variable can never make \(R^2\) smaller. So \(R^2\) cannot tell us whether a variable is worth adding.

Adjusted R²

Adjusted \(R^2\) has a penalty for each of the \(k\) explanatory variables (\(n\): number of observations):

\[R^2_{adj} = 1 - \frac{\sum (y_i - \hat{y}_i)^2 / (n - k - 1)}{\sum (y_i - \bar{y})^2 / (n - 1)}\]

glance(model_all) |>
  select(r.squared, adj.r.squared)
# A tibble: 1 × 2
  r.squared adj.r.squared
      <dbl>         <dbl>
1     0.258         0.254

It goes up only if a new variable helps more than we would expect by chance. Use it to compare models.

R² vs. adjusted R²

R-squared and adjusted R-squared for four models of birth weight
Explanatory variables R² Adjusted R²
gestation 0.166 0.165
gestation + smoke 0.216 0.214
all six variables 0.258 0.254
all six + random 0.259 0.254

RMSE

Remember RMSE (root mean squared error) from earlier today: the typical size of a residual, \(e_i = y_i - \hat{y}_i\).

  1. Square each residual (so negative and positive errors do not cancel out).
  2. Take the mean of the squared residuals.
  3. Take the square root (to get back to the units of \(y\)).

\[\text{RMSE} = \sqrt{\frac{1}{n}\sum e_i^2}\]

RMSE of the six-variable model

augment(model_all) |>
  summarize(rmse = sqrt(mean(.resid^2)))
# A tibble: 1 × 1
   rmse
  <dbl>
1  15.8

The six-variable model’s predictions are typically off by about 15.8 ounces. A smaller RMSE means predictions closer to the observed birth weights.

Comparing the models

Adjusted R-squared and RMSE for four models of birth weight
Explanatory variables Adjusted R² RMSE (oz)
gestation 0.165 16.73
gestation + smoke 0.214 16.23
all six variables 0.254 15.78
all six + random 0.254 15.77

Adjusted \(R^2\): higher is better. RMSE: lower is better. Adding random did not change adjusted \(R^2\), and RMSE went down by only 0.008 ounces.

Occam’s razor

Among models that explain the data about equally well, choose the simpler one.

This principle of parsimony is called Occam’s razor, after William of Ockham, a 14th-century philosopher.

Why prefer a simpler model?

  • It is easier to interpret and explain.
  • To predict for a new baby, we need to collect fewer variables.
  • It is less likely to be overfit.

Which model would you choose?

Adjusted R-squared and RMSE for three models of birth weight
Explanatory variables Adjusted R² RMSE (oz)
gestation + smoke 0.214 16.23
all six variables 0.254 15.78
all six + random 0.254 15.77

Discussion

Using adjusted \(R^2\), RMSE, and Occam’s razor, which model would you choose? Are the extra variables worth collecting? Does it depend on what the model is for?

Training and testing

Why do we fit models?

Often, to make predictions for new data: babies who are not in our data yet.

So far, we evaluated each model on the same data we used to fit it. That is like a clothing store checking whether a jacket fits… on the model it was tailored for.

A jacket made for its models

Illustration of 3 male looking models on a runway in exact same jacket, belt, pants, and shoes.

Training: fits perfectly.

The same jacket and pants worn by three different people with very different body types. The middle figure is tall, hence the jacket arms and pants legs are too short for them, the righ figure is short and the jacket arms and pants legs are too large for them.

Testing: new people, not a good fit.

Overfitting: the 15 babies

We fit two models to 15 babies: a straight line and a very wiggly curve.

Two scatterplots of the same 15 babies, birth weight against gestation. On the left, a straight line through the points. On the right, a wiggly curve that goes up and down to pass close to almost every point. The training RMSE is 12.2 ounces for the line and 5.0 ounces for the wiggly curve.

Which model looks better?

Overfitting: new babies

Now we use both models to predict the other 947 babies (in the same range of gestation).

The same two models drawn over all the other babies, shown as gray points. The straight line goes through the middle of the gray cloud. The wiggly curve swings far above and below the cloud. The testing RMSE is 17.1 ounces for the line and 43.5 ounces for the wiggly curve.

The wiggly model learned the noise in its 15 babies, not the pattern. It is overfit.

In practice: split the data first

Today, we used all the babies to learn one tool at a time. In a real analysis, this is where we would have begun:

  1. First, before fitting any model: randomly split the data into training (often 80%) and testing (20%) data. Put the testing data aside.
  2. Use only the training data to fit, check, and compare models (residual plots, adjusted \(R^2\), RMSE, Occam’s razor).
  3. At the end, check the chosen model on the testing data.

The testing data play the role of new babies that the model has never seen.

Step 1: split the data

initial_split(), training(), and testing() are from the {rsample} package (part of the tidymodels family, which works well with the tidyverse).

set.seed(84735)
babies_split <- initial_split(babies, prop = 0.8)
babies_train <- training(babies_split)
babies_test <- testing(babies_split)

939 babies for training and 235 babies for testing.

Steps 2 and 3: fit on training, check on testing

model_train <- lm(bwt ~ gestation + smoke, data = babies_train)

babies_test |>
  mutate(prediction = predict(model_train, newdata = babies_test)) |>
  summarize(test_rmse = sqrt(mean((bwt - prediction)^2)))
# A tibble: 1 × 1
  test_rmse
      <dbl>
1      15.9

predict() from earlier today: here newdata is the whole testing data.

Comparing models on testing data

Training and testing RMSE (ounces) for three models of birth weight
Explanatory variables Training RMSE Testing RMSE
gestation 16.85 16.24
gestation + smoke 16.30 15.94
all six variables 15.78 15.81

Exercise

Which model predicts new babies best? Do the extra variables lead to overfitting here? Does this change which model you would choose with Occam’s razor?

Cross-validation

Note

With one split, the result depends on which rows happened to land in the testing data. Cross-validation repeats the split many times (each row gets a turn in the testing data) and averages the results. You will see it in more advanced classes.

Summary

  • Evaluate a model: how fair, how wrong, how accurate?
  • LINE: Linearity, Independence, Normality, Equal variance. Think about independence (clusters, time); check the rest with residual plots of \(e_i\) against \(\hat{y}_i\). A log transformation can help with right-skewed variables.
  • Correlation \(r\): strength and direction of a linear relationship. \(R^2\): the proportion of the variability in \(y\) explained by the model; an association, not causation.
  • Average \(y\) (confidence interval) vs. single \(y\) (prediction interval).
  • Multiple linear regression: lm(y ~ x1 + x2, ...). Each slope is interpreted holding the other variables constant; still not causal.
  • Compare models with adjusted \(R^2\) (higher is better) and RMSE, the typical size of a residual (lower is better). Occam’s razor: prefer the simpler model when two do about equally well.
  • In a real analysis, first split the data into training and testing data, build the model on the training data, and check it on the testing data at the end.