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.
All models are wrong, but some are useful. (George Box)
To evaluate a model, we ask:
These three questions come from Johnson, Ott, & Dogucu (2022), Bayes Rules!, Chapter 10. They work for both frequentist and Bayesian models.
These questions are not answered with R code. They are answered by thinking about the context.
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.
\[Y_i = \beta_0 + \beta_1 X_i + \epsilon_i \qquad \epsilon_i \sim N(0, \sigma^2)\]
The model makes four assumptions (LINE):
On Wednesday, we will see that Bayesian regression makes the same assumptions.
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:
Independence is about how the data were collected. We check it by thinking, not with a plot.
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?
For each observation \(i\):
augment() from the {broom} package adds both to the data: .fitted is \(\hat{y}_i\) and .resid is \(e_i\).
# 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.
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).
We want it to look roughly Normal: unimodal, symmetric, centered at 0.
When the conditions are not met, the estimates, p-values, and intervals may not be trustworthy. Sometimes a transformation helps.
Data: mammals in the openintro package: 62 mammal species; body weight (kg) and brain weight (g).
Exercise
Which conditions do not look reasonable?
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.
Much better!
# 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.
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}\]
\[\widehat{\text{brain}} = 8.4 \times \text{body}^{0.75}\]
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.
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 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.
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).exp() undoes log() and takes us back to grams:
188 instead of 186: R uses the unrounded estimates (2.1348 and 0.7517), while we rounded them to 2.13 and 0.75.
The correlation, \(r\), measures the strength and direction of the linear relationship between two numerical variables. It is always between \(-1\) and \(1\).
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!
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}\]
\[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\).
\[b_1 = r \times \frac{s_y}{s_x} \qquad\qquad b_0 = \bar{y} - b_1 \bar{x}\]
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}\]
Our predictions of birth weight are typically off by about 16.7 ounces. RMSE is in the units of \(y\).
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:
The model explains the other 17%. This is \(R^2\).
\[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}\]
# 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\).
Exercise
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.From this model alone, we cannot conclude causation.
\(\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.
fit lwr upr
1 119.9293 118.9936 120.865
fit lwr upr
1 119.9293 87.22107 152.6376
We saw predict() with the mammals model. With interval =, it also gives an interval.
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?
\[y_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + \dots + \beta_k x_{ki} + \epsilon_i\]
For birth weight:
\[\text{bwt}_i = \beta_0 + \beta_1 \text{gestation}_i + \beta_2 \text{smoke}_i + \epsilon_i\]
Some babies are missing some variables. Today we compare models with different variables, so every model should use the same babies.
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.
In R, we add explanatory variables with +.
# 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}\]
smoke is 0 or 1, so the model is two lines with the same slope:
Each slope is interpreted holding the other variables constant.
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
| 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?)
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?
“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.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.
# 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).
Exercise
height (1.154) in context.| 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^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)}\]
# 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.
| 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 |
Remember RMSE (root mean squared error) from earlier today: the typical size of a residual, \(e_i = y_i - \hat{y}_i\).
\[\text{RMSE} = \sqrt{\frac{1}{n}\sum e_i^2}\]
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.
| 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.
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?
| 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?
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.

Training: fits perfectly.

Testing: new people, not a good fit.
We fit two models to 15 babies: a straight line and a very wiggly curve.
Which model looks better?
Now we use both models to predict the other 947 babies (in the same range of gestation).
The wiggly model learned the noise in its 15 babies, not the pattern. It is overfit.
Today, we used all the babies to learn one tool at a time. In a real analysis, this is where we would have begun:
The testing data play the role of new babies that the model has never seen.
initial_split(), training(), and testing() are from the {rsample} package (part of the tidymodels family, which works well with the tidyverse).
939 babies for training and 235 babies for testing.
# A tibble: 1 × 1
test_rmse
<dbl>
1 15.9
predict() from earlier today: here newdata is the whole testing data.
| 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?
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.
lm(y ~ x1 + x2, ...). Each slope is interpreted holding the other variables constant; still not causal.