Extra Practice: Prediction Concepts and Applications
Each group below is a set of practice problems.
I recommend looking at the concept questions before the case studies, which are very in depth.
Click a case study to open it. Some case studies are meant for pen and paper (a calculator is fine, but no code); the others use code: you can also download the .csv files and play with the code and data in rstudio.
The case studies come in two families that follow the same steps: fuel consumption (a regression problem) and defective parts (a classification problem, using logistic regression).
N.B. We had to use the dplyr function pull() below. That’s because we had to “pull” a plain number out of a dataframe and reuse it later. You will never have to know, or use this function. Because we didn’t learn it in the class, if you use it on an exam question, you risk getting a 0 on that question.
All libraries and datasets have already been loaded for you.
This whole case study is meant for pen and paper. You can use a calculator, but no code.
A delivery company recorded the fuel consumption of some of its vehicles, along with a few characteristics of each trip. The company wants to predict the fuel consumption of the next vehicle. The variables are:
| Variable | Meaning | Units of measurement |
|---|---|---|
| \(Y\) | fuel consumption (the target) | liters per 100 kilometers (L/100 km) |
| \(X_1\) | steady driving speed | kilometers per hour (km/h) |
| \(X_2\) | vehicle mass | kilograms (kg) |
| \(X_3\) | outside temperature | degrees Celsius (°C) |
Here is the training set, with 6 vehicles:
| Vehicle | \(Y\) (L/100 km) | \(X_1\) (km/h) | \(X_2\) (kg) | \(X_3\) (°C) |
|---|---|---|---|---|
| 1 | 9 | 50 | 1300 | 20 |
| 2 | 15 | 115 | 1800 | 5 |
| 3 | 6 | 75 | 1100 | 18 |
| 4 | 13 | 35 | 1700 | 12 |
| 5 | 7 | 65 | 1200 | 22 |
| 6 | 10 | 100 | 1450 | 15 |
Q1 Suppose you didn’t have any features available (no \(X_1\), \(X_2\), \(X_3\)), only the six values of \(Y\) above. What would be your best procedure to create a prediction for the next value of \(Y\)? What prediction does it give? Can you think of a second, different procedure?
Show answer
With no features, the best we can do is predict the same number for every new vehicle, the typical value of \(Y\). A natural choice is the sample mean:
\[\hat{Y} = \bar{Y} = \frac{9 + 15 + 6 + 13 + 7 + 10}{6} = \frac{60}{6} = 10 \text{ L/100 km}\]
A second, equally reasonable procedure is the sample median, \(\tilde{Y}\). Sorting the data gives 6, 7, 9, 10, 13, 15, so the median is the average of the two middle values:
\[\hat{Y} = \tilde{Y} = \frac{9 + 10}{2} = 9.5 \text{ L/100 km}\]
We will call these Model A (predict \(\bar{Y}\)) and Model B (predict \(\tilde{Y}\)). Both ignore the features completely.
Q2 Sketch, on paper, the training data together with the predictions of the two models. Put \(Y\) on the vertical axis. (There is no \(X\) here, since the models don’t use any features.)
Show answer
The data are just a column of six points on a single vertical axis. Each model’s prediction is a flat (horizontal) line, since it predicts the same value no matter what: one at 10 for the mean and one at 9.5 for the median. The two lines are almost on top of each other.

Q3 Compute the MSE of the two models on the training set. What are the units of measurement of the MSE?
Show answer
The MSE is the average of the squared errors (error = \(Y\) minus the prediction).
| \(Y\) | \(Y - \bar{Y}\) | \((Y - \bar{Y})^2\) | \(Y - \tilde{Y}\) | \((Y - \tilde{Y})^2\) |
|---|---|---|---|---|
| 9 | −1 | 1 | −0.5 | 0.25 |
| 15 | 5 | 25 | 5.5 | 30.25 |
| 6 | −4 | 16 | −3.5 | 12.25 |
| 13 | 3 | 9 | 3.5 | 12.25 |
| 7 | −3 | 9 | −2.5 | 6.25 |
| 10 | 0 | 0 | 0.5 | 0.25 |
| Sum | 60 | 61.5 |
\[\text{MSE}_A = \frac{60}{6} = 10 \qquad \text{MSE}_B = \frac{61.5}{6} = 10.25\]
Since we square the errors, we also square the units: the MSE is measured in (L/100 km)², liters per 100 kilometers, squared.
Q4 Looking at the MSEs: would this level of error be acceptable in real life?
Show answer
It’s very hard to say. An MSE of 10 (L/100 km)² is not a quantity we have any feeling for: what is a “squared liter per 100 km”? We can’t compare it with the size of a typical vehicle’s consumption, so we can’t tell whether an error of this size is a problem or not.
Q5 Now compute the RMSE of the two models, with units. Is this level of error acceptable in real life?
Show answer
\[\text{RMSE}_A = \sqrt{10} \approx 3.16 \text{ L/100 km} \qquad \text{RMSE}_B = \sqrt{10.25} \approx 3.20 \text{ L/100 km}\]
Now we can reason about it: on average, the predictions are off by roughly 3 L/100 km. The average vehicle consumes about 10 L/100 km, so that’s an error of around 30%. If the company wants to budget for fuel, that is probably too much. If it only wants a very rough idea of which vehicles are thirsty, it might be fine. Whether an error is acceptable always depends on the application, but at least now we can have that conversation.
Q6 When thinking about errors in real life, is it easier for you to think about the MSE or the RMSE? Why?
Show answer
The RMSE. It has the same units as \(Y\) (L/100 km here), so it can be read directly as “a typical size of the prediction error” and compared with the values of \(Y\) themselves. The MSE is in squared units, which have no direct real-life meaning, so it is mostly useful as a mathematical tool because it is more mathematically well behaved and simple than other metrics.
Q7 Are the MSEs or RMSEs you computed enough to decide whether Model A (\(\bar{Y}\)) or Model B (\(\tilde{Y}\)) is better?
Show answer
No. These are training errors: we measured them on the very same data that we used to build the models, so it’s dangerous to draw conclusions from them.
To compare models fairly, we need to evaluate them on new data that neither model has seen: a test set.
Q8 Here is a test set of 4 new vehicles:
| Vehicle | \(Y\) (L/100 km) | \(X_1\) (km/h) | \(X_2\) (kg) | \(X_3\) (°C) |
|---|---|---|---|---|
| 7 | 7 | 70 | 1250 | 20 |
| 8 | 8 | 60 | 1350 | 16 |
| 9 | 9 | 90 | 1400 | 14 |
| 10 | 10 | 45 | 1500 | 19 |
Compute the RMSE of Model A and Model B on this test set (use the predictions you computed from the training set), and draw conclusions.
Show answer
The predictions are still 10 and 9.5, because the models were built on the training set only. We never recompute the mean or median on the test set.
| \(Y\) | \(Y - 10\) | \((Y - 10)^2\) | \(Y - 9.5\) | \((Y - 9.5)^2\) |
|---|---|---|---|---|
| 7 | −3 | 9 | −2.5 | 6.25 |
| 8 | −2 | 4 | −1.5 | 2.25 |
| 9 | −1 | 1 | −0.5 | 0.25 |
| 10 | 0 | 0 | 0.5 | 0.25 |
| Sum | 14 | 9 |
\[\text{RMSE}_A = \sqrt{\frac{14}{4}} = \sqrt{3.5} \approx 1.87 \text{ L/100 km} \qquad \text{RMSE}_B = \sqrt{\frac{9}{4}} = 1.5 \text{ L/100 km}\]
Conclusions. On the test set, Model B (the median) does better, the opposite of what the training set suggested: this is exactly why the training error was not enough to choose between them. But we should not get carried away: the test set has only 4 vehicles, and the difference between the two models (about 0.4 L/100 km) is small, so this could easily be luck. Overall, the two models are basically equally good (and equally simple, since neither uses the features). We would want a much larger test set, to really decide between the two, which is what the next case study uses.
We go back to the fuel consumption data, but this time with much more data: a training set of 80 vehicles and a test set of 60 vehicles.
Dataframe names: train and test
Target variable: Y, the fuel consumption in liters per 100 kilometers (L/100 km).
Features: X_1 (speed, km/h), X_2 (vehicle mass, kg), X_3 (outside temperature, °C), X_4 (driver age, years).
The first few rows of train:
| Y | X_1 | X_2 | X_3 | X_4 |
|---|---|---|---|---|
| 8.0 | 86 | 1120 | -1 | 69 |
| 9.1 | 75 | 1950 | 13 | 47 |
| 13.3 | 41 | 1780 | 28 | 69 |
| 12.2 | 53 | 1960 | -1 | 61 |
| 5.5 | 74 | 1110 | -1 | 50 |
| 19.6 | 32 | 1980 | 8 | 46 |
In this case study we will only use the two baseline models from part 1, which ignore the features: Model A predicts the training mean \(\bar{Y}\), and Model B predicts the training median \(\tilde{Y}\).
Want to work in RStudio instead? Download the datasets, fuel_train.csv and fuel_test.csv, put them in your working directory, and load them with:
library(dplyr)
library(ggplot2)
library(patchwork)
train <- read.csv("fuel_train.csv")
test <- read.csv("fuel_test.csv")Reminder: all datasets and libraries are already loaded for you.
Q1 Write a pipeline to add two columns, Y_hat_mean and Y_hat_median, with the predictions of the two models, to both train and test.
Hint: remember that the models are built using only the training set.
Show answer
Y_bar <- train |> summarize(Y_bar = mean(Y)) |> pull(Y_bar)
Y_tilde <- train |> summarize(Y_tilde = median(Y)) |> pull(Y_tilde)
train <- train |>
mutate(Y_hat_mean = Y_bar, Y_hat_median = Y_tilde)
# The test set gets the SAME numbers: the mean and median of the training set.
# (Using the test set's own mean would mean peeking at the answers.)
test <- test |>
mutate(Y_hat_mean = Y_bar, Y_hat_median = Y_tilde)
head(train)# A tibble: 6 × 7
Y X_1 X_2 X_3 X_4 Y_hat_mean Y_hat_median
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 8 86 1120 -1 69 10.5 9.5
2 9.1 75 1950 13 47 10.5 9.5
3 13.3 41 1780 28 69 10.5 9.5
4 12.2 53 1960 -1 61 10.5 9.5
5 5.5 74 1110 -1 50 10.5 9.5
6 19.6 32 1980 8 46 10.5 9.5
head(test)# A tibble: 6 × 7
Y X_1 X_2 X_3 X_4 Y_hat_mean Y_hat_median
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 8.7 78 1640 10 21 10.5 9.5
2 7.3 71 1770 17 38 10.5 9.5
3 5.9 74 1400 10 45 10.5 9.5
4 8 65 1830 19 29 10.5 9.5
5 14.3 101 1440 2 30 10.5 9.5
6 12.9 100 1250 1 40 10.5 9.5
Q2 Visualize both datasets together with the predictions of the two models. Put Y on the vertical axis (there is no feature on the horizontal axis), and show the data as points and the two models as flat lines.
Hint: ggplot(d, aes(x = "", y = Y)) + geom_jitter(width = 0.1, height = 0) draws the points of a dataset d on a vertical axis, and geom_hline(yintercept = ...) adds a flat line. With the patchwork package, p1 + p2 puts two plots p1 and p2 side by side.
Show answer
p_train <- ggplot(train, aes(x = "", y = Y)) +
geom_jitter(width = 0.1, height = 0) +
geom_hline(yintercept = Y_bar, color = "blue", linewidth = 1) +
geom_hline(yintercept = Y_tilde, color = "red", linewidth = 1, linetype = "dashed") +
labs(x = NULL, y = "Y (L/100 km)", title = "train",
subtitle = "blue: mean, red dashed: median")
p_test <- ggplot(test, aes(x = "", y = Y)) +
geom_jitter(width = 0.1, height = 0) +
geom_hline(yintercept = Y_bar, color = "blue", linewidth = 1) +
geom_hline(yintercept = Y_tilde, color = "red", linewidth = 1, linetype = "dashed") +
labs(x = NULL, y = "Y (L/100 km)", title = "test",
subtitle = "blue: mean, red dashed: median")
p_train + p_test
The two lines are almost on top of each other. Neither model gets close to the points that are far from the center.
Q3 Write a pipeline to compute the MSE and RMSE of the two models, on both the training set and the test set.
Hint: if you haven’t written a function before, you can just copy and paste the pipeline once for each dataset.
Show answer
# Training set
train |>
summarize(
MSE_mean = mean((Y - Y_hat_mean)^2),
MSE_median = mean((Y - Y_hat_median)^2)
) |>
mutate(
RMSE_mean = sqrt(MSE_mean),
RMSE_median = sqrt(MSE_median)
)# A tibble: 1 × 4
MSE_mean MSE_median RMSE_mean RMSE_median
<dbl> <dbl> <dbl> <dbl>
1 13.7 14.8 3.70 3.84
# Test set
test |>
summarize(
MSE_mean = mean((Y - Y_hat_mean)^2),
MSE_median = mean((Y - Y_hat_median)^2)
) |>
mutate(
RMSE_mean = sqrt(MSE_mean),
RMSE_median = sqrt(MSE_median)
)# A tibble: 1 × 4
MSE_mean MSE_median RMSE_mean RMSE_median
<dbl> <dbl> <dbl> <dbl>
1 12.1 11.4 3.48 3.38
Remember the units: the MSEs are in (L/100 km)², and the RMSEs are in L/100 km.
Q4 Are these two models overfitting? Why would you expect them to be, or not to be?
Show answer
No, and we should not have expected them to. Overfitting happens when a model is flexible enough to bend itself around the random noise in the training data, so it looks great on the training set and worse on new data. These models are about the least flexible models possible: each one summarizes the whole training set with a single number, so there is no way to chase individual points.
You can check this in your results: the training and test errors should be close to each other. Any small difference is just luck in which vehicles ended up in which dataset (the test error can even be lower than the training error). The problem with these models is the opposite one: they are far too simple to capture anything about how fuel consumption depends on the features, so the error is large on both sets.
We continue with the same fuel consumption data: train (80 vehicles) and test (60 vehicles), with target Y (L/100 km) and features X_1 (speed, km/h), X_2 (vehicle mass, kg), X_3 (outside temperature, °C), and X_4 (driver age, years).
Our baseline models ignore the features, and they are not very good. Now we will use a linear model to bring features in.
Want to work in RStudio instead? Download the datasets, fuel_train.csv and fuel_test.csv, put them in your working directory, and load them with:
library(dplyr)
library(ggplot2)
library(patchwork)
train <- read.csv("fuel_train.csv")
test <- read.csv("fuel_test.csv")Reminder: all datasets and libraries are already loaded for you.
Q1 If you could add only one feature to the model, which one would you add? Justify your answer with plots (and, if you like, numbers).
Hint: make a scatterplot of Y against each of the four features, and look for the feature with the strongest linear association with Y. ggplot(train, aes(x = X_1, y = Y)) + geom_point() makes one scatterplot, and the function cor() (inside summarize()) can help.
Show answer
p1 <- ggplot(train, aes(x = X_1, y = Y)) + geom_point() + labs(y = "Y (L/100 km)")
p2 <- ggplot(train, aes(x = X_2, y = Y)) + geom_point() + labs(y = "Y (L/100 km)")
p3 <- ggplot(train, aes(x = X_3, y = Y)) + geom_point() + labs(y = "Y (L/100 km)")
p4 <- ggplot(train, aes(x = X_4, y = Y)) + geom_point() + labs(y = "Y (L/100 km)")
(p1 + p2) / (p3 + p4)
train |>
summarize(
r_X_1 = cor(Y, X_1),
r_X_2 = cor(Y, X_2),
r_X_3 = cor(Y, X_3),
r_X_4 = cor(Y, X_4)
)# A tibble: 1 × 4
r_X_1 r_X_2 r_X_3 r_X_4
<dbl> <dbl> <dbl> <dbl>
1 -0.255 0.241 -0.0324 -0.121
Looking only at the correlations, X_1 (about −0.26) and X_2 (about 0.24) are roughly tied. The scatterplots tell them apart: X_2 shows a clear upward trend, so we would add X_2 (vehicle mass). X_3 and X_4 look like shapeless clouds.
Look at X_1 too: its correlation is fairly weak, but the scatterplot is definitely not a shapeless cloud. It has a clear U shape. A correlation coefficient only measures linear association, so it misses most of this, and a straight line in X_1 can’t capture it either.
Q2 Now suppose you are also allowed to transform one of the features before adding it to the model. Which feature would you choose and what transformation would you apply? Create the transformed feature, called X_1_t or similar, in both train and test.
Show answer
We choose X_1 (speed). The scatterplot shows that fuel consumption is lowest at moderate speeds (around 70 km/h) and rises when driving much slower or much faster. This is a very strong association, but a highly nonlinear one, so a straight line can’t capture it. We can straighten it out by using the squared distance from the sweet spot:
train <- mutate(train, X_1_t = (X_1 - 70)^2)
test <- mutate(test, X_1_t = (X_1 - 70)^2)
ggplot(train, aes(x = X_1_t, y = Y)) +
geom_point() +
labs(y = "Y (L/100 km)")
train |> summarize(r_X_1_t = cor(Y, X_1_t))# A tibble: 1 × 1
r_X_1_t
<dbl>
1 0.914
After the transformation, the relationship is a nice straight line with very little scatter, and the correlation is far stronger than for any of the original features.
Q3 Write code to fit one linear model for each feature: X_1, X_2, X_3, X_4, and the transformed X_1_t (five models in total, each with a single feature). Compute the MSE, RMSE, and \(R^2\) of each model on both the training set and the test set.
Use this definition: \(R^2 = 1 - \dfrac{\text{MSE of the model}}{\text{MSE of the baseline}}\), where the baseline model predicts the training mean \(\bar{Y}\), and both MSEs are computed on the same dataset. In words: the proportion of the baseline’s error that the model eliminates.
Show answer
Y_bar <- train |> summarize(Y_bar = mean(Y)) |> pull(Y_bar)
model_1 <- lm(Y ~ X_1, data = train)
model_2 <- lm(Y ~ X_2, data = train)
model_3 <- lm(Y ~ X_3, data = train)
model_4 <- lm(Y ~ X_4, data = train)
model_1_t <- lm(Y ~ X_1_t, data = train)
# Stack the predictions of every model on both sets, then summarize each group
bind_rows(
train |> mutate(set = "train", feature = "X_1", Y_hat = predict(model_1, newdata = train)),
test |> mutate(set = "test", feature = "X_1", Y_hat = predict(model_1, newdata = test)),
train |> mutate(set = "train", feature = "X_2", Y_hat = predict(model_2, newdata = train)),
test |> mutate(set = "test", feature = "X_2", Y_hat = predict(model_2, newdata = test)),
train |> mutate(set = "train", feature = "X_3", Y_hat = predict(model_3, newdata = train)),
test |> mutate(set = "test", feature = "X_3", Y_hat = predict(model_3, newdata = test)),
train |> mutate(set = "train", feature = "X_4", Y_hat = predict(model_4, newdata = train)),
test |> mutate(set = "test", feature = "X_4", Y_hat = predict(model_4, newdata = test)),
train |> mutate(set = "train", feature = "X_1_t", Y_hat = predict(model_1_t, newdata = train)),
test |> mutate(set = "test", feature = "X_1_t", Y_hat = predict(model_1_t, newdata = test))
) |>
group_by(feature, set) |>
summarize(
MSE = mean((Y - Y_hat)^2),
RMSE = sqrt(MSE),
R2 = 1 - MSE / mean((Y - Y_bar)^2),
.groups = "drop"
)# A tibble: 10 × 5
feature set MSE RMSE R2
<chr> <chr> <dbl> <dbl> <dbl>
1 X_1 test 13.8 3.72 -0.142
2 X_1 train 12.8 3.58 0.0648
3 X_1_t test 2.58 1.61 0.786
4 X_1_t train 2.27 1.51 0.835
5 X_2 test 10.9 3.30 0.101
6 X_2 train 12.9 3.59 0.0582
7 X_3 test 11.8 3.43 0.0267
8 X_3 train 13.7 3.70 0.00105
9 X_4 test 12.5 3.53 -0.0298
10 X_4 train 13.5 3.68 0.0145
(If you prefer, you can also write the evaluation pipeline separately for each model and each dataset.)
The model with the transformed feature X_1_t should be by far the best, then, on the test set, the model with X_2. The models with X_1 (untransformed), X_3, and X_4 should be barely better than the baseline: \(R^2\) close to 0, and possibly even slightly negative on the test set.
Q4 Do you see any overfitting in these five models?
Show answer
No. For each model, the training and test metrics should be close to each other, and the small differences go in both directions. This is what we’d expect: each model only has two coefficients, estimated from 80 observations, so it is far too simple to memorize the noise in the training set. (Note that a model can be bad without overfitting: the models using X_1, X_3, and X_4 are bad because they don’t capture any association, not because they are too flexible.)
Q5 What are the units of measurement of the MSE, the RMSE, and \(R^2\)?
Show answer
- MSE: the squared units of \(Y\), here (L/100 km)².
- RMSE: the same units as \(Y\), here L/100 km.
- \(R^2\): no units. It’s a ratio of two MSEs, and the units cancel. It can be read as the proportion of the baseline’s MSE that the model eliminates: 0 means no better than the baseline, and 1 means perfect predictions. (On a test set it can even be negative, if the model is worse than the baseline.)
Q6 Pen and paper. A model has been fit to predict Y from X_2. Here is its output:
| term | estimate |
|---|---|
| (Intercept) | 6.11000 |
| X_2 | 0.00305 |
And here are two vehicles from the training set:
| Y | X_1 | X_2 | X_3 | X_4 |
|---|---|---|---|---|
| 13.3 | 41 | 1780 | 28 | 69 |
| 8.0 | 86 | 1120 | -1 | 69 |
Compute the residual of the model for each of these two vehicles, including units. One of them should be positive and the other negative. What does the sign of a residual tell you?
Show answer
The model is \(\hat{Y} = b_0 + b_1 \cdot X_2\), using the two coefficients in the output. The residual is the actual value minus the prediction, \(Y - \hat{Y}\).
- Vehicle with \(X_2\) = 1780 kg and \(Y\) = 13.3 L/100 km: the prediction is 11.54 L/100 km, so the residual is 13.3 − 11.54 = 1.76 L/100 km. It’s positive: the vehicle burned more fuel than the model predicted (the model underpredicted).
- Vehicle with \(X_2\) = 1120 kg and \(Y\) = 8 L/100 km: the prediction is 9.53 L/100 km, so the residual is 8 − 9.53 = -1.53 L/100 km. It’s negative: the vehicle burned less fuel than the model predicted (the model overpredicted).
The residual is measured in the same units as \(Y\) (L/100 km). Its sign tells us the direction of the miss (positive: prediction too low; negative: prediction too high), and its size tells us how big the miss was. The RMSE is a kind of “typical size” of these residuals.
We keep working with the fuel consumption data. For this case study, the transformed feature X_1_t from part 3 has already been added to train and test, so the features are X_1, X_2, X_3, X_4, and X_1_t. The training mean Y_bar has also been loaded for you.
Want to work in RStudio instead? Download the datasets, fuel_train.csv and fuel_test.csv, put them in your working directory, and load them with:
library(dplyr)
library(ggplot2)
library(patchwork)
train <- read.csv("fuel_train.csv")
test <- read.csv("fuel_test.csv")
# The transformed feature from part 3
train <- mutate(train, X_1_t = (X_1 - 70)^2)
test <- mutate(test, X_1_t = (X_1 - 70)^2)
# The baseline's training mean
Y_bar <- train |> summarize(Y_bar = mean(Y)) |> pull(Y_bar)Reminder: all datasets and libraries are already loaded for you.
Q1 Fit a linear model that uses all five features. Compute its metrics on the training and the test set. Is there overfitting yet?
Show answer
model_all <- lm(Y ~ X_1 + X_2 + X_3 + X_4 + X_1_t, data = train)
bind_rows(
train |> mutate(set = "train", Y_hat = predict(model_all, newdata = train)),
test |> mutate(set = "test", Y_hat = predict(model_all, newdata = test))
) |>
group_by(set) |>
summarize(
MSE = mean((Y - Y_hat)^2),
RMSE = sqrt(MSE),
R2 = 1 - MSE / mean((Y - Y_bar)^2)
)# A tibble: 2 × 4
set MSE RMSE R2
<chr> <dbl> <dbl> <dbl>
1 test 0.223 0.472 0.982
2 train 0.131 0.362 0.990
This model is very good (an \(R^2\) close to 1), and the training and test metrics are close to each other. A gap, with the test error somewhat worse than the training error, is normal, because the coefficients were chosen to fit the training set. There is no real overfitting yet: six coefficients estimated from 80 observations is not enough flexibility to memorize the noise. Keep these numbers as a reference for the next questions.
Q2 Based on your scatterplots from part 3, which feature would you use to try to overfit the model as fast as possible? Why?
Show answer
The best candidate is X_4 (driver age), the feature whose scatterplot is a shapeless cloud. (X_3 is another reasonable choice, since it has only a very weak association with Y.) The reasoning:
- Overfitting means fitting the noise. Because
X_4has essentially no association withY, the only thing a wiggly function ofX_4can latch onto is random noise. Every drop in the training error we get from adding flexibility to this feature is, by construction, noise being memorized, so it can’t possibly help on the test set. - For a feature that has real signal, like
X_2, the first few terms capture something real, and the test error improves before the extra flexibility starts to hurt.
So the intuition “the noisiest feature overfits fastest” is basically right. Two refinements. First, “noisy” here means that Y is scattered around any trend in that feature (the feature has little association with Y), not that the feature itself is measured with error. Second, what ultimately causes overfitting is the amount of flexibility relative to the number of observations: any feature will overfit once the polynomial has enough terms, and how quickly the test error deteriorates also depends on the feature’s distribution. So in practice the differences between features are modest. You’ll test this yourself in Q4.
Q3 Replace that feature by a polynomial of itself, in the linear model with the other four features, and keep increasing the degree of the polynomial. Record the RMSE on the training and the test set for each degree, until you see clear signs of overfitting.
Hint: lm(Y ~ X_1 + X_2 + X_3 + X_1_t + poly(X_4, 5), data = train) uses a polynomial of degree 5 in X_4. Try degrees like 1, 2, 3, 5, 7, 9, 11, 13, 15, 20. A line plot of the RMSE against the degree makes the pattern easy to see.
Show answer
model_d1 <- lm(Y ~ X_1 + X_2 + X_3 + X_1_t + poly(X_4, 1), data = train)
model_d3 <- lm(Y ~ X_1 + X_2 + X_3 + X_1_t + poly(X_4, 3), data = train)
model_d5 <- lm(Y ~ X_1 + X_2 + X_3 + X_1_t + poly(X_4, 5), data = train)
model_d10 <- lm(Y ~ X_1 + X_2 + X_3 + X_1_t + poly(X_4, 10), data = train)
model_d15 <- lm(Y ~ X_1 + X_2 + X_3 + X_1_t + poly(X_4, 15), data = train)
model_d20 <- lm(Y ~ X_1 + X_2 + X_3 + X_1_t + poly(X_4, 20), data = train)
overfit_X_4 <- bind_rows(
train |> mutate(set = "train", degree = 1, Y_hat = predict(model_d1, newdata = train)),
test |> mutate(set = "test", degree = 1, Y_hat = predict(model_d1, newdata = test)),
train |> mutate(set = "train", degree = 3, Y_hat = predict(model_d3, newdata = train)),
test |> mutate(set = "test", degree = 3, Y_hat = predict(model_d3, newdata = test)),
train |> mutate(set = "train", degree = 5, Y_hat = predict(model_d5, newdata = train)),
test |> mutate(set = "test", degree = 5, Y_hat = predict(model_d5, newdata = test)),
train |> mutate(set = "train", degree = 10, Y_hat = predict(model_d10, newdata = train)),
test |> mutate(set = "test", degree = 10, Y_hat = predict(model_d10, newdata = test)),
train |> mutate(set = "train", degree = 15, Y_hat = predict(model_d15, newdata = train)),
test |> mutate(set = "test", degree = 15, Y_hat = predict(model_d15, newdata = test)),
train |> mutate(set = "train", degree = 20, Y_hat = predict(model_d20, newdata = train)),
test |> mutate(set = "test", degree = 20, Y_hat = predict(model_d20, newdata = test))
) |>
group_by(set, degree) |>
summarize(
MSE = mean((Y - Y_hat)^2),
RMSE = sqrt(MSE),
R2 = 1 - MSE / mean((Y - Y_bar)^2),
.groups = "drop"
)
overfit_X_4 |> select(set, degree, RMSE, R2)# A tibble: 12 × 4
set degree RMSE R2
<chr> <dbl> <dbl> <dbl>
1 test 1 0.472 0.982
2 test 3 0.473 0.981
3 test 5 0.474 0.981
4 test 10 0.468 0.982
5 test 15 0.487 0.980
6 test 20 2.21 0.596
7 train 1 0.362 0.990
8 train 3 0.358 0.991
9 train 5 0.356 0.991
10 train 10 0.352 0.991
11 train 15 0.331 0.992
12 train 20 0.273 0.995
# (log scale on the vertical axis, because the test RMSE can explode)
p_X_4 <- ggplot(overfit_X_4, aes(x = degree, y = RMSE, color = set)) +
geom_line() +
geom_point() +
scale_y_log10() +
labs(title = "X_4")
p_X_4
The pattern to look for: as the degree increases, the training RMSE keeps going down (it has to: a polynomial of a higher degree can always do at least as well on the data it’s fit on), but the test RMSE stops improving, and eventually gets worse, until it is much larger than the training RMSE. That growing gap is the clear sign of overfitting. The model is using its extra wiggles to fit the noise in the 80 training vehicles, which doesn’t carry over to new vehicles.
Q4 (Bonus) Repeat Q3 with a different feature, for example X_2, the feature that is most strongly (linearly) associated with Y. Does it overfit more slowly than the feature you chose in Q3? Was your intuition from Q2 right?
Show answer
model_X_2_d1 <- lm(Y ~ X_1 + X_3 + X_4 + X_1_t + poly(X_2, 1), data = train)
model_X_2_d3 <- lm(Y ~ X_1 + X_3 + X_4 + X_1_t + poly(X_2, 3), data = train)
model_X_2_d5 <- lm(Y ~ X_1 + X_3 + X_4 + X_1_t + poly(X_2, 5), data = train)
model_X_2_d10 <- lm(Y ~ X_1 + X_3 + X_4 + X_1_t + poly(X_2, 10), data = train)
model_X_2_d15 <- lm(Y ~ X_1 + X_3 + X_4 + X_1_t + poly(X_2, 15), data = train)
model_X_2_d20 <- lm(Y ~ X_1 + X_3 + X_4 + X_1_t + poly(X_2, 20), data = train)
overfit_X_2 <- bind_rows(
train |> mutate(set = "train", degree = 1, Y_hat = predict(model_X_2_d1, newdata = train)),
test |> mutate(set = "test", degree = 1, Y_hat = predict(model_X_2_d1, newdata = test)),
train |> mutate(set = "train", degree = 3, Y_hat = predict(model_X_2_d3, newdata = train)),
test |> mutate(set = "test", degree = 3, Y_hat = predict(model_X_2_d3, newdata = test)),
train |> mutate(set = "train", degree = 5, Y_hat = predict(model_X_2_d5, newdata = train)),
test |> mutate(set = "test", degree = 5, Y_hat = predict(model_X_2_d5, newdata = test)),
train |> mutate(set = "train", degree = 10, Y_hat = predict(model_X_2_d10, newdata = train)),
test |> mutate(set = "test", degree = 10, Y_hat = predict(model_X_2_d10, newdata = test)),
train |> mutate(set = "train", degree = 15, Y_hat = predict(model_X_2_d15, newdata = train)),
test |> mutate(set = "test", degree = 15, Y_hat = predict(model_X_2_d15, newdata = test)),
train |> mutate(set = "train", degree = 20, Y_hat = predict(model_X_2_d20, newdata = train)),
test |> mutate(set = "test", degree = 20, Y_hat = predict(model_X_2_d20, newdata = test))
) |>
group_by(set, degree) |>
summarize(
MSE = mean((Y - Y_hat)^2),
RMSE = sqrt(MSE),
.groups = "drop"
)
p_X_2 <- ggplot(overfit_X_2, aes(x = degree, y = RMSE, color = set)) +
geom_line() +
geom_point() +
scale_y_log10() +
labs(title = "X_2")
p_X_4 + p_X_2
Compare the two panels by looking at the degree at which the test RMSE starts to climb away from the training RMSE. What you find will depend on your data, so the honest answer is whatever your plots show. Expect both features to eventually overfit when the degree is high enough, and the differences between features to be much smaller than the effect of the degree itself. The lesson is that overfitting is driven mostly by model flexibility relative to the amount of training data, and that adding flexibility on a feature with no real signal can only add noise.
A factory records whether each part coming off a production line is defective, to decide which parts to send to a (costly) manual inspection. The variables are:
| Variable | Meaning | Units of measurement |
|---|---|---|
| \(Y\) | the target: 1 if the part is defective, 0 if it is fine | none (it’s a category) |
| \(X_1\) | curing temperature | degrees Celsius (°C) |
| \(X_2\) | line speed | parts per minute |
| \(X_3\) | humidity in the factory | percent (%) |
| \(X_4\) | age of the machine operator | years |
Part A: pen and paper
Everything in Part A is meant for pen and paper (a calculator is fine, but no code). Here is the training set, with 6 parts:
| Part | \(Y\) | \(X_1\) (°C) | \(X_2\) (parts/min) | \(X_3\) (%) | \(X_4\) (years) |
|---|---|---|---|---|---|
| 1 | 0 | 182 | 35 | 45 | 34 |
| 2 | 1 | 158 | 52 | 60 | 41 |
| 3 | 0 | 176 | 28 | 38 | 52 |
| 4 | 0 | 191 | 40 | 55 | 29 |
| 5 | 1 | 203 | 47 | 70 | 45 |
| 6 | 0 | 179 | 33 | 42 | 23 |
Q1 Suppose you didn’t have any features, only the six values of \(Y\). What would be your best procedure to produce a prediction for the next part? Give both an estimated probability that the part is defective and a decision (1 or 0).
Show answer
Without features, every part gets the same prediction. The best estimate of the probability that the next part is defective is the sample proportion of defective parts (equivalently, the sample mean of the 0/1 values):
\[\hat{P}(Y = 1) = \hat{p} = \frac{2}{6} = \frac{1}{3} \approx 0.33\]
To turn this probability into a decision, we use the usual threshold of 0.5: predict 1 if \(\hat{p} > 0.5\) and 0 otherwise. Since \(\hat{p} = 0.33 < 0.5\), the model predicts 0 (not defective) for every part.
Q2 Sketch, on paper, the training data together with the model’s predictions. Put \(Y\) on the vertical axis, and draw the decision threshold too.
Show answer
The data are points at only two heights: four at \(Y = 0\) and two at \(Y = 1\). The model’s predicted probability is a flat line at \(1/3\), and the decision threshold is a flat line at 0.5. Since the prediction line is below the threshold, every decision is 0.

Q3 Compute the MCR, the precision, and the recall of the model on the training set. What are their units of measurement?
Show answer
The model decides 0 for every part, so it never predicts a defect. Counting the four cells of the confusion matrix:
| Decision 1 | Decision 0 | |
|---|---|---|
| Actually 1 | TP = 0 | FN = 2 |
| Actually 0 | FP = 0 | TN = 4 |
\[\text{MCR} = \frac{FP + FN}{6} = \frac{2}{6} \approx 0.33 \qquad \text{Recall} = \frac{TP}{TP + FN} = \frac{0}{2} = 0\]
\[\text{Precision} = \frac{TP}{TP + FP} = \frac{0}{0} \text{ which is undefined, since the model never predicts a defect}\]
None of these has units: they are all proportions (between 0 and 1), which are sometimes written as percentages.
Q4 Is this level of error acceptable in real life?
Show answer
An MCR of 0.33 means the model is wrong for one part out of three, which sounds bad. But the MCR alone is misleading here: this model catches none of the defective parts (the recall is 0), so as a quality-control tool it is useless. And if defects were rare, say 5% of the parts, the same “always predict 0” model would have an MCR of just 0.05, which sounds great while still catching nothing. Whether an error level is acceptable depends on the application and on the cost of each kind of mistake: here, a defective part shipped to a customer versus a good part sent to inspection.
Q5 Here is a test set of 4 new parts:
| Part | \(Y\) | \(X_1\) (°C) | \(X_2\) (parts/min) | \(X_3\) (%) | \(X_4\) (years) |
|---|---|---|---|---|---|
| 7 | 0 | 185 | 38 | 50 | 31 |
| 8 | 1 | 165 | 55 | 62 | 38 |
| 9 | 0 | 172 | 30 | 47 | 47 |
| 10 | 0 | 188 | 36 | 52 | 26 |
Compute the MCR, precision, and recall of the same model on this test set. Are the training metrics enough to judge the model? What do you conclude?
Show answer
The model is still “predict 0 for every part” (the probability \(1/3\) came from the training set), so on the test set: TP = 0, FP = 0, TN = 3, FN = 1.
\[\text{MCR} = \frac{1}{4} = 0.25 \qquad \text{Recall} = \frac{0}{1} = 0 \qquad \text{Precision} = \frac{0}{0} \text{ (undefined)}\]
The training metrics alone are not enough: they describe how the model does on the data it was built from, so we need to check it on new data. Here the test MCR happens to be a little lower than the training MCR, which just reflects which parts ended up in which set, and with only 4 parts we can’t read much into it. What is clear is the bigger picture: the MCR looks “not too bad” (75% of the decisions are right), but the model never flags a defective part. Beating this baseline, in all the metrics and not only the MCR, is what a model that uses the features must do.
Part B: code
Now we use a much larger dataset: a training set train with 150 parts and a test set test with 500 parts, with the same variables as above.
| Y | X_1 | X_2 | X_3 | X_4 |
|---|---|---|---|---|
| 0 | 160 | 43 | 36 | 42 |
| 0 | 174 | 52 | 44 | 55 |
| 0 | 165 | 38 | 33 | 57 |
| 0 | 192 | 27 | 70 | 50 |
| 0 | 168 | 21 | 77 | 43 |
| 0 | 168 | 37 | 28 | 34 |
Again we only use the baseline model: the estimated probability is the proportion of defective parts in the training set, and the decision is 1 if this probability is above 0.5, and 0 otherwise.
Want to work in RStudio instead? (Part B) Download the datasets, parts_train.csv and parts_test.csv, put them in your working directory, and load them with:
library(dplyr)
library(ggplot2)
library(patchwork)
train <- read.csv("parts_train.csv")
test <- read.csv("parts_test.csv")Q6 Write a pipeline to add two columns, p_hat and Y_hat, to both train and test.
Show answer
# The proportion of defective parts in the TRAINING set
prop_1 <- train |> summarize(prop_1 = mean(Y)) |> pull(prop_1)
train <- train |>
mutate(p_hat = prop_1, Y_hat = ifelse(p_hat > 0.5, 1, 0))
# The test set gets the same prediction, computed from the training set
test <- test |>
mutate(p_hat = prop_1, Y_hat = ifelse(p_hat > 0.5, 1, 0))
head(train)# A tibble: 6 × 7
Y X_1 X_2 X_3 X_4 p_hat Y_hat
<int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0 160 43 36 42 0.327 0
2 0 174 52 44 55 0.327 0
3 0 165 38 33 57 0.327 0
4 0 192 27 70 50 0.327 0
5 0 168 21 77 43 0.327 0
6 0 168 37 28 34 0.327 0
Q7 Visualize both datasets with the model’s predictions: Y on the vertical axis, the predicted probability as a flat line, and the decision threshold as another flat line.
Hint: since Y only takes the values 0 and 1, use ggplot(d, aes(x = "", y = Y)) + geom_jitter(width = 0.3, height = 0) so the points don’t sit on top of each other, and geom_hline(yintercept = ...) for the flat lines.
Show answer
p_train <- ggplot(train, aes(x = "", y = Y)) +
geom_jitter(width = 0.3, height = 0) +
geom_hline(yintercept = prop_1, color = "blue", linewidth = 1) +
geom_hline(yintercept = 0.5, color = "gray40", linewidth = 1, linetype = "dashed") +
labs(x = NULL, y = "Y (1 = defective)", title = "train",
subtitle = "blue: predicted probability, gray dashed: threshold")
p_test <- ggplot(test, aes(x = "", y = Y)) +
geom_jitter(width = 0.3, height = 0) +
geom_hline(yintercept = prop_1, color = "blue", linewidth = 1) +
geom_hline(yintercept = 0.5, color = "gray40", linewidth = 1, linetype = "dashed") +
labs(x = NULL, y = "Y (1 = defective)", title = "test",
subtitle = "blue: predicted probability, gray dashed: threshold")
p_train + p_test
Q8 Write a pipeline to compute the MCR, precision, and recall of this model on both the training set and the test set.
Show answer
# Training set
train |>
summarize(
TP = sum(Y == 1 & Y_hat == 1),
FP = sum(Y == 0 & Y_hat == 1),
TN = sum(Y == 0 & Y_hat == 0),
FN = sum(Y == 1 & Y_hat == 0)
) |>
mutate(
MCR = (FP + FN) / (TP + FP + TN + FN),
Precision = TP / (TP + FP),
Recall = TP / (TP + FN)
)# A tibble: 1 × 7
TP FP TN FN MCR Precision Recall
<int> <int> <int> <int> <dbl> <dbl> <dbl>
1 0 0 101 49 0.327 NaN 0
# Test set
test |>
summarize(
TP = sum(Y == 1 & Y_hat == 1),
FP = sum(Y == 0 & Y_hat == 1),
TN = sum(Y == 0 & Y_hat == 0),
FN = sum(Y == 1 & Y_hat == 0)
) |>
mutate(
MCR = (FP + FN) / (TP + FP + TN + FN),
Precision = TP / (TP + FP),
Recall = TP / (TP + FN)
)# A tibble: 1 × 7
TP FP TN FN MCR Precision Recall
<int> <int> <int> <int> <dbl> <dbl> <dbl>
1 0 0 355 145 0.29 NaN 0
If the model never predicts a 1, the precision is NaN (0 divided by 0), and the recall is 0.
Q9 Is this model overfitting? Why would you expect it to be, or not?
Show answer
No. As with the baselines for regression, the model summarizes the entire training set with one number, so it has no way of chasing the noise in individual parts. The training and test metrics should be close, and any difference is due to the particular parts that fell into each set. The model’s problem is that it is too simple (it ignores all the features), not that it is too flexible.
We continue with the defective parts data: train (150 parts) and test (500 parts). The target is Y (1 if the part is defective, 0 otherwise), and the features are X_1 (curing temperature, °C), X_2 (line speed, parts/min), X_3 (humidity, %), and X_4 (operator age, years).
Want to work in RStudio instead? Download the datasets, parts_train.csv and parts_test.csv, put them in your working directory, and load them with:
library(dplyr)
library(ggplot2)
library(patchwork)
train <- read.csv("parts_train.csv")
test <- read.csv("parts_test.csv")Reminder: all datasets and libraries are already loaded for you.
Q1 If you could add only one feature to the model, which one would you add? Justify your answer with plots.
Hint: for a binary target, compare the distribution of each feature between the defective parts and the fine parts, for example with histograms in two colors, one for each value of Y, in dodged position: ggplot(train, aes(x = X_1, fill = factor(Y))) + geom_histogram(position = "dodge", bins = 12). The feature whose distribution shifts* the most between the two groups has the strongest linear association with Y.*
Show answer
p1 <- ggplot(train, aes(x = X_1, fill = factor(Y))) +
geom_histogram(position = "dodge", bins = 12) +
labs(fill = "Y (1 = defective)")
p2 <- ggplot(train, aes(x = X_2, fill = factor(Y))) +
geom_histogram(position = "dodge", bins = 12) +
labs(fill = "Y (1 = defective)")
p3 <- ggplot(train, aes(x = X_3, fill = factor(Y))) +
geom_histogram(position = "dodge", bins = 12) +
labs(fill = "Y (1 = defective)")
p4 <- ggplot(train, aes(x = X_4, fill = factor(Y))) +
geom_histogram(position = "dodge", bins = 12) +
labs(fill = "Y (1 = defective)")
(p1 + p2) / (p3 + p4) + plot_layout(guides = "collect")
The feature we would add is X_2 (line speed): it is the only one whose center clearly shifts between the two groups, with defective parts tending to come from faster line speeds. X_3 and X_4 show little or no difference between the groups.
X_1 is the interesting one: the centers of the two distributions are about the same, but the defective parts are much more spread out, with many at both low and high temperatures. That’s a sign of a strong nonlinear association, which a model that is linear in X_1 can’t capture.
Q2 Write code to fit one logistic regression model for each feature (X_1, X_2, X_3, X_4; four models in total, each with a single feature). Compute the MCR, precision, and recall of each model on both the training set and the test set, using the usual decision threshold of 0.5.
Hint: glm(Y ~ X_2, data = train, family = "binomial") fits a logistic regression, and predict(model, newdata = test, type = "response") gives predicted probabilities.
Show answer
model_1 <- glm(Y ~ X_1, data = train, family = "binomial")
model_2 <- glm(Y ~ X_2, data = train, family = "binomial")
model_3 <- glm(Y ~ X_3, data = train, family = "binomial")
model_4 <- glm(Y ~ X_4, data = train, family = "binomial")
# Stack the predicted probabilities of every model on both sets, then summarize each group
bind_rows(
train |> mutate(set = "train", feature = "X_1", Y_hat = predict(model_1, newdata = train, type = "response")),
test |> mutate(set = "test", feature = "X_1", Y_hat = predict(model_1, newdata = test, type = "response")),
train |> mutate(set = "train", feature = "X_2", Y_hat = predict(model_2, newdata = train, type = "response")),
test |> mutate(set = "test", feature = "X_2", Y_hat = predict(model_2, newdata = test, type = "response")),
train |> mutate(set = "train", feature = "X_3", Y_hat = predict(model_3, newdata = train, type = "response")),
test |> mutate(set = "test", feature = "X_3", Y_hat = predict(model_3, newdata = test, type = "response")),
train |> mutate(set = "train", feature = "X_4", Y_hat = predict(model_4, newdata = train, type = "response")),
test |> mutate(set = "test", feature = "X_4", Y_hat = predict(model_4, newdata = test, type = "response"))
) |>
mutate(decision = ifelse(Y_hat > 0.5, 1, 0)) |>
group_by(feature, set) |>
summarize(
TP = sum(Y == 1 & decision == 1),
FP = sum(Y == 0 & decision == 1),
TN = sum(Y == 0 & decision == 0),
FN = sum(Y == 1 & decision == 0),
.groups = "drop"
) |>
mutate(
MCR = (FP + FN) / (TP + FP + TN + FN),
Precision = TP / (TP + FP),
Recall = TP / (TP + FN)
) |>
select(feature, set, MCR, Precision, Recall)# A tibble: 8 × 5
feature set MCR Precision Recall
<chr> <chr> <dbl> <dbl> <dbl>
1 X_1 test 0.29 NaN 0
2 X_1 train 0.327 NaN 0
3 X_2 test 0.29 NaN 0
4 X_2 train 0.327 NaN 0
5 X_3 test 0.29 NaN 0
6 X_3 train 0.327 NaN 0
7 X_4 test 0.29 NaN 0
8 X_4 train 0.327 NaN 0
X_2 is the only feature with a clear (linear) association with Y, so its model should be the best of the four, although at the threshold of 0.5 the difference may barely show. Notice that several of the single-feature models never predict a defective part at the threshold of 0.5 (precision NaN, recall 0, and an MCR equal to the baseline’s): their predicted probabilities never get above 0.5, even though a feature like X_2 does carry some information. We will come back to this when we change the threshold.
Q3 Do you see any overfitting in these four models?
Show answer
No. Each model has only two coefficients and is fit on 150 parts, so the training and test metrics should be close to each other (with differences going in both directions, due to chance). A model like the ones using X_3 or X_4 is bad because the feature carries almost no information, not because the model is too flexible.
Q4 What are the units of measurement of the MCR, the precision, and the recall?
Show answer
None of them has units. They are all proportions: the MCR is the fraction of all parts that are misclassified, the precision is the fraction of the parts predicted defective that really are defective, and the recall is the fraction of the defective parts that the model catches. They all lie between 0 and 1, and can be written as percentages.
Q5 Pen and paper. A logistic regression model has been fit to predict Y from X_2. Here is its output:
| term | estimate |
|---|---|
| (Intercept) | -0.77600 |
| X_2 | 0.00135 |
And here are two parts from the training set:
| Y | X_2 |
|---|---|
| 1 | 57 |
| 0 | 43 |
For each part, (a) compute the predicted probability that it is defective, (b) compute the residual, \(Y\) minus the predicted probability (one will be positive and the other negative), (c) say whether the model’s decision is right or wrong at the threshold of 0.5, and say whether it is a TP, FP, TN, or FN, and (d) do the same for a threshold of 0.3.
Show answer
The predicted probability is \(\hat{P}(Y = 1) = \dfrac{1}{1 + e^{-(b_0 + b_1 \cdot X_2)}}\), using the two coefficients from the output.
- Part with \(X_2\) = 57 parts/min and \(Y\) = 1: the linear part is -0.7, and the predicted probability is about 0.33. The residual is 1 − 0.33 = 0.67 (positive: the model gave too low a probability to the thing that happened). At a threshold of 0.5, the decision is 0: a FN. At a threshold of 0.3, the decision is 1: a TP.
- Part with \(X_2\) = 43 parts/min and \(Y\) = 0: the linear part is -0.72, and the predicted probability is about 0.33. The residual is 0 − 0.33 = -0.33 (negative: the model gave too high a probability to the thing that did not happen). At a threshold of 0.5, the decision is 0: a TN. At a threshold of 0.3, the decision is 1: a FP.
Residuals here are differences between a 0/1 outcome and a probability, so they have no units. For a part that really is defective (\(Y = 1\)) the residual is always positive (we’re comparing 1 to a probability below 1), and for a fine part (\(Y = 0\)) it is always negative. The size of the residual tells you how surprised the model was: a defective part that got a probability of 0.1 has a residual of 0.9.
Also notice how changing the threshold can change the type of decision for the same part: lowering the threshold makes the model more eager to predict “defective”.
The decision threshold
For the rest of this case study, use the model with only X_2:
Q6 Compute the MCR, precision, and recall of this model on test_hat for thresholds from 0.1 to 0.9, in steps of 0.1.
Hint: mutate(decision = ifelse(Y_hat > 0.3, 1, 0)) makes the decisions for one threshold, and you can repeat the pipeline for each threshold. Or stack copies of test_hat with bind_rows(), each with its own threshold column, and use group_by(threshold).
Show answer
model_X_2 <- glm(Y ~ X_2, data = train, family = "binomial")
test_hat <- mutate(test, Y_hat = predict(model_X_2, newdata = test, type = "response"))
threshold_results <- bind_rows(
test_hat |> mutate(threshold = 0.1),
test_hat |> mutate(threshold = 0.2),
test_hat |> mutate(threshold = 0.3),
test_hat |> mutate(threshold = 0.4),
test_hat |> mutate(threshold = 0.5),
test_hat |> mutate(threshold = 0.6),
test_hat |> mutate(threshold = 0.7),
test_hat |> mutate(threshold = 0.8),
test_hat |> mutate(threshold = 0.9)
) |>
mutate(decision = ifelse(Y_hat > threshold, 1, 0)) |>
group_by(threshold) |>
summarize(
TP = sum(Y == 1 & decision == 1),
FP = sum(Y == 0 & decision == 1),
TN = sum(Y == 0 & decision == 0),
FN = sum(Y == 1 & decision == 0)
) |>
mutate(
MCR = (FP + FN) / (TP + FP + TN + FN),
Precision = TP / (TP + FP),
Recall = TP / (TP + FN)
)
threshold_results |> select(threshold, MCR, Precision, Recall)# A tibble: 9 × 4
threshold MCR Precision Recall
<dbl> <dbl> <dbl> <dbl>
1 0.1 0.71 0.29 1
2 0.2 0.71 0.29 1
3 0.3 0.71 0.29 1
4 0.4 0.29 NaN 0
5 0.5 0.29 NaN 0
6 0.6 0.29 NaN 0
7 0.7 0.29 NaN 0
8 0.8 0.29 NaN 0
9 0.9 0.29 NaN 0
ggplot(threshold_results, aes(x = threshold)) +
geom_line(aes(y = MCR, color = "MCR"), linewidth = 1) +
geom_line(aes(y = Precision, color = "Precision"), linewidth = 1) +
geom_line(aes(y = Recall, color = "Recall"), linewidth = 1) +
scale_color_manual(values = c("MCR" = "black", "Precision" = "blue", "Recall" = "red")) +
labs(y = NULL, color = NULL)
Q7 What happens to the precision and the recall as you increase the threshold? What would happen at the extremes, a threshold of 0 and a threshold of 1?
Show answer
Raising the threshold makes the model more reluctant to say “defective”, so it flags fewer parts. The recall goes down (we catch fewer of the defective parts), and the precision typically goes up (the parts we do flag are the ones the model is most sure about, so a larger share of them are truly defective). Lowering the threshold does the opposite: we catch more defective parts, but we also flag more good parts by mistake. The MCR is usually lowest somewhere in the middle, but not necessarily exactly at 0.5.
At the extremes:
- Threshold 0: every part is flagged as defective. The recall is 1 (nothing is missed), but the precision is just the overall proportion of defective parts.
- Threshold 1: no part is flagged (a probability can’t exceed 1). The recall is 0, and the precision is undefined (0/0). This is the same as the baseline that always predicts 0.
Q8 The company says that shipping one defective part to a customer costs far more than manually inspecting a good part. Would you use a threshold above or below 0.5? What if inspections were extremely expensive instead?
Show answer
If a missed defective part (a false negative) is much more costly than a needless inspection (a false positive), we want to catch as many defective parts as possible, i.e. a high recall, so we should use a lower threshold (for example 0.2 or 0.3), accepting more false positives. If inspections were extremely expensive, then false positives would be the main concern, and we’d want a high precision, so a higher threshold. The default threshold of 0.5 is only the right choice when the two kinds of mistakes are about equally costly. The threshold is a decision about the application, not a statistical property of the model.
Q9 Suppose you try many thresholds and pick the one with the best metrics on the test set. Is that a good idea? On which data should you choose the threshold?
Show answer
It’s not a good idea. If we choose the threshold (or anything else about the model) using the test set, then the test set is no longer new data: it has influenced our choice, and the test metrics will be optimistic. The threshold should be chosen using the training data (or a separate validation set), and then the test set should be used only once, to report how that final choice performs.
We keep working with the defective parts data, with the features X_1, X_2, X_3, and X_4.
Want to work in RStudio instead? Download the datasets, parts_train.csv and parts_test.csv, put them in your working directory, and load them with:
library(dplyr)
library(ggplot2)
library(patchwork)
train <- read.csv("parts_train.csv")
test <- read.csv("parts_test.csv")Reminder: all datasets and libraries are already loaded for you.
Q1 Fit a logistic regression that uses all four features. Compute its MCR, precision, and recall on the training and test sets (threshold 0.5). Is there overfitting yet?
Show answer
model_all <- glm(Y ~ X_1 + X_2 + X_3 + X_4, data = train, family = "binomial")
bind_rows(
train |> mutate(set = "train", Y_hat = predict(model_all, newdata = train, type = "response")),
test |> mutate(set = "test", Y_hat = predict(model_all, newdata = test, type = "response"))
) |>
mutate(decision = ifelse(Y_hat > 0.5, 1, 0)) |>
group_by(set) |>
summarize(
TP = sum(Y == 1 & decision == 1),
FP = sum(Y == 0 & decision == 1),
TN = sum(Y == 0 & decision == 0),
FN = sum(Y == 1 & decision == 0)
) |>
mutate(
MCR = (FP + FN) / (TP + FP + TN + FN),
Precision = TP / (TP + FP),
Recall = TP / (TP + FN)
) |>
select(set, MCR, Precision, Recall)# A tibble: 2 × 4
set MCR Precision Recall
<chr> <dbl> <dbl> <dbl>
1 test 0.286 1 0.0138
2 train 0.327 NaN 0
The test metrics are typically a bit worse than the training metrics, which is normal: the coefficients were chosen to fit the training set. As long as the gap is small, this isn’t overfitting yet. Keep the size of this gap in mind as a reference for the next questions.
Q2 Based on your plots from part 2, which feature would you use to try to overfit the model as fast as possible? Why?
Show answer
The best candidate is X_4 (operator age): its distributions for defective and fine parts look the same, so it has essentially no association with Y. (X_3 is another reasonable choice.) A wiggly function of a feature with no association can only latch onto random noise, so every improvement in the training metrics it buys us is noise memorized, which can’t help on new parts. The intuition “the noisiest feature overfits fastest” is basically right, with the same caveats as in the regression case study: “noisy” means little association with Y, and in the end overfitting is driven mostly by how flexible the model is compared with how much training data there is, so the differences between features are modest.
Q3 Replace that feature by a polynomial of itself in the logistic regression (keeping the other three features), and keep increasing the degree. Record the MCR on the training and test sets for each degree, until you see clear signs of overfitting.
Hint: glm(Y ~ X_1 + X_2 + X_3 + poly(X_4, 5), data = train, family = "binomial") uses a polynomial of degree 5 in X_4. Try degrees like 1, 2, 3, 5, 7, 9, 11, 13, 15. At high degrees glm() may print warnings such as “fitted probabilities numerically 0 or 1 occurred”: that is itself a symptom of a model that has become too flexible.
Show answer
model_d1 <- glm(Y ~ X_1 + X_2 + X_3 + poly(X_4, 1), data = train, family = "binomial")
model_d3 <- glm(Y ~ X_1 + X_2 + X_3 + poly(X_4, 3), data = train, family = "binomial")
model_d5 <- glm(Y ~ X_1 + X_2 + X_3 + poly(X_4, 5), data = train, family = "binomial")
model_d10 <- glm(Y ~ X_1 + X_2 + X_3 + poly(X_4, 10), data = train, family = "binomial")
model_d15 <- glm(Y ~ X_1 + X_2 + X_3 + poly(X_4, 15), data = train, family = "binomial")
overfit_X_4 <- bind_rows(
train |> mutate(set = "train", degree = 1, Y_hat = predict(model_d1, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 1, Y_hat = predict(model_d1, newdata = test, type = "response")),
train |> mutate(set = "train", degree = 3, Y_hat = predict(model_d3, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 3, Y_hat = predict(model_d3, newdata = test, type = "response")),
train |> mutate(set = "train", degree = 5, Y_hat = predict(model_d5, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 5, Y_hat = predict(model_d5, newdata = test, type = "response")),
train |> mutate(set = "train", degree = 10, Y_hat = predict(model_d10, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 10, Y_hat = predict(model_d10, newdata = test, type = "response")),
train |> mutate(set = "train", degree = 15, Y_hat = predict(model_d15, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 15, Y_hat = predict(model_d15, newdata = test, type = "response"))
) |>
mutate(decision = ifelse(Y_hat > 0.5, 1, 0)) |>
group_by(set, degree) |>
summarize(
TP = sum(Y == 1 & decision == 1),
FP = sum(Y == 0 & decision == 1),
TN = sum(Y == 0 & decision == 0),
FN = sum(Y == 1 & decision == 0),
.groups = "drop"
) |>
mutate(
MCR = (FP + FN) / (TP + FP + TN + FN),
Precision = TP / (TP + FP),
Recall = TP / (TP + FN)
)
overfit_X_4 |> select(set, degree, MCR, Precision, Recall)# A tibble: 10 × 5
set degree MCR Precision Recall
<chr> <dbl> <dbl> <dbl> <dbl>
1 test 1 0.286 1 0.0138
2 test 3 0.28 0.692 0.0621
3 test 5 0.31 0.417 0.172
4 test 10 0.396 0.248 0.179
5 test 15 0.4 0.28 0.241
6 train 1 0.327 NaN 0
7 train 3 0.327 0.5 0.0204
8 train 5 0.327 0.5 0.102
9 train 10 0.273 0.682 0.306
10 train 15 0.3 0.559 0.388
p_X_4 <- ggplot(overfit_X_4, aes(x = degree, y = MCR, color = set)) +
geom_line() +
geom_point() +
labs(title = "X_4")
p_X_4
The pattern to look for: as the degree increases, the training MCR keeps going down (the model has more and more freedom to get the training parts right), while the test MCR stops improving and starts to creep up, so the gap between the two grows. The extra flexibility is being spent on memorizing which training parts happened to be defective, which doesn’t carry over to new parts. Compared with the regression case study, the effect on the MCR can look smaller, because the MCR only counts whether a decision is right or wrong; the estimated probabilities themselves become much more extreme (hence the warnings).
Q4 (Bonus) Repeat with a different feature, for example X_2. Does it overfit more slowly? Was your intuition from Q2 right?
Show answer
model_X_2_d1 <- glm(Y ~ X_1 + X_3 + X_4 + poly(X_2, 1), data = train, family = "binomial")
model_X_2_d3 <- glm(Y ~ X_1 + X_3 + X_4 + poly(X_2, 3), data = train, family = "binomial")
model_X_2_d5 <- glm(Y ~ X_1 + X_3 + X_4 + poly(X_2, 5), data = train, family = "binomial")
model_X_2_d10 <- glm(Y ~ X_1 + X_3 + X_4 + poly(X_2, 10), data = train, family = "binomial")
model_X_2_d15 <- glm(Y ~ X_1 + X_3 + X_4 + poly(X_2, 15), data = train, family = "binomial")
overfit_X_2 <- bind_rows(
train |> mutate(set = "train", degree = 1, Y_hat = predict(model_X_2_d1, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 1, Y_hat = predict(model_X_2_d1, newdata = test, type = "response")),
train |> mutate(set = "train", degree = 3, Y_hat = predict(model_X_2_d3, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 3, Y_hat = predict(model_X_2_d3, newdata = test, type = "response")),
train |> mutate(set = "train", degree = 5, Y_hat = predict(model_X_2_d5, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 5, Y_hat = predict(model_X_2_d5, newdata = test, type = "response")),
train |> mutate(set = "train", degree = 10, Y_hat = predict(model_X_2_d10, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 10, Y_hat = predict(model_X_2_d10, newdata = test, type = "response")),
train |> mutate(set = "train", degree = 15, Y_hat = predict(model_X_2_d15, newdata = train, type = "response")),
test |> mutate(set = "test", degree = 15, Y_hat = predict(model_X_2_d15, newdata = test, type = "response"))
) |>
mutate(decision = ifelse(Y_hat > 0.5, 1, 0)) |>
group_by(set, degree) |>
summarize(MCR = mean(Y != decision), .groups = "drop")
p_X_2 <- ggplot(overfit_X_2, aes(x = degree, y = MCR, color = set)) +
geom_line() +
geom_point() +
labs(title = "X_2")
p_X_4 + p_X_2
Compare the degrees at which the test MCR starts to move away from the training MCR. The answer depends on your data, so go with what your plots show. Expect both features to overfit once the degree is large enough, and the differences between features to be small compared with the effect of the degree. Overfitting is mostly about flexibility relative to the amount of training data.
No data and no code in this case study. For each question, answer in a sentence or two.
Q1 I come to you with a model that predicts \(Y\) with an RMSE of 0.011 mm. Would you be excited about using it in real life?
Show answer
We can’t know: it depends on the application. If we are manufacturing high-precision microchips, where the dimensions matter at the scale of micrometers, an error of 0.011 mm could be a terrible, gigantic error. If we are measuring the length of hot dogs, an error of 0.011 mm is absurd overkill, far smaller than anything that matters. The RMSE is in the units of \(Y\), so it has to be judged against the scale of \(Y\) and the cost of errors in the application.
Q2 I come to you with a model that predicts \(Y\) with an RMSE of 0.011 mm. Would you be impressed with my skills as a statistician?
Show answer
Not necessarily. Maybe the data is just very easy: if \(Y\) barely varies (for example, all the parts are essentially the same size), then even the laziest model, one that predicts the average of \(Y\) for everything, would get a tiny RMSE, with no skill involved. A small RMSE only means something when compared with a baseline, like the RMSE of the model that always predicts \(\bar{Y}\).
Q3 I come to you with a model that predicts \(Y\) with an \(R^2\) of 0.2. Would you be impressed with my skills as a statistician?
Show answer
Not by itself. An \(R^2\) of 0.2 means the model eliminates only 20% of the baseline’s MSE, so it is just a little better than the model that always predicts the average (the baseline has an \(R^2\) of 0). But, as the next question shows, this is not necessarily your fault as a statistician.
Q4 I come to you with a model that predicts \(Y\) with an \(R^2\) of 0.2. Do you think you could do better?
Show answer
Not necessarily! Maybe the data simply contains little information about \(Y\): if the features have only a weak association with \(Y\), then 0.2 might be the best that anyone could do, however skilled. How well we can predict is limited by how much association there is in the data.
Q5 I come to you with a model that predicts \(Y\) with an \(R^2\) of 1. Would you be impressed with my skills as a statistician?
Show answer
Hmm, an \(R^2\) of 1 means perfect predictions, which almost never happens with real data. I would be suspicious. Most likely either (1) the model is overfit and you’re showing me the training \(R^2\) instead of the test \(R^2\), or (2) you made a mistake somewhere, for example a feature that accidentally contains the answer (such as a transformation of \(Y\) itself), or a mistake in the calculation.
Q6 Challenge: write a set of questions like the five above, but for classification metrics: the MCR, the precision, and the recall. For each question, write down the answer you would expect.
Show answer
Here are some examples of what good questions and answers could look like:
- A model has an MCR of 0.01. Are you excited to use it in real life? It depends on the application: if a mistake means a wrong movie recommendation, an MCR of 1% is great; if it means missing a serious disease, 1% could be unacceptable.
- A model has an MCR of 0.01. Are you impressed with my skills? Not necessarily: if 99% of the data has \(Y = 0\), then the baseline that always predicts 0 also has an MCR of 0.01, and my model might have learned nothing.
- A model has a precision of 100%. Are you impressed? Not necessarily: maybe the model flags a single, extremely obvious case, and misses everything else (a tiny recall). Precision alone is easy to game.
- A model has a recall of 100%. Are you impressed? Not necessarily: the model that flags everything as positive has a recall of 100% too. Recall alone is easy to game in the other direction.
- A model has an MCR of 0 (or a precision and recall of 100%). Are you impressed? I would be suspicious: probably it’s the training MCR of an overfit model, or the answer has leaked into the features, or there’s a mistake.
- A model has an MCR of 0.4. Could you do better? Not necessarily: maybe the features carry very little information about \(Y\).
No data and no code in this case study.
Quick questions
Q1 Would you trust a test RMSE computed on a test set made of only 10 data points? Why? Give a numerical example.
Show answer
No. A test RMSE is an estimate of how the model would do on new data, and an estimate computed from only 10 points is very imprecise: with a different set of 10 points we could get a very different number. A confidence interval would be very wide.
A numerical example. Suppose the test RMSE is 2.0 (so the test MSE is 4.0). The test MSE is just the sample mean of the squared errors \(e_i^2\), so we can use the usual confidence interval for a mean. Say the standard deviation of the squared errors is \(s = 6\). Then an approximate 95% confidence interval for the true MSE is
\[\text{MSE} \pm 1.96 \cdot \frac{s}{\sqrt{n}}\]
- With \(n = 10\) test points: \(4.0 \pm 1.96 \cdot \frac{6}{\sqrt{10}} = 4.0 \pm 3.72\), so about \((0.28, 7.72)\) for the MSE. Taking square roots of the endpoints, that’s about 0.5 to 2.8 for the RMSE. The true RMSE could plausibly be anywhere from about a quarter of our estimate to about 40% above it. (And with only 10 points, even the normal approximation behind this interval is shaky.)
- With \(n = 1000\) test points: \(4.0 \pm 1.96 \cdot \frac{6}{\sqrt{1000}} = 4.0 \pm 0.37\), and the interval for the RMSE shrinks to about 1.9 to 2.1.
Same estimate, but with 10 points it’s almost meaningless, and with 1000 it is a number we can rely on.
Q2 Which property of variables allows us to make very good predictions about them?
Show answer
Association. If the features are strongly associated with \(Y\) (knowing the features tells us a lot about \(Y\)), we can predict \(Y\) well. If they aren’t, even the best model can’t do much better than a baseline.
Q3 For a given dataset, what are the best-case and the worst-case scenarios for the number of false negatives (FN), false positives (FP), true positives (TP), and true negatives (TN)?
Show answer
Say that the dataset has \(P\) actual positives and \(N\) actual negatives.
- Best case: TP = \(P\), TN = \(N\), FP = 0, FN = 0. Every decision is right (MCR = 0, precision = 1, recall = 1).
- Literally the worst case: TP = 0, TN = 0, FP = \(N\), FN = \(P\). Every decision is wrong (MCR = 1).
But the literal worst case is not really “worst”: a model that is wrong about everything is incredibly informative. We could simply flip all its decisions (0 becomes 1, and 1 becomes 0) and get a perfect model. So the model that is truly useless sits in the middle: a model whose decisions have no relationship with the truth, like the baseline that always predicts the same thing. If a model is doing worse than that, we can flip it around and do better.
For example, with \(P = 30\) and \(N = 70\): the best case is TP = 30, TN = 70, and the literal worst case is FP = 70, FN = 30, but the always-predict-0 baseline (TP = 0, FP = 0, TN = 70, FN = 30, an MCR of 0.3) is the real floor.
A model for predicting student scores
Imagine that I trained a model to predict the final percentage score of students in a course, using their year, major, and GPA. I used a training set from the last 5 years of Stat 20. The test RMSE is 0.2.
Q4 What are the units of measurement of this RMSE?
Show answer
The RMSE has the same units as \(Y\). Here \(Y\) is a percentage score, so there are no “physical” units: the RMSE is just 0.2 percentage points (out of 100).
Q5 Is this a regression or a classification problem?
Show answer
Regression: the target (the percentage score) is a numerical variable that can take many different values.
Q6 If I use a linear regression, how many coefficients would you see in the fitting output?
Show answer
A huge number. GPA (and year, if treated as a number) each contribute one coefficient, but major is a categorical variable with a large number of levels, and a linear model needs a separate indicator variable, with its own coefficient, for each level (except one reference level). E.g. with 100 separate majors, we get 99 coefficients just for the major, so about 101 coefficients in total.
Q7 Which feature do you think will be the most useful?
Show answer
GPA, probably by a wide margin: it is likely the feature most strongly associated with the final score, since students who do well in their other courses tend to do well in this one too.
Q8 Now imagine I use this model for a Latin class that I teach in Canada. Would you trust the test RMSE of 0.2 for this new class?
Show answer
Not really. The test RMSE is only a good estimate of the model’s error on new data from the same population as the training data. Here the training data came from a completely different population (Stat 20 students, over 5 years), so using the model in a Latin class in Canada raises a huge selection bias problem: the grading, the course, and the students are all different, so the test RMSE won’t generalize to the new population.
Calculating, estimating, predicting
Think carefully about what each verb means. A population is all the units we care about, while a sample is a subset of them. A parameter is a number that describes a population (like a population proportion).
First, a small business received 10 emails yesterday, and that’s all of the emails we care about (the population). The variable \(Y\) is 1 if the email is spam and 0 otherwise:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
|---|---|---|---|---|---|---|---|---|---|---|
| \(Y\) | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 |
Q9 Calculate the probability that \(Y = 1\) if I draw one email at random from this population.
Show answer
Since we have the whole population, this is just the population proportion: 4 spam emails out of 10, so the probability is \(4/10 = 0.4\).
Q10 Estimate the probability that \(Y = 1\) if I draw one email at random from this population.
Show answer
The question makes no sense. We have the entire population, so there is nothing to estimate: we can simply calculate the probability exactly, as above. We estimate when we only have a sample and don’t have access to the population.
Now a different situation. A big company has millions of emails on its servers, which we can’t look at in full (the population). We only have a sample of 6 emails:
| 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|
| \(Y\) | 1 | 1 | 0 | 1 | 0 | 1 |
Q11 Estimate the probability that \(Y = 1\) if I draw one email at random from the company’s population of emails.
Show answer
We use the sample proportion as our estimator: \(\hat{p} = 4/6 \approx 0.67\). This is an estimate of the unknown population proportion.
Q12 Calculate the probability that \(Y = 1\) if I draw one email at random from the company’s population of emails.
Show answer
That’s impossible. To calculate the probability exactly, we would need access to the whole population, and all we have is a sample of 6 emails. The best we can do is estimate it.
Q13 Predict the probability that \(Y = 1\) if I draw one email at random from the company’s population of emails.
Show answer
That’s nonsensical. The probability is a parameter: a fixed, unobservable number describing the population. We can estimate parameters, but we can’t predict them: we predict things that can be observed.
Q14 Estimate the next value of \(Y\) (the next email’s category).
Show answer
That’s nonsensical. \(Y\) is an observable variable: once the next email arrives, we will simply see its value. We estimate unobservable quantities (parameters), not observable ones.
Q15 Calculate the next value of \(Y\).
Show answer
That’s impossible: we don’t know the future. There is no formula that gives us the exact value of an email that we haven’t seen yet.
Q16 Predict the next value of \(Y\).
Show answer
This is the right verb for an observable quantity that we haven’t seen yet. We use our estimated probability and the usual decision rule: predict 1 if the estimated probability is above 0.5, and 0 if it is below 0.5. Here \(\hat{p} = 0.67 > 0.5\), so we predict 1 (spam).
In summary: we calculate population parameters, if we have the population, we estimate them, if we have a sample, and we predict observable variables that we haven’t seen, yet.