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
Instructions — read these; do the work in the hw-08.qmd in your own repo
This assignment is due Wednesday, December 2, at 11:59pm. To be considered on time:
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.
In this assignment, you will…
dnorm() and see when the pooled curve shows one peak or two;pnorm();hw-08. It contains the starter documents you need.source("homework_08_helpers.R") resolves.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.
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.
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
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.
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.
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.
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)\).
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?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)}. \]
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).
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.
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.
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.
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\).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.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.
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}}\).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.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. |