Due: Sat, 11/7, midnight
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.
Choose the following from your data set:
.value_counts() method on your
response variable column to help figure this out.)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.
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.
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.
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:
best_params_ and
best_score_).cv_results_['mean_test_score'].(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.)
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:
pca.components_ contains these
directions; matching them to your original (or encoded) feature names
will make the results much easier to understand.pca.explained_variance_ratio_ and np.cumsum()
may be helpful.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.
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.
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}\):
PCA to reduce them to a chosen number of
components.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:
best_params_
and best_score_).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.
Send me an email with subject line DATA 419: homework #4 turnin and attach the following.
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.
Include your four main figures:
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.
Send email with subject line DATA 419 homework #4 help!! or come to office hours!