Use either R or Python and run that language’s code blocks in order. The R code generates a random split with seed 432. The supplied breast-cancer-split.csv records those same rows for Python, since the two languages do not generate the same split from the same seed. Both solutions therefore use 398 training observations and 171 test observations. Your numerical results can differ if you choose another random split.
Set a random seed and randomly split the observations into 70% training and 30% test data. Use the same split for every model. Standardize the predictors using the training means and standard deviations, and apply the same transformations to the test data.
Fit ordinary logistic regression with an intercept and no penalty, and KNN with Euclidean distance, equal neighbor weights, and
Using the estimated probabilities for y = 1 on the test data, plot all six ROC curves in one figure and report their AUC values. Which of the six fitted models do you prefer? Give a brief justification based on your results.
Solution
We compare the models using their estimated probabilities of malignancy, not class predictions at a single cutoff. For KNN, this probability is the proportion of malignant cases among the nearest training observations:
where is the set of those neighbors. Averaging the numeric responses 0 and 1 gives this probability directly.
First split the data, then estimate each predictor’s mean and standard deviation from the training observations. Use those same values to standardize both sets. This prevents the test observations from influencing the fitted distance scale.
from pathlib import Pathimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.metrics import roc_curve, roc_auc_scoredata_dir = Path("data")ifnot (data_dir /"breast-cancer.csv").exists(): data_dir = Path("practice/weeks/week-06/data")data = pd.read_csv(data_dir /"breast-cancer.csv")# Use the split generated with seed 432 in the R solution.split = pd.read_csv(data_dir /"breast-cancer-split.csv")train = data.loc[split["split"].eq("train")]test = data.loc[split["split"].eq("test")]predictors = ["mean_radius", "mean_texture", "mean_smoothness"]x_bar = train[predictors].mean()s = train[predictors].std(ddof=1)X_train = ((train[predictors] - x_bar) / s).to_numpy()X_test = ((test[predictors] - x_bar) / s).to_numpy()y_train = train["y"].to_numpy()y_test = test["y"].to_numpy()
Fit ordinary logistic regression and the five KNN models. In R, knn.reg averages the 0/1 responses; in Python, predict_proba returns the same neighbor proportions. Logistic regression includes an intercept, and C=np.inf removes the penalty in the Python fit.
Test ROC curves for logistic regression and five KNN fits on the same 171 observations.
For this split, I prefer logistic regression. Its test AUC is , the largest of the six values, and it gives a simple fitted model. KNN with is nearly tied at , followed by at . The smaller neighborhoods have lower test AUCs: , , and for , respectively. The ROC curves show that the larger neighborhoods rank these test cases more effectively than does.
This is a comparison on one test split. A small AUC difference does not establish that one method is always better, and AUC measures ranking rather than the fraction of correct class predictions. For a final model-selection exercise, choose the method and using validation or cross-validation within the training data, then evaluate the chosen model on a fresh test set.
Question 2: Training and test ROC curves
Original question
Use the same data, training/test split, and standardization as in Question 1. Fit KNN with Euclidean distance, equal neighbor weights, and
Use each fitted model to estimate probabilities for both the training and test observations. For training predictions, include each observation itself among its nearest neighbors.
For each , use a separate panel to show the training and test ROC curves together. Report both AUC values.
Explain the difference between training and test performance and how it changes with . In particular, explain what happens at and why training performance may not reflect performance on new observations.
Solution
At , each training observation is its own nearest neighbor. Thus its fitted probability equals its observed response, giving a training AUC of 1. This perfect training ranking does not establish good prediction for a new observation, whose label was not used in fitting.
Reuse the data split and standardization from Question 1. In particular, supply the training predictors explicitly when requesting training predictions so that each observation can be its own neighbor.
Training and test ROC curves for each KNN neighborhood size. Each training observation is included among its own neighbors.
The training AUC is at , whereas the test AUC is only . As increases through , test AUC rises to , , , and . The training-test gap shrinks from about at to at .
Training AUC does not decrease at every step: it falls to at , then rises to at and at . Although larger neighborhoods smooth the fitted probabilities, their ranking can improve on both sets. The important pattern here is the overly optimistic training performance for very small , especially .
Increasing reduces the influence of any one training label. It often reduces the optimism of training performance and makes the estimated probabilities less variable. If becomes too large, however, averaging over distant observations can miss local structure. Neither test AUC nor the training-test gap must change monotonically on a particular split.
For 1NN, the estimated probabilities take only the values 0 and 1. Its test ROC curve therefore has one nontrivial point, and its AUC equals . The perfect training AUC is a consequence of reusing each observation’s own label; the test curve evaluates predictions for observations outside the training set.
Question 3: Peer evaluation of Homework 5
No solution is provided for this peer-evaluation question.