DATA 419 homework #4: kNN, cross-validation, and PCA (+40XP)

Due: Sat, 11/7, midnight

Finding structure in your own data

In homework #1, you built regression models using the data set you chose earlier in the semester. In this homework, you’ll return to it and expand your analysis.

This time, you’ll use two response variables: a categorical response for kNN classification, and a quantitative response for principal components regression (PCR). You’ll explore three ideas:

As in homework #1, you’ll write Python code to do the analysis and then prepare a short report explaining what you discovered. The goal is not necessarily spectacular predictive accuracy; it’s to learn something interesting about your particular data set.

Preparation

Prep 1. Choose your variables

Choose the following from your data set:

  1. One categorical response variable \(y_{cat}\) that you’d like to predict using kNN. Two or a few categories will be easier to work with than dozens. Make sure there are enough observations in each category to support 5-fold cross-validation. (At least 20, and preferably 40+, of each class. You can use the .value_counts() method on your response variable column to help figure this out.)
  2. One quantitative response variable \(y_{num}\) that you’d like to predict using PCR. You can reuse the numerical response you chose for homework #1, or choose a different one.
  3. Two numerical predictors \(x_1\) and \(x_2\) for which you suspect there might be some relationship with \(y_{cat}\). You’ll use these to draw two-dimensional kNN decision regions.
  4. A larger collection of predictors for Parts 2–5. It can include the first two numerical predictors, additional numerical predictors, and (if appropriate) categorical predictors. As long as you don’t have zillions, it’s perfectly fine to choose “all your predictors” for this (except for the response variables, of course). Make sure to have at least three numerical/encoded features in the final matrix so you can examine three principal components.
  5. A real-world identifier for your observations, if you have one: a person’s name, a country, a team, a song title, etc. You’ll use some of these identifiers to label points on a plot. An identifier is not a predictor.

As before, don’t use row numbers, names, IDs, or other bookkeeping fields as predictors just because they’re available. Avoid categorical predictors with enormous numbers of distinct values; one-hot encoding can turn one such variable into hundreds or thousands of columns.

Prep 2. Get the data ready

Use the data-loading code/package you developed for homework #0. Clean, recode, or combine columns as necessary so that each row represents one observation with known responses and usable predictors. You may use different subsets of rows for classification and regression if missing values require it, but keep your predictors and response aligned within each analysis.

Take a look at how many observations you have in each category of \(y_{cat}\). If one category is very rare, ordinary accuracy can be misleading, and some cross-validation folds might not contain enough examples of it. Choose a sensible target or combine categories only when the combination makes real-world sense.

You’ll need to standardize numerical predictors using StandardScaler. If you include categorical predictors in your larger feature set, encode them appropriately (OneHotEncoder for unordered categories; OrdinalEncoder only when an order is meaningful). ColumnTransformer and Pipeline will be useful here.

Important: For any cross-validated model, scaling, encoding, and PCA must be fitted inside each training fold, not once on the entire data set before cross-validation. The easiest way to guarantee this is to put the preprocessing steps and the estimator in a sklearn Pipeline, and pass that pipeline to GridSearchCV.

Unlike homework #1, we’ll rely primarily on cross-validation, rather than evaluating everything on one train/test split. We’ll use accuracy to evaluate kNN classification and \(R^2\) to evaluate PCR, always on held-out cross-validation folds rather than the data used to fit each model.


1. Draw some kNN decision regions

Using only \(x_1\) and \(x_2\) to predict \(y_{cat}\), fit three KNeighborsClassifier models, with three substantially different choices of \(k\):

Adjust these numbers if your data set’s size calls for it. Standardize the two numerical features first: nearest-neighbor distances are sensitive to the scale of the axes.

Use DecisionBoundaryDisplay.from_estimator(..., response_method="predict") to show the decision regions for each classifier. Overlay the actual observations as colored dots, with color indicating the true response category. Make three plots, or one figure with three side-by-side panels. Use the same axis limits for all three, so the changes are easy to see.

Label the axes and identify the value of \(k\) on each plot. Include a legend (or some other clear indication) of which color represents which response category.


2. Find a good \(k\) using cross-validation

Now use your larger set of predictors from the preparation section to predict \(y_{cat}\). This is a separate kNN experiment: unlike Part 1, you are no longer restricted to two dimensions.

Build a pipeline that preprocesses your predictors and then runs KNeighborsClassifier. Pass it to GridSearchCV, using prediction accuracy (scoring="accuracy") and 5-fold cross-validation.

(A note on naming: if the kNN step in your pipeline is named knn, its grid parameter will be called knn__n_neighbors.)

Explore a reasonably large range of \(k\) values, such as 1 through 50, or another broad but computationally feasible range for your data set. Don’t include values that would exceed the number of training observations in a fold.

Your program should:

  1. Print the best \(k\) and its mean cross-validation accuracy (best_params_ and best_score_).
  2. Produce a graph with \(k\) on the horizontal axis and mean cross-validation accuracy on the vertical axis. With a single scoring metric, the values are available in cv_results_['mean_test_score'].
  3. Print the accuracy of a simple majority-class baseline: what fraction of your observations belong to the most common response category? This gives you a reference point for judging whether your classifier is accomplishing much.

(Obviously don’t select the winning \(k\) based on its accuracy on the same observations used to train it. That’s precisely the problem cross-validation is meant to address.)


3. Discover your principal components

Use the same larger predictor set you used in Part 2. Standardize the numerical features and encode any categorical features, so that PCA receives an entirely numerical matrix. PCA does not use either response variable to calculate the components.

Fit PCA to this matrix and examine its first three principal components.

Your program should print:

When you read the loadings, pay attention to which features have the largest positive and negative weights. Is there a plausible real-world interpretation for each component? You may find that one seems to measure something recognizable, while another is hard to interpret. That’s fine!

This PCA fit is for exploring and describing your data. In Part 5, where PCA becomes part of a predictive model, you’ll fit it inside cross-validation instead.


4. Make a map of your observations in PC space

Use the PCA results to project your observations onto PC1 and PC2.

Create a scatterplot with:

Choose labeled points thoughtfully, and keep the labels readable. You don’t need to label every observation. The idea is to make the plot say something about actual people, places, teams, objects, etc., rather than merely about anonymous rows.

Notice whether the response categories occupy different parts of this plot, overlap heavily, or show some other interesting pattern. Even though you’ll predict the quantitative response in Part 5, coloring this plot by the categorical response may reveal structure shared with the kNN task.


5. Use principal components to predict a quantitative response

Finally, let’s find out whether the principal components are useful for prediction, rather than just visualization. This time, you’ll predict your quantitative response \(y_{num}\), not the categorical response from Parts 1–2.

You’ll perform actual principal components regression (PCR): PCA followed by linear regression. Use the same larger predictor set as in Parts 2–4, but predict \(y_{num}\) instead of \(y_{cat}\):

  1. Preprocess the predictors (standardize numerical features and encode categorical features).
  2. Apply PCA to reduce them to a chosen number of components.
  3. Fit a LinearRegression model using those components.

Put all three steps in a single Pipeline. Use GridSearchCV with scoring="r2" and 5-fold cross-validation to tune pca__n_components. \(R^2\) measures regression performance, not classification accuracy; larger values are better, and negative values are possible.

Try every valid number of components from 1 through the total number of features in your encoded feature matrix. (If the number of features exceeds the number of training observations in a cross-validation fold, stop at the largest valid number of components.)

Your program should:

  1. Print the number of components giving the highest mean cross-validation \(R^2\), and that \(R^2\) (best_params_ and best_score_).
  2. Produce a graph with number of principal components on the horizontal axis and mean cross-validation \(R^2\) on the vertical axis.

The PCA must be fitted anew in each training fold. In particular, don’t first fit PCA to all your observations, compute the PC scores, and then cross-validate a regression model on those scores. That would allow information from the held-out folds to influence the transformation.


What to turn in

Send me an email with subject line DATA 419: homework #4 turnin and attach the following.

1. Your Python programs

Submit the actual .py source files. Two programs would be a natural organization: one for the kNN work (Parts 1–2) and one for the PCA/PCR work (Parts 3–5). You’re welcome to organize the code differently if it makes sense.

The programs should load your data, carry out the necessary preprocessing, run the analyses and cross-validation, print the requested numerical results, and generate the plots. Don’t send screenshots of code.

2. Your short report (one PDF)

Include your four main figures:

  1. The three kNN decision-region diagrams (which can be panels of one figure).
  2. Cross-validated kNN accuracy versus \(k\).
  3. Your PC1-versus-PC2 scatterplot, with some observations identified by name.
  4. Cross-validated \(R^2\) versus number of principal components.

Also include your PC1–PC3 loading table, the individual and cumulative explained-variance figures, the best \(k\) and kNN accuracy, and the best number of principal components and PCR \(R^2\). Identify both response variables in your report.

Then organize a few short, thoughtful paragraphs around these three open-ended questions:

A. What did kNN teach you about your data? Discuss what changed across the three decision-region diagrams, what the cross-validation curve looks like, and what (if anything) the best value of \(k\) suggests. How much better is your best kNN model than the majority-class baseline?

B. What did PCA reveal? Interpret the first three PCs as best you can using their loadings. How much of your data’s variation do the first three collectively account for? In the PC1/PC2 plot, do the positions of recognizable observations and the response-category colors tell an interesting story?

C. Was dimensionality reduction useful for predicting your quantitative response? How did cross-validated \(R^2\) change as you added principal components? Did a relatively small number of PCs perform as well as (or better than) using all of them? What did you learn, what surprised you, and what would you be cautious about concluding? (Remember that \(R^2\) and classification accuracy measure different things and should not be compared directly.)

This does not need to be a long formal paper. Prefer well-labeled plots and tables accompanied by a few insightful paragraphs over pages of prose. And if your models perform poorly, or your PCs resist interpretation, say so — that’s a legitimate finding, too.

As always, commit your work to your git repository before turning it in.


Questions?

Send email with subject line DATA 419 homework #4 help!! or come to office hours!