Sub topic 5
Choosing k: bias versus variance
This chapter assumes you know how k-NN classifies by majority vote, what a decision boundary is, and how to split data into training and validation sets. It uses scikit-learn and NumPy.
What k controls
k-NN has no fitted parameters. Its main setting is k, the number of neighbours that vote. That one number sets how flexible the model is.
- Small k makes predictions from a few very close points. The boundary follows the training data closely, including its noise.
- Large k averages over many points. The boundary becomes smooth, and local structure can get washed out.
Bias and variance in k-NN
Bias is the error from a model being too simple to match the real pattern. Variance is how much the model changes if you train it on a different sample of the same data.
| k | Boundary | Bias | Variance | Typical failure |
|---|---|---|---|---|
| 1 | Jagged, hugs every point | Low | High | Overfitting: one mislabelled point creates its own region |
| Moderate | Smooth but still local | Medium | Medium | Usually the best trade-off |
| Close to n | Nearly flat | High | Low | Underfitting: predicts the majority class everywhere |
At k = 1, training accuracy is 1.0 on data without duplicate points, because each point is its own nearest neighbour. That number says nothing about generalisation. At k = n (the training set size), every query gets the same answer, the overall majority class.
Measuring the effect
Choose k by comparing training scores with cross-validated scores across a range of values. The code below uses validation_curve with a scaling pipeline, so scaling is fitted inside each fold.
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import validation_curve
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())
ks = [1, 3, 5, 9, 15, 25, 51, 101]
train_scores, val_scores = validation_curve(
pipe, X, y,
param_name="kneighborsclassifier__n_neighbors",
param_range=ks,
cv=5,
)
print("k train validation")
for k, tr, va in zip(ks, train_scores.mean(axis=1), val_scores.mean(axis=1)):
print(f"{k:<4} {tr:.3f} {va:.3f}")
best_k = ks[int(np.argmax(val_scores.mean(axis=1)))]
print("best k:", best_k)Read the output as follows:
- At k = 1, the training score is near 1.0 and the validation score is lower. The gap between them signals high variance.
- As k grows, the training score falls toward the validation score. The two scores meet.
- At very large k, both scores drop together. This is high bias, and the gap no longer tells you much.
Pick the k where the validation score peaks, not where training score peaks.
Practical rules
- Use odd k for binary problems. An odd k avoids tied votes between two classes. With more than two classes, ties can still happen, so see the chapter on practical pitfalls.
- Search a sensible range. Start with small odd values and widen the search. A common upper bound is around the square root of the training size, but treat that as a starting point and not a rule.
- Prefer the simpler model when scores are close. If several values of k score within the noise of each other, a larger k gives a smoother and usually more stable model.
- Tune k after scaling. The best k depends on the distance, and the distance depends on feature scales.
- Keep a final test set. Choosing k on validation scores makes them slightly optimistic. Report accuracy on data that played no part in the choice.
Common errors
- Reading
best_kfrom a single train/validation split. One split is noisy, so use cross-validation. - Fitting the scaler on all the data before cross-validation. Information from the validation folds then leaks into the scaling.
- Treating the best k as universal. It depends on the dataset size, the noise and the number of features. Retune it when any of these change.
Exercise
A k-NN classifier gets 100% training accuracy and 71% validation accuracy at k = 1. At k = 101 it gets 64% on both. Which end shows high variance, which shows high bias, and what would you try next?
Show answer
k = 1 shows high variance (overfitting): a large gap between training and validation scores. k = 101 shows high bias (underfitting): both scores are low and equal. Try intermediate values such as 5 to 25 with cross-validation and choose the k with the best validation score, preferring the larger k if scores are close.