Questions 1 through 3 include R and Python solutions. Use either language and run its code blocks in order. No solution is provided for the analysis skill in Question 4.
Extract the combined ZIP and run the code from its week-07 folder, which contains the data folder. The two languages use the same supplied observations in Questions 1 and 2. In Question 3, they use the same simulation model and settings but generate different random observations.
Question 1: LDA
Original question
Letβs start by estimating the components of LDA. From the lecture notes, for each target point , we find the class label with the largest score
Thus, we need to estimate:
the prior probabilities ;
the mean vector (centroid) for each class; and
the pooled covariance matrix .
Use saheart.csv, the SAheart data from ElemStatLearn. The two classes are defined by chd, the coronary heart disease indicator. Use all nine other variables as numerical predictors, coding famhist as 1 for Absent and 2 for Present. The following code constructs an predictor matrix and an -entry response vector , where is the number of observations.
Calculate the prior probabilities, class means, and pooled covariance matrix from these data. Use the pooled covariance denominator from the lecture, where is the number of classes.
Use your estimated values to predict the label of each observation in the training data. These are in-sample fitted labels. Provide the confusion matrix, with observed classes in rows and predicted classes in columns. Check that the dimensions of your matrices and vectors match. Calculate the scores yourself for this part.
Perform the same LDA analysis using MASS::lda in R or LinearDiscriminantAnalysis(solver="svd") in Python, using the same numerical predictors and empirical class priors. Provide the confusion matrix. Do the results match?
Solution
a. Estimate the LDA components.
Estimate each class mean separately, then pool the variation around those means. Using deviations from the overall mean would mix the separation between classes into the within-class covariance.
For classes , the estimates from the lecture are
and
Here and there are nine predictors. In the code, the rows of mu_hat and entries of pi_hat are ordered by class 0, then class 1. The matrix Sigma_hat is . Retain the specified 1/2 coding of famhist in both the manual and package fits.
There are 302 observations in class 0 and 160 in class 1, so the estimated priors are and . The pooled covariance uses denominator .
b. Calculate the scores and fitted labels.
Substitute the estimates into the discriminant score:
The larger score determines the fitted class. The code solves a linear system for each class instead of constructing the covariance inverse. Multiplying the predictor matrix by the nine-entry solution gives one score per observation; score therefore has 462 rows and two columns.
fit <- MASS::lda(X, grouping = y, prior = pi_hat)y_hat_package <-predict(fit, newdata = X)$classtable(Observed = y, Predicted = y_hat_package)
Predicted
Observed 0 1
0 258 44
1 73 87
Show the solution code
all(y_hat_package == y_hat)
[1] TRUE
Show the solution code
fit = LinearDiscriminantAnalysis(solver="svd", priors=pi_hat).fit(X, y)y_hat_package = fit.predict(X)print(pd.crosstab(y, y_hat_package, rownames=["Observed"], colnames=["Predicted"]))
Predicted 0 1
Observed
0 258 44
1 73 87
Show the solution code
print(np.array_equal(y_hat_package, y_hat))
True
Both packages give the same confusion matrix and agree with every manually calculated label. They implement the same LDA rule with the pooled within-class covariance and the same priors. The agreement checks the calculation; it does not establish performance on new observations. All 462 observations were used both to estimate the rule and to calculate this accuracy.
Question 2: QDA and marginal screening
Original question
In the lecture, ordinary QDA could not be fitted to the handwritten digit sample because its within-class covariance matrices were singular. Letβs consider selecting fewer variables and see whether this helps. For this question, use the full zip-train.csv.gz as the training data and zip-test.csv.gz as the test data, with all ten digit classes. These are the original zip.train and zip.test data from ElemStatLearn. Each file has no header: the first column is the digit label and the remaining 256 columns are pixel values.
Instead of using all 256 predictors, select the 40 with the largest marginal variances in the training data. Here, marginal variance means the variance of one pixel across all training observations. Use the original pixel values without standardizing them, and retain the same selected predictors in the test data.
Use MASS::qda in R or QuadraticDiscriminantAnalysis(tol=1e-8) in Python.
Fit QDA using these 40 predictors and report the test confusion matrix, with observed classes in rows and predicted classes in columns. Also report the test misclassification rate.
Did QDA fit successfully, and how well did it predict the test labels? Explain your findings using the class sample sizes, the number of selected predictors, and the within-class covariance estimates.
Repeat the analysis using the 10 predictors with the largest marginal variances in the training data. How does the test misclassification rate compare with the 40-predictor version? Why do you think this happens?
Solution
First rank the pixels by their marginal variances in the training data. Keep the original pixel values: standardizing would remove the variance differences used for screening. Use the same selected columns in the test data, without using the test observations to select them.
a. Fit QDA using the 40 pixels with the largest training variances. Both packages estimate the class priors from the training proportions. The confusion matrices below have observed digits in rows and predicted digits in columns, in the order 0 through 9.
There are 312 errors among the 2,007 test observations, so the test misclassification rate is , or 15.55%. The two languages give the same predicted labels.
b. The 40-pixel fit succeeds because the selected predictors have a nonsingular sample covariance matrix within every class in these data. This homework uses the full training file, with at least 542 observations per digit, rather than the lectureβs sample of 100 per digit. Thus, the lectureβs argument that there are more predictors than observations per class does not apply to this full file. Constant or linearly dependent pixels can still make the full 256-pixel covariance matrices singular; selecting these 40 pixels avoids that problem here.
The Python setting tol=1e-8 permits a small positive covariance eigenvalue in this example. It changes the numerical rank tolerance, not the fitted QDA model; no covariance regularization is added.
c. Now keep only the first 10 pixels in the same training-variance ranking and repeat the fit and test prediction.
The 10-pixel model has substantially higher test error on this split. Using fewer predictors reduces the number of covariance entries to estimate, but also removes information that can distinguish digits. Here, that information loss outweighs the benefit of estimating a smaller covariance matrix. Large marginal variance does not by itself guarantee that a pixel separates classes, and reducing the dimension does not always improve prediction.
Question 3: Compare LDA and QDA
Original question
In this simulation, we will study how the relative performance of LDA and QDA changes with the true covariance structure. The parameter controls the distribution from which we generate the data; it is not a tuning parameter of LDA or QDA.
Consider a classification problem with two equally likely classes, labeled 1 and 2, and covariates. The first two covariates have the class-conditional distributions
In both classes, the remaining eight covariates are independent standard normal variables, independent of the first two. Consider
For each value of , generate 100 training observations and 1,000 independent test observations from each class. Fit ordinary LDA and QDA using all 10 covariates and equal class priors. Estimate the class means from the training data, with one pooled covariance matrix for LDA and one full covariance matrix per class for QDA. Set a random seed and report it.
Generate one dataset for each value of . Fit both methods and calculate their test misclassification rates. Within each setting, use the same training and test observations for the two methods.
At each fixed value of , repeat the experiment 50 times, generating new training and test observations in each repetition. Plot average test error against in one figure, with one curve for LDA and one for QDA. These curves compare performance across different data-generating distributions.
Compare the two methods at small and large values of . How does changing the true covariance structure affect their relative performance? Explain the pattern using their covariance assumptions and the bias-variance trade-off. How can the eight noise covariates affect performance even though they contain no information about the class label?
Solution
a. At , the two classes have the same covariance matrix, so LDAβs covariance assumption is correct. As increases, the first two predictors tilt in opposite directions in the two classes. QDA can represent this difference, but must estimate more covariance parameters. We first compare the fitted methods on one training and test sample at each value of .
Both language versions use seed 43207 and the stated model, with 100 training and 1,000 test observations per class. Their random observations differ because R and NumPy use different random-number generators. Within each setting, LDA and QDA use exactly the same observations and equal class priors.
Each row compares the two fitted methods on one training and test sample. Another realization can change the values or even which method has the lower error. We therefore repeat the comparison before interpreting the overall pattern.
b. Generate fresh training and test observations in every repetition. The stored errors have three dimensions: repetition, value of , and method. Averaging over the 50 repetitions gives one mean error for each method at each . The code continues from part a without resetting the seed.
Average test error over 50 independent training and test samples at each value of rho. Both methods use the same observations within a repetition.
c. LDA has lower average error at small . At , both language versions give average error around 0.17 for LDA and 0.20 for QDA. Pooling estimates a covariance matrix that is truly shared by the classes. QDA estimates two separate matrices even though the population matrices are equal, adding estimation variability without gaining a more appropriate boundary.
For larger , the class covariance matrices differ substantially. Their off-diagonal entries have opposite signs, so pooling averages away information about the different orientations of the two classes. QDA retains this information and can fit a curved boundary. At , its average error is about 0.10, compared with about 0.17 for LDA in both language versions. In this experiment, its lower approximation bias outweighs the additional estimation variability. The curves compare different population distributions; is not selected as a tuning parameter.
The eight extra predictors have the same independent standard normal distribution in both classes, so they carry no class information. Nevertheless, both methods estimate their means, variances, and covariances with the other predictors from finite samples. Those estimated differences can change fitted decisions. QDA is more affected because it estimates a full covariance matrix separately in each class. Each ten-dimensional covariance matrix has distinct entries, so QDA estimates 110 covariance entries compared with LDAβs 55. These noisy estimates help explain why QDA can perform worse when the true class covariances are similar, despite its greater flexibility.
The repeated simulations describe average performance under this model and these sample sizes. They do not imply that QDA wins on every sample with a large , or that increasing correlation improves every classification method.
Question 4: Create and use an LDA/QDA analysis skill