Sub topic 9
Tuning k and weights with cross-validation
This chapter assumes you know how k-NN votes, why k trades bias against variance, and why features need scaling. It shows how to pick k and the voting rule from data without touching the test set.
Why a single split is not enough
You could try several values of k and keep the one with the best test score. That makes the test set part of model selection, so its score becomes an optimistic estimate of real performance.
Cross-validation fixes this. You split the training data into folds. Each fold takes a turn as the validation set while the model trains on the others. The average validation score ranks each candidate setting. The test set stays untouched until the end.
What to tune
Two hyperparameters matter most for k-NN:
n_neighbors: the value of k. Small values give low bias and high variance. Large values give the reverse.weights:"uniform"gives each neighbour one vote."distance"weights each vote by the inverse of its distance.
You can also tune p (the Minkowski power, where 1 is Manhattan and 2 is Euclidean), but start with these two.
Scaling must happen inside each fold
If you scale the whole training set before cross-validation, each validation fold has influenced the mean and standard deviation used to scale it. That is data leakage. The fix is a pipeline, which refits the scaler on the training part of every fold.
from sklearn.datasets import load_wine
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
pipe = make_pipeline(StandardScaler(), KNeighborsClassifier())
param_grid = {
"kneighborsclassifier__n_neighbors": [1, 3, 5, 7, 9, 11],
"kneighborsclassifier__weights": ["uniform", "distance"],
}
grid = GridSearchCV(pipe, param_grid, cv=5)
grid.fit(X_train, y_train)
print(grid.best_params_)
print(grid.score(X_test, y_test))Read the code in three parts:
make_pipelinenames each step after its lowercase class name. The scaler isstandardscalerand the classifier iskneighborsclassifier.- Parameter names use the form
stepname__parameter, with two underscores. This is how the grid reaches inside the pipeline. GridSearchCVtries all 6 × 2 = 12 combinations. Withcv=5that means 60 model fits. After the search it refits the best combination on the full training set.
grid.score(X_test, y_test) is the first time the test set is used. It gives your final performance estimate.
Reading the results
best_params_ gives the winner. The cv_results_ attribute holds the mean and standard deviation of the score for every combination. Look at it before trusting the winner.
import pandas as pd
results = pd.DataFrame(grid.cv_results_)
cols = [
"param_kneighborsclassifier__n_neighbors",
"param_kneighborsclassifier__weights",
"mean_test_score",
"std_test_score",
]
print(results[cols].sort_values("mean_test_score", ascending=False).head())If several settings score within one standard deviation of each other, the data cannot tell them apart. In that case, prefer the simpler or cheaper choice. For k-NN, a larger k gives a smoother boundary, and a smaller one is slightly faster to predict.
Common errors
- Scaling before splitting. Fitting
StandardScaleron all the data leaks validation information. Put it in the pipeline. - Wrong parameter names.
n_neighborsalone raises an error inside a pipeline. Use thekneighborsclassifier__n_neighborsform. - Reporting the best CV score as final performance. The best of many cross-validation scores is optimistically biased. Report the held-out test score.
- Unstratified folds on imbalanced data. For classifiers,
cv=5stratifies by default, but a custom splitter may not. Check it. - A grid that hits its edge. If the best
kis the largest value in your list, extend the list.
Exercise
A grid has n_neighbors in [1, 3, 5, 7], weights in ["uniform", "distance"], and you use cv=10. How many model fits does GridSearchCV perform during the search, not counting the final refit? Why is the scaler placed in a pipeline rather than applied beforehand?
Show answer
There are 4 × 2 = 8 combinations, and each is fit 10 times, so 80 fits. The scaler is in the pipeline so it is refit on the training part of each fold only. Scaling beforehand would let the validation folds influence the scaling statistics, which leaks information and inflates the scores.
Exercise
Your grid search picks n_neighbors=11, the largest value you offered, and the scores for 9 and 11 differ by less than their standard deviations. What should you do?
Show answer
Extend the grid with larger values such as 13, 15 and 21, since the best value may lie beyond the edge. If the scores stay within noise of each other, choose the simpler option, or the one that is cheaper to run.