Lecture 10

Machine Learning I: Training, Test Data, Dummy Variables, and Residual Plots

Byeong-Hak Choe

SUNY Geneseo

November 23, 2026

🎯 Goals of Linear Regression

hms_heavy_days: Days with a heavy smoke plume over the county that month.

pm25: Monthly mean PM2.5 at the county’s EPA monitors, in µg/m³.

  • The goals of linear regression are to:
  1. Modeling for explanation: Find the relationship between hms_heavy_days and pm25 by estimating a true value of b1.
  • The estimated value of b1 is denoted by \(\hat{\texttt{b1}}\). This coefficient describes an association unless a causal design supports a causal interpretation.
  1. Modeling for prediction: Make a prediction on pm25[i] for new county-month i
  • The predicted value of pm25[i] is denoted by \(\widehat{\texttt{pm25}}\texttt{[i]}\), where

\[\widehat{\texttt{pm25}}\texttt{[i]} \;=\quad \hat{\texttt{b0}} \,+\, \hat{\texttt{b1}}\texttt{*hms_heavy_days[i]}\]

✂️ Training and Test Data

  • Training data: When we’re building a linear regression model, we need data to train the model.

  • Test data: We also need data to test whether the model works well on new data.

  • So, we start with splitting a given data.frame into training and test data.frames when building a linear regression model.

A dataset divided into training and test observations.

🧪 Training vs. Test Data

  • We use training data to train/fit the linear regression model.
    • We then make a prediction using test data, which are unseen/new from the viewpoint of the trained linear regression model.
  • In this way, we can test whether our model performs well in the real world, where unseen data points exist.

🌀 Overfitting

Comparison of model fit and overfitting.

🛠️ Model Construction and Evaluation

The model construction and evaluation workflow.

🎲 A Little Bit of Statistics for the Uniform Distribution

  • The probability density function for the uniform distribution looks like:

  • With the uniform distribution, any values of \(x\) between 0 and 1 is equally likely drawn.

The uniform probability density between zero and one.

  • We will use the uniform distribution when splitting data into training and testing data sets.

🔀 Randomization in the Sampling Process

  • Why do we randomize when splitting given data into training and test data?
    • Randomizing the sampling process helps the training and test sets have similar distributions within the observed sample.
    • If the sample does not properly represent the entire population, the model result is biased toward the sample.
  • Suppose the splitting process is not randomized, so that the observations with pm25 > 20 are in the training data and the observations with pm25 <= 20 are in the test data.
    • What would be the model result then?

🏷️ Dummy Variables in Linear Regression

📈 Motivation: Treating Categorical Variables in Linear Regression

  • Linear regression models require numerical predictors, but many variables are categorical.

    • Example: similar smoke and weather conditions but different calendar months.
  • The Approach:
    Convert categorical variables into numerical format using dummy variables.

  • Why Do This?

    • Allows the model to compare different categories.
    • Each dummy variable indicates the presence (1) or absence (0) of a category.

🔢 What are Dummy Variables?

Definition: Binary indicators (0 or 1) representing categories.

Purpose: Transform qualitative data into a quantitative form for regression analysis.

Example: \[ D_i = \begin{cases} 1, & \text{if the observation belongs to the category} \\ 0, & \text{otherwise} \end{cases} \]

🏷️ Dummy Variables in Regression Models

Consider a regression model including a dummy variable: \[ y_i = \beta_0 + \beta_1 x_i + \beta_2 D_i + \epsilon_i \]

  • \(x_i\): A continuous predictor.

  • \(D_i\): Dummy variable (e.g., calendar month, county).

  • Interpretation: \(\beta_2\) captures the difference in the response \(y\) when the category is present (i.e., \(D_i=1\)) versus absent.

⚠️ The Dummy Variable Trap

🔗 Multicollinearity

  • Multicollinearity happens in multivariate regression when two or more predictors are highly correlated, so they contain overlapping information.
  • Perfect multicollinearity means one predictor is an exact linear combination of other predictors.
  • Problem: For a categorical variable with \(k\) levels, using all \(k\) dummies causes perfect multicollinearity:

    • If you include all \(k\) dummy variables in the model, their values always sum to 1: \[ D_{1i} + D_{2i} + \cdots + D_{ki} = 1 \quad \text{(for each observation)} \]
  • This is problematic, because one dummy is completely predictable from the others.

  • The intercept already captures the constant part (1), making one of the dummy variables redundant.

✅ Avoiding the Dummy Variable Trap

  • Solution: Drop one dummy (choose a reference category)

  • The reference category is represented by a combination of \(\texttt{month}\) variables.

    • Dummy for the reference category is 1 if all the rest of the dummies is 0.
    • Dummy for the reference category is 0 otherwise.
  • Proper model: \[ y_i = \beta_0 + \beta_1 D_{1, i} + \beta_2 D_{2, i} + \cdots + \beta_{k-1} D_{(k-1), i} + \epsilon_i \]

  • Interpretation:

    • Each \(\beta_j\) (for \(j=1,2,\ldots,k-1\)) represents the difference from the reference category.

💻 Dummy Variable Regression in R

In R, factors automatically generate dummies and avoid the dummy variable trap.

# Set January as the reference month
# dtrain and dtest come from Classwork 8
model <- lm(pm25 ~ hms_heavy_days + tmax + month, data = dtrain)

stargazer(
  model,
  type = "html",
  title = "PM2.5 with Month Dummies (Reference = January)",
  dep.var.labels = "PM2.5 (µg/m³)",
  digits = 3
)

📊 Residual Plots

📉 Residuals

  • Model equation: \(Y_{i} \,=\, \beta_{0} \,+\, \beta_{1}X_{1,i} \,+\, \beta_{2}X_{2,i} \, + \, \epsilon_i\)
    • \(\epsilon_i\) is a random noise, or a statistical error:

\[ \epsilon_i \sim N(0, \sigma^2) \]

  • Errors have a mean value of 0 with constant variance \(\sigma^2\).

  • Errors are uncorrelated with \(X_{1,i}\) and with \(X_{2, i}\).

📉 Residuals

  • If we re-arrange the simple regression equation, \[\begin{align} {\epsilon}_{i} \,=\, Y_{i} \,-\, (\, {\beta}_{0} \,+\, {\beta}_{1}X_{1,i} \,). \end{align}\]

  • \(\texttt{residual_error}_{i}\) is the estimated counterpart of the unobserved error \(\epsilon_{i}\), denoted by \(\hat{\epsilon_{i}}\).

\[ \begin{align} \hat{\epsilon_{i}} \,=\, &Y_i \,-\, \hat{Y}_i\\ \,=\, &Y_{i} \,-\, (\, \hat{\beta_{0}} \,+\, \hat{\beta_{1}}X_{1,i} \,) \end{align} \]

📊 Residual Plots

  • Residual plot: scatterplot of

    • fitted values on x-axis
    • residuals on y-axis
  • A residual plot can be used to diagnose the quality of model results.

  • We assume that \(\epsilon_{i}\) have a mean value of 0 with constant variance \(\sigma^2\):

    • A well-behaved residual plot should bounce randomly and form a cloud roughly at the level of zero residual, the perfect prediction line.

📊 Residual Plots

Training residuals from the wildfire month-dummy regression against fitted PM2.5. The red smoother shows the average residual pattern.

  • On average, are the predictions correct?
  • Are there systematic errors?

🔎 Examples

Generic residual-plot examples showing random clouds, curvature, and changing variance.

🔎 Unbiasedness and Homoskedasticity

  • No systematic mean pattern: mean residual is ~0 within thin vertical strips

  • Homoskedastic: similar spread of residuals across fitted values

  • If residual variance changes with fitted values ⇒ heteroscedasticity

🔎 What happens if biased?

  • The model consistently overpredicts or underpredicts for certain values.
    • Indicates that the model might be misspecified—perhaps missing important variables or using an incorrect functional form.
    • Systematic errors can weaken predictions and inference. A residual plot alone does not establish coefficient bias.

📏 What happens if heteroscedasticity is present?

  • Consequences of heteroscedasticity:
    • 📉 Inefficient coefficient estimates: Under the zero-conditional-mean assumption, OLS estimates remain unbiased but need not have the smallest variance.
    • ❌ Incorrect conventional standard errors: Homoskedastic standard-error formulas can give unreliable p-values and confidence intervals.
    • ⚠️ Misleading inferences: Predictors may appear statistically significant or insignificant incorrectly.
    • 🎯 Unequal prediction uncertainty: Errors can have greater spread at higher fitted values even when the conditional mean is correctly specified.

💻 Residual Plot in R

# The wildfire regression on the dummy-variable slide, using training rows
model_month <- lm(pm25 ~ hms_heavy_days + tmax + month, data = dtrain)
aug_model <- broom::augment(model_month)

ggplot(aug_model, aes(x = .fitted, y = .resid)) +
  geom_point(alpha = 0.25) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_smooth(se = FALSE, method = "loess", formula = y ~ x) +
  labs(
    x = "Fitted PM2.5 (µg/m³)",
    y = "Residual (µg/m³)",
    title = "Wildfire PM2.5: Training Residuals"
  )