H. Sherry Zhang
Department of Statistics and Data Sciences
University of Texas at Austin
library(usethis) create_from_github("SDS322E-26FALL/1103-ml2", fork = FALSE)
In ML in practice I, your group picked a dataset and turned it into a question: one row, a response variable, and candidate predictors.
In K-nearest neighbor and cross validation, we tuned a KNN model for the penguins.
Today, put the two together: build a tuned KNN model for your group’s question.
The same workflow as the penguins example:
Step 0: Training-testing split
Step 1: Specify the model, with the number of neighbors left to tune
Step 2: Specify the pre-processing recipe
Step 3: Build a workflow
Step 4: Fit the model
Step 5/6: Predict and calculate classification metrics on the testing data
| Response | Step 1 | Step 6 |
|---|---|---|
| numeric | nearest_neighbor(mode = "regression", neighbors = tune()) |
rmse, rsq |
| binary | nearest_neighbor(mode = "classification", neighbors = tune()) |
accuracy, roc_auc |
Penguins only needed step_normalize(). Real data usually needs more:
| Problem | Recipe step |
|---|---|
| Categorical predictors: KNN needs numbers to compute distances | step_dummy(all_nominal_predictors()) |
A categorical predictor with many rare levels (e.g. country) |
step_other(all_nominal_predictors(), threshold = 0.05) |
| Missing values | step_naomit() |
| Predictors on different scales | step_normalize(all_numeric_predictors()) |
| A column with only one value | step_zv(all_predictors()) |
Large data: KNN computes the distance to every training row, so it is slow on big data. Work with a random subsample first:
In your group, use your question from part I and build a tuned KNN model. Share at the end:
autoplot()) and the best \(k\)The script ml2.R in the repository loads the four datasets and has the steps as comments. The penguins script from Nov 4 (knn.R) has all the code you need.