Skip to main content

HW 08: Hidden groups and many predictors

Instructions — read these; do the work in the hw-08.qmd in your own repo

ImportantDue date

This assignment is due Wednesday, December 2, at 11:59pm. To be considered on time:

  • Your final rendered document (with all code, output, and answers) pushed to your GitHub repo
  • That same document, as a PDF, submitted on Gradescope

Introduction

Galton pooled the heights of men and women and found a curve that looked closer to a single normal curve than he expected. In Problem 1, you will build mixtures of two normal curves, see when the hidden groups become visible, and ask how well one new measurement can be assigned to its group.

Problem 2 picks up from Lecture 25’s omitted-variable story and asks the opposite question: what happens when we add predictors that carry no signal? You will first add predictors to a regression whose true slopes you know, then choose predictors for a fixed dataset by how they perform on held-out rows, and finally test your chosen model once on fresh data.

Learning goals

In this assignment, you will…

  • build a mixture of two normal curves with dnorm() and see when the pooled curve shows one peak or two;
  • use Bayes’s rule to find the probability that a new measurement came from each group, with equal and unequal group weights;
  • calculate the error rates of a classification rule with pnorm();
  • see how adding predictors changes the center and the spread of estimated slopes, and the error on training rows and on new rows;
  • screen candidate predictors by their gains on validation rows over many random splits, then test a chosen model once on held-out data.

Getting started

  • Go to the statistical-history organization on GitHub. Click on the repo with the prefix hw-08. It contains the starter documents you need.
  • Clone it the same way you cloned HW 07’s repo — see Lab 01 if you need the steps again.
  • Keep the supplied folder arrangement so source("homework_08_helpers.R") resolves.
  • Run the document top to bottom before you submit, and keep the seeds you used so your results can be reproduced. The template sets the seeds Problem 2 uses.

Materials and submission

Work in hw-08.qmd in your homework repository. Include your calculations, plots, and written answers. Base R is sufficient. Keep homework_08_helpers.R and the data/ folder beside your .qmd.

WarningFilling in the template

Replace each YOUR CODE HERE comment with your own code. In the commented skeletons, replace each ___ with an R expression, then remove the leading # from those code lines to run them. Write each response after Your answer:. Keep code and output visible. An untouched template can render, but is not a completed submission. Once you add code, the document will not render if any chunk has an error.

Problem 1 — When can we see two groups?

When Pearson proposed adding two normal curves to describe a set of measurements, Galton told him that he had tried pooling measurements of adult men and women. The pooled measurements looked closer to a normal curve than he had expected. Could someone see the two groups in the pooled curve? And even if the two group curves are given, how well can you tell where one new measurement came from? Revisit the excerpt from Galton’s letter. Stigler, p. 333

The excerpt leaves the measured trait and the source of the data open. Galton separately published standing-height percentiles for visitors to his Anthropometric Laboratory at the 1884 International Health Exhibition. The first model below uses the reported female and male medians, 63.3 and 67.9 inches, as normal means. The common standard deviation of 2.7 inches is a rounded approximation based on the two groups’ 5th-to-95th percentile ranges. Galton’s published percentile table, p. 277

Working with dnorm()

In Lab 09 you used rnorm(n, mean, sd) to draw n random numbers from a normal distribution, and a histogram of many draws took on the familiar bell shape. dnorm() describes that same distribution without drawing anything: dnorm(x, mean, sd) gives the value of the normal density curve at x, the smooth curve those histograms approach. Given a whole vector of values, it returns one density value for each. So to draw a curve, make a fine grid of values with seq(), compute the density at each one, and connect the points with plot(..., type = "l") ("l" for line). Here is the normal curve with mean 0 and standard deviation 1, drawn between −5 and 5:

z <- seq(-5, 5, by = 0.01)          # 1001 evenly spaced values from -5 to 5
dens <- dnorm(z, mean = 0, sd = 1)  # the density at each value
length(dens)
[1] 1001

For a single value, dnorm() returns a single density value. At \(z = 1\):

dnorm(1, mean = 0, sd = 1)
[1] 0.2419707

That number, about 0.242, is the density at \(z = 1\): the point on the curve directly above \(z = 1\), marked with a dot in the plot below. A density value is not a probability on its own. Multiplying a curve by a number multiplies every density value: 0.5 * dens has the same shape, with every value halved. lines() adds a curve to a plot that already exists.

plot(z, dens, type = "l", lwd = 2, xlab = "z", ylab = "Density",
     main = "Normal curve, mean 0, SD 1")
points(1, dnorm(1, mean = 0, sd = 1), pch = 19)              # the density at z = 1
segments(1, 0, 1, dnorm(1, mean = 0, sd = 1), lty = 3)       # from the axis up to it
lines(z, 0.5 * dens, lty = 2)                                # every density value halved
legend("topright", c("dnorm(z)", "0.5 * dnorm(z)"), lty = c(1, 2),
       lwd = c(2, 1), bty = "n")

In the models below, each group has its own normal curve. In Part 1a you will draw each one this way on a grid of heights in inches, multiply it by its group’s weight, and add the two to get the mixture.

Working with pnorm()

A probability comes from area under a density curve. pnorm(t, mean, sd) gives the area under the normal curve to the left of t: the probability that a draw from that distribution is below t. Adding lower.tail = FALSE gives the area to the right of t instead. The two areas add to 1, because the whole area under a density curve is 1.

pnorm(1, mean = 0, sd = 1)                      # area below z = 1
[1] 0.8413447
pnorm(1, mean = 0, sd = 1, lower.tail = FALSE)  # area above z = 1
[1] 0.1586553

The shaded regions below are the two areas these lines calculate.

In Part 1c you will use these areas to find how often a classification rule guesses the wrong group.

The models

First draw a group label, \(G\): \(A\) with probability \(w_A\), or \(B\) with probability \(w_B\), where \(w_A + w_B = 1\). These are the weights of the two groups. Then draw a height \(X\) from that group’s normal distribution. We use the same standard deviation and the same midpoint in all three models. The second and third rows widen the gap in the first row to see what changes.

Model Mean of \(A\) (inches) Mean of \(B\) (inches) Common SD (inches)
Exhibition heights 63.3 67.9 2.7
Wider gap 62.225 68.975 2.7
Widest gap 60.2 71.0 2.7

Let \(f_A(x)\) and \(f_B(x)\) be the values of the two normal density curves at \(x\). Use dnorm(x, mean = ..., sd = ...) to evaluate a density curve. The mixture density is the sum of the two weighted curves,

\[ f(x) = w_A f_A(x) + w_B f_B(x). \]

It describes the measured heights when the group labels are hidden. Use the supplied parameters throughout.

Part 1a — Look at the pooled measurements

In this part the two groups are equally common: \(w_A = w_B = \tfrac12\), so the mixture density is \(f(x) = \tfrac12 f_A(x) + \tfrac12 f_B(x)\).

  1. Before plotting, predict whether the model based on exhibition heights will have one peak or two. Calculate the gap between the two means in standard deviation units for each model.
  2. Plot the pooled density and the two weighted component curves for each model. Use the same scales in all three panels. A grid such as seq(50, 82, by = 0.02) is fine. Use a line type or color to show which curve describes the distribution of the unlabeled heights. Between which two of your tested gaps does the pooled curve first show two peaks?

Part 1b — Classify a new measurement

Bayes’s rule combines two pieces of information: how often a group is drawn (its weight) and how much density its curve puts near the observed height. Given a new height \(x\), the model gives

\[ \Pr(G=B\mid X=x) = \frac{w_B f_B(x)}{w_A f_A(x) + w_B f_B(x)}. \]

  1. For the exhibition and widest-gap models, calculate this probability at \(x=65.6\), \(66.6\), and \(68.6\) inches. Report it in a table and indicate which label you would guess if all wrong guesses cost the same. Mark ties. Explain which of these heights stays equally ambiguous as the means move farther apart.
  2. Return to the exhibition model and change the group probabilities to \(w_A=0.8\) and \(w_B=0.2\). Recalculate the probability at \(66.6\) inches. Compare your guess with the one from the equal-weight model. What information did the new weights add?

Part 1c — How often will the rule get it wrong?

With equal weights and equal standard deviations, guess \(A\) below the midpoint of the means and \(B\) above it. Use the original equal weights for this part. In every model the midpoint is 65.6 inches.

The midpoint is the rule’s boundary. For a new height \(X\), the rule guesses \(A\) if \(X < 65.6\) and \(B\) if \(X > 65.6\). So “guess \(B\)” means the same thing as “\(X > 65.6\)”, and “guess \(A\)” the same as “\(X < 65.6\)”.

The rule makes an error when it guesses \(B\) for a height that actually came from group \(A\), or guesses \(A\) for a height that actually came from group \(B\). Work out each kind of error separately, then combine them. The function pnorm(t, mean = ..., sd = ...) gives the area below a threshold \(t\). Add lower.tail = FALSE for the area above (see Working with pnorm() above).

  1. Errors on heights from group \(A\). “Given \(G = A\)” means: suppose the new height came from group \(A\). Then \(X\) is a draw from \(A\)’s normal distribution, with \(A\)’s mean and the common standard deviation. The rule makes an error if \(X\) lands above the boundary, where it guesses \(B\): \[ \Pr(\text{guess } B \mid G = A) = \Pr(X > 65.6 \mid G = A). \] In the exhibition model, for example, this is the probability that a draw from a normal distribution with mean 63.3 and SD 2.7 is above 65.6 inches. Calculate it for the exhibition and widest-gap models. Which tail of \(A\)’s curve is this, and why?
  2. Errors on heights from group \(B\). Calculate \[ \Pr(\text{guess } A \mid G = B) = \Pr(X < 65.6 \mid G = B) \] for both models. Which tail of \(B\)’s curve is this? Compare it with your answer to 1.
  3. The overall error rate. For a new draw whose group we do not know, the overall error rate is the probability that the rule guesses the wrong group. The draw comes from \(A\) with probability \(w_A\) and from \(B\) with probability \(w_B\), so \[ \text{overall error} = w_A \Pr(\text{guess } B \mid G = A) + w_B \Pr(\text{guess } A \mid G = B). \] Calculate it for both models with \(w_A = w_B = \tfrac12\).
  4. Write a short paragraph to Galton. Use your plots and error rates to explain how two groups can produce one visible peak, and why even two visible peaks leave some individual heights ambiguous. If the means were also equal, what could a new height tell you about the group that produced it?

Problem 2 — How many predictors can we afford?

In Lecture 25, leaving a relevant predictor out could change the slope we estimated for another predictor. What happens when we add predictors that carry no signal? In the first experiment, the true slopes are known, so you can check how well least squares recovers them. In the second, you have a fixed dataset and must decide which columns are worth keeping from their performance on held-out rows.

Part 2a — Add predictors to a known signal

In this part you simulate many small studies in which you know the truth. In each study, all 50 predictors, \(X_1\) through \(X_{50}\), are drawn independently from a standard normal distribution. The outcome is \(Y = 2X_1 - 1.5X_2 + \varepsilon\), with independent standard normal noise \(\varepsilon\). Thus \(X_1\) and \(X_2\) have true slopes 2 and \(-1.5\). Treat the other columns as candidates and see what happens when you give them room in the fit. Each study has 28 training rows, used to fit the models, and 160 new rows drawn from the same rule, used only to check predictions.

TipHelper functions in this part

One course-written helper, from homework_08_helpers.R, simulates a study. The other two are ordinary R.

Call What it does for you
draw_regression_study() Simulates one study from the rule above. It takes no arguments. It returns a list of two data frames, each with columns Y and X1 through X50: $train holds the 28 training rows and $test the 160 new rows. Every call makes new random draws, so set the seed first to reproduce a study. For example, after study <- draw_regression_study(), fit with data = study$train and predict with newdata = study$test
reformulate(cols, response = "Y") Builds a model formula from a vector of column names. reformulate(c("X1", "X2"), response = "Y") gives Y ~ X1 + X2
mean((y - pred)^2) Mean squared error (MSE), defined below: the average squared difference between observed values y and predictions pred

Use the first \(p\) columns of predictors, so a model of size \(p=5\) uses X1 through X5; paste0("X", seq_len(p)) makes those names. Here \(p\) counts predictors, and lm() also fits an intercept.

Mean squared error. To measure how far a model’s predictions are from the observed outcomes, square each prediction error and average them: \[ \text{MSE} = \frac{1}{n}\sum_{i=1}^{n} (y_i - \hat y_i)^2, \] where \(y_i\) is the observed outcome in row \(i\), \(\hat y_i\) is the model’s prediction for that row, and \(n\) is the number of rows. In R this is mean((y - pred)^2). A smaller MSE means predictions closer to the outcomes. On the training rows, MSE measures how closely the model fits the data it was fitted to. On the new rows, it measures how well the model predicts data it has never seen, and that is what we care about: we want a model with low MSE on new rows.

  1. Set the seed to 808 and draw one training set. For \(p=28\) and \(p=50\), report the number of coefficients the model would need, fit$rank (the number of independent columns in the regression), and the number of NA coefficients. Why can the full list of coefficients fail to have a unique least-squares solution even when the training fit is nearly exact? From here on, Part 2a uses only models with fewer than 28 predictors, \(p < 28\).
  2. Reset the seed to 808 and repeat the experiment 200 times. Each repetition draws a fresh study with draw_regression_study() and fits all six sizes, \(p=2,5,8,12,18,24\), on that study’s same 28 training rows, recording the estimated slopes on X1 and X2. After 200 repetitions you have 200 estimates of each slope at each \(p\), one from each simulated study. Find the mean of the 200 estimates at each size, and use var() to find their variance, which measures how much the estimate changes from one simulated study to the next. The template supplies code for two plots. The first shows, for each \(p\), a boxplot of the 200 estimates of each slope, with their mean as a blue dot and the true slope as a dashed line. The second shows the variance of each slope’s estimates against \(p\). Explain what the boxes, dots, and lines show, and whether the center or the spread of the estimates changes more as you add predictors.
  3. In the same 200 draws, record the MSE on the training rows and on the 160 new rows for each fit. (Reset the seed to 808 and repeat the loops from question 2; the same seed gives the same 200 studies.) Plot the two mean MSEs against \(p\). Remember that the goal is a low MSE on the new rows. Where does adding predictors make the training fit look better while hurting prediction on new rows? Explain how the slope plots help you understand this pattern.

Part 2b — Screen predictors in one split

data/screening_development.csv contains one fixed dataset with 40 rows, a response Y, and 50 possible predictors X1 through X50. An unknown subset of the columns carries signal. In every split you will offer 8 of the 50 predictors. You will use the other data file in Part 2c.

Use one random split to see how the scoring works before repeating it. Start with set.seed(20261127) and draw the rows before drawing the columns so everyone starts with the same split.

  • Sample 28 row numbers without replacement for training. The other 12 rows are your validation rows. Separately, sample 8 predictor names, also without replacement.
  • Fit an lm() with all the offered predictors kept, on the 28 training rows, and calculate its MSE on the 12 validation rows. Call it \(\text{MSE}_{\text{kept}}\).
  • For each offered predictor, refit on the same training rows with that predictor dropped, and calculate the new model’s MSE on the same validation rows, \(\text{MSE}_{\text{dropped}}\). The gain from keeping the predictor is \(\text{MSE}_{\text{dropped}}-\text{MSE}_{\text{kept}}\). Call it a win for that predictor if its gain is positive.
  1. Show the gain table for your first split and identify the winners. Explain what a positive gain tells you about a predictor in that particular fit and split.
  2. Repeat the whole procedure above 300 times in all, counting your first split as one of them. Each time, use the same development dataset but draw a new split of the rows and a new set of 8 predictors, then calculate the gains. Because each split offers only 8 of the 50 predictors, each predictor is offered in only some of the 300 splits. For each predictor, count how many splits it was offered in, average its gains over those splits, and find the fraction of those splits in which it was a win. Show the ten predictors with the highest average gain. Why divide the number of wins by the number of times that predictor was offered, rather than by 300?

Part 2c — Choose a model and test it once

  1. Use the screening table to choose a final set of predictors. State your rule and the names you kept before reading the test file. For example, you can look for a clear gap between the strongest average gains and the rest, using the win fractions as context.
  2. Refit your chosen model on all 40 development rows. Now load data/screening_test.csv and report its root mean squared error (RMSE, the square root of MSE) on the 200 fresh rows. Compare it with the RMSE from predicting the development mean of Y for every test row. Explain why the 300 splits, which reuse development rows, play a different role from this final test.

Data sources

The data in data/ were simulated for Problem 2; all quantities are unitless. data/SOURCES.md in your repo describes both files.

File Observations Use
screening_development.csv 40 Draw training and validation rows, choose predictors, and fit the final model.
screening_test.csv 200 Evaluate the final model after choosing its predictors.