Sub topic 9
Tuning k and Weights with Cross-Validation
This chapter assumes you know how k-NN votes among neighbours, why feature scaling matters, and what distance-weighted voting does. It also assumes you can split data into train and test sets with scikit-learn. Here you will choose k and the voting rule with data instead of guessing, and you will avoid the mistakes that make the chosen values look better than they are.
Why k and weights are hyperparameters
k-NN has no fitted parameters. Training only stores the data, so nothing in fit can tell you whether k=3 or k=15 is better. Settings like these are called hyperparameters. You set them before fitting, and you judge them by how well the resulting model predicts data it has not seen.
Two hyperparameters matter most:
n_neighbors(k): small values give flexible, noisy boundaries (low bias, high variance). Large values give smooth boundaries that can miss local structure (high bias, low variance).weights:"uniform"gives every neighbour one vote."distance"weights each vote by the inverse of its distance, so closer points count more.
Other settings can also be tuned: the distance metric, and p for the Minkowski metric (p=1 is Manhattan, p=2 is Euclidean). Every extra setting multiplies the search cost and the chance of overfitting the search itself.
Why not tune on the test set
Suppose you try twenty values of k and keep the one with the best test score. That score is now optimistic. The test set picked the winner, so it no longer measures performance on new data.
The usual fix has three parts:
- Hold out a test set and do not touch it until the end.
- Split the remaining training data into folds and use them to compare settings.
- Refit the winner on all the training data and score it once on the test set.
How k-fold cross-validation works
In k-fold cross-validation you split the training data into cv equal folds. For each fold, you train on the other folds and score on that fold. You then average the scores. The letter k here is unrelated to the k in k-NN. To avoid confusion, this chapter writes cv for the number of folds.
Cross-validation with cv=5 fits five models per candidate. A grid of 6 values of k and 2 weighting rules gives 12 candidates, so the search fits 60 models. With k-NN, each fit is cheap because it only stores data. Each scoring pass is the expensive part, because every validation point is compared with the stored training points.
The leakage trap: scale inside the folds
Scaling changes distances, so you must scale before k-NN. But if you scale the whole training set first and then cross-validate, each validation fold has already influenced the mean and standard deviation used to scale the training folds. This is data leakage, and it makes scores look slightly better than they should.
A Pipeline solves this. Cross-validation refits every step on each training fold only. The scaler learns its statistics from those rows and then transforms the validation fold.
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
# Safe: the scaler is refit on each training fold
safe = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
print("pipeline :", cross_val_score(safe, X, y, cv=5).mean())
# No scaling at all, for comparison
raw = KNeighborsClassifier(n_neighbors=5)
print("unscaled :", cross_val_score(raw, X, y, cv=5).mean())On the wine data, the unscaled model scores far lower. The proline feature has values in the hundreds or thousands, so it dominates the distance.
Running a grid search
GridSearchCV takes an estimator and a dictionary of candidate values. When the estimator is a pipeline, parameter names use the form stepname__parametername. make_pipeline names each step with the lowercase class name, so the neighbours step is kneighborsclassifier.
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))After fit, GridSearchCV refits the best pipeline on the whole training set (refit=True is the default). Calling grid.score or grid.predict then uses that refit model. The test set enters only at the last line.
For classifiers, an integer cv means stratified folds. Each fold keeps roughly the class proportions of the full training set, which matters when classes are uneven.
Reading the results, not just the winner
best_params_ hides how sensitive the score is to each setting. The cv_results_ dictionary holds the mean and spread for every candidate.
import numpy as np
results = grid.cv_results_
order = np.argsort(results["rank_test_score"])
for i in order[:5]:
print(
results["params"][i],
round(results["mean_test_score"][i], 3),
"+/-",
round(results["std_test_score"][i], 3),
)Look at two things:
- The plateau. If
k=5,7and9score within a fraction of a percentage point, the choice among them is noise. Pick by a secondary rule, such as the largestk(smoother boundary) or the cheapest to run. - The standard deviation. With five folds and a small dataset, the spread across folds is often larger than the gap between the top candidates. The "one standard error" rule picks the simplest setting whose mean score is within one standard error of the best. For k-NN, "simplest" usually means a larger
k.
Choosing the grid
Practical guidance for the search space:
- Range of k. Start with odd values up to about the square root of the training size, then widen if the best value sits at the edge of the grid. A best value at the edge means the true optimum may lie outside your range.
- Odd k for two classes. An odd
kavoids tied votes in binary problems. With more classes, ties are still possible. - Upper limit. In each split, the training fold holds only
(cv-1)/cvof your training data. Ifkexceeds that count, scikit-learn raises an error. - Spacing. Neighbouring values such as
k=10andk=11rarely differ much. Coarse steps (1, 3, 5, 9, 15, 25) then a finer pass around the winner cost less. - Weights. Distance weighting helps most with larger
k, where far neighbours would otherwise outvote close ones. Withk=1the two rules are identical, so that combination is searched twice for nothing. - Metric. Add
"kneighborsclassifier__p": [1, 2]to compare Manhattan and Euclidean distance, but only if you have a reason. Each added axis multiplies the number of fits.
Choosing the scoring metric
The default metric for classifiers is accuracy. That is a poor guide when one class is rare, because a model can score well by favouring the majority class. Set scoring to match what you care about, for example "balanced_accuracy", "f1_macro" or "roc_auc_ovr". For KNeighborsRegressor, the default is R², and you can use "neg_mean_absolute_error" or "neg_root_mean_squared_error". Scikit-learn negates error metrics so that higher is always better.
Estimating performance honestly: nested cross-validation
The best score in grid.best_score_ is still biased upward, because you chose it as the maximum over many noisy estimates. A single held-out test set avoids this but gives a noisy estimate if it is small. Nested cross-validation reduces that noise. An outer loop holds out each fold in turn, and an inner grid search runs on the remaining data.
from sklearn.datasets import load_wine
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
pipe = make_pipeline(StandardScaler(), KNeighborsClassifier())
param_grid = {
"kneighborsclassifier__n_neighbors": [1, 3, 5, 7, 9, 11],
"kneighborsclassifier__weights": ["uniform", "distance"],
}
inner = GridSearchCV(pipe, param_grid, cv=5)
outer_scores = cross_val_score(inner, X, y, cv=5)
print(outer_scores.mean(), outer_scores.std())This runs the whole search once per outer fold, so it costs outer × inner × candidates fits. The result estimates how well the whole procedure (scaling, search, and refit) generalises. It does not give you a single final model. To get one, run the grid search once on all your data.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Cross-validation score much higher than test score | Scaling or feature selection done before splitting | Move every learned step into the pipeline |
| `ValueError` about `n_neighbors` larger than samples | `k` larger than a training fold | Lower the largest `k` or use fewer folds |
| Best `k` is the largest value in the grid | Grid too narrow | Extend the grid and search again |
| Best `k` is 1 | Possible duplicates or near-duplicates across folds, or very clean classes | Check for repeated rows, and compare with `k=3` and `k=5` |
| `KeyError` in `param_grid` or an invalid parameter error | Wrong step name in the pipeline | Print `pipe.get_params().keys()` to see valid names |
| Unstable best parameters between runs | Small dataset, noisy folds | Use repeated CV (`RepeatedStratifiedKFold`) or the one-standard-error rule |
If your data has a natural grouping (several rows from the same patient, say), plain folds put near-copies of a row in both training and validation parts. Use GroupKFold and pass groups to fit. For time series, use TimeSeriesSplit so the validation fold always comes after the training folds.
Key points
- k and the voting rule are chosen by measuring held-out performance, never by training accuracy.
- Put the scaler and the classifier in one
Pipelineso each fold scales using only its training rows. GridSearchCVrefits the winner on the full training set. Score the test set once.- Inspect
cv_results_for plateaus and spread before trusting the top-ranked candidate. - Choose a
scoringmetric that fits the problem, especially under class imbalance. - Use nested cross-validation when you need an unbiased estimate of the entire tuning procedure.
Exercise
You scale all of X_train with StandardScaler, then call GridSearchCV on a plain KNeighborsClassifier using the scaled data. A colleague says the scores are slightly optimistic. Why, and what is the fix?
Show answer
The scaler's mean and standard deviation were computed from all training rows, including rows that later serve as validation folds. Validation information leaked into preprocessing. Fix it by building makepipeline(StandardScaler(), KNeighborsClassifier()) and passing that pipeline to GridSearchCV, with parameter names such as "kneighborsclassifiernneighbors", so the scaler is refit on each fold's training rows only.
Exercise
A grid search with 8 values of n_neighbors, 2 weighting rules and cv=5 is run inside an outer 4-fold cross-validation. How many k-NN models are fitted for the search itself, not counting the refits of the winners?
Show answer
The grid has 8 × 2 = 16 candidates. Each inner search fits 16 × 5 = 80 models. The outer loop runs 4 inner searches, so 4 × 80 = 320 fits. If you also count the refit of the best model after each inner search, add 4 more.