Sub topic 5
Choosing k: bias versus variance
The earlier chapters covered how k-NN measures distance and how it votes. This chapter covers the one setting you must always choose yourself, the number of neighbours k. You will see why small and large values of k fail in different ways, how to spot each failure in numbers, and what rules of thumb are worth trusting.
This chapter assumes you know what training error and validation error are, and that you have run KNeighborsClassifier before. Formal cross-validation tuning comes in a later chapter. Here a single validation split is enough to show the effect.
What k controls
k-NN has no fitted parameters. Its flexibility comes from k, which is a hyperparameter, a setting you choose before the model sees any data.
- Small k makes each prediction depend on very few points. The model follows the training data closely, including its noise.
- Large k averages over many points. The model becomes smooth, but it can wash out real structure.
These two failures are the two sides of the bias-variance trade-off.
- Bias is the error from a model being too simple to capture the true pattern. Even with unlimited data from the same source, a high-bias model stays wrong in a systematic way.
- Variance is the error from a model being too sensitive to the particular training sample. A high-variance model would change a lot if you trained it on a different sample of the same size.
Why small k has high variance
Take k = 1. The prediction for a query is the label of its single closest training point. If that point is mislabelled or sits in an unusual spot, the prediction is wrong, and nothing else in the data can correct it.
For regression the effect can be written down. Suppose each target is the true value plus independent noise with variance σ². The k-NN prediction is the average of k noisy targets. The noise part of that average has variance σ²/k. Doubling k halves the noise contribution. At k = 1 you inherit the full σ².
For classification there is no clean formula, but the same logic applies. The vote of one neighbour is a noisy estimate of the local class probabilities. The vote of 25 neighbours is a much steadier estimate.
The training set also fits itself perfectly at k = 1. Each training point is its own nearest neighbour at distance 0, so training accuracy is 1.0 (assuming no duplicate points with conflicting labels). A perfect training score here says nothing about quality.
Why large k has high bias
As k grows, the neighbourhood grows. The points in it come from farther and farther away, so they stop describing the area around the query. The prediction reflects the region instead of the location.
The extreme case is k equal to the number of training points. Every query gets the same answer, the overall majority class (or the overall mean for regression). The model ignores the features entirely. That is maximum bias and zero variance.
Bias also grows when classes are small. If a minority class has 20 examples and k is 51, a query deep inside that class can still be outvoted by points from other classes, because the neighbourhood must reach beyond the class to find 51 points.
The trade-off at a glance
| Property | Small k (for example 1) | Large k (close to n) |
|---|---|---|
| Decision boundary | Jagged, with small islands around noisy points | Smooth, eventually one region |
| Bias | Low | High |
| Variance | High | Low |
| Training error | Near zero | Approaches the majority-class error |
| Typical failure | Overfitting | Underfitting |
| Sensitivity to label noise | High | Low |
Seeing it in numbers
The script below uses a noisy two-class dataset. It trains a model for several values of k and prints accuracy on the training data and on held-out data.
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = make_moons(n_samples=400, noise=0.35, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
print(f"{'k':>4} {'train acc':>10} {'val acc':>8}")
for k in [1, 3, 5, 9, 15, 25, 51, 101, 280]:
model = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
train_acc = model.score(X_train, y_train)
val_acc = model.score(X_val, y_val)
print(f"{k:>4} {train_acc:>10.3f} {val_acc:>8.3f}")Run it and look for three things:
- At k = 1 the training accuracy is 1.000, while the validation accuracy is clearly lower. The gap between the two is the signature of high variance.
- At moderate k, training accuracy drops and validation accuracy rises. The two scores move closer together.
- At k = 280, which equals the size of the training set, every query gets the same prediction. The training set is split evenly between the two classes, so both accuracies fall to about 0.5.
The exact numbers depend on the random seed, but the shape does not. Validation accuracy rises, peaks and falls, and the best k sits in between.
The U-shaped curve of validation error against k is a validation curve. You read the best k from its minimum.
Rules of thumb and their limits
You will see several shortcuts. They are starting points, not answers.
- k ≈ √n. With 280 training points this suggests about 17. It often lands in a reasonable region, but it ignores noise level, dimensionality and class overlap. Treat it as the centre of a search range.
- Use odd k for two classes. An odd k cannot produce a tied vote between two classes. With three or more classes, odd k does not prevent ties, so the rule helps only in the binary case. Tie handling is covered in the pitfalls chapter.
- Small k when classes are clean and well separated, larger k when labels are noisy. This follows from the variance argument above and is a good guide to which end of the range to search first.
For a theoretical anchor, consider what happens as the amount of data grows without limit. The 1-NN classifier's error approaches at most twice the best possible error, called the Bayes error. If k also grows, but more slowly than n, k-NN's error approaches the Bayes error itself. In practice you never have unlimited data, so the finite-sample trade-off above is what you deal with.
Variance you can measure
Variance is about how much the model changes between training samples. You can see this directly. The script below trains k-NN on many bootstrap resamples of the training set and records how often the prediction for one fixed query point changes.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.neighbors import KNeighborsClassifier
X, y = make_moons(n_samples=400, noise=0.35, random_state=0)
query = np.array([[0.5, 0.25]])
rng = np.random.default_rng(0)
for k in [1, 5, 25, 101]:
votes = []
for _ in range(200):
idx = rng.choice(len(X), size=len(X), replace=True)
model = KNeighborsClassifier(n_neighbors=k).fit(X[idx], y[idx])
votes.append(model.predict(query)[0])
share_of_class_1 = np.mean(votes)
print(f"k={k:>3} share of resamples predicting class 1: {share_of_class_1:.2f}")Where the query sits near a class border, a high-variance model flips between classes depending on the resample, so its share is far from 0 or 1. As k grows, the share settles toward one answer. Note that a stable answer is not always a correct one. A large k can be confidently wrong, which is bias at work.
Errors to avoid when choosing k
- Choosing k by training accuracy. Training accuracy always favours k = 1, so it picks the most overfit model. Score on data the model was not fitted on.
- Choosing k on the final test set. If you try many values of k and keep the one with the best test score, the test score is no longer an honest estimate. Keep the test set for one final evaluation, and choose k on a validation split or with cross-validation.
- Scoring on the training data with
cross_val_scoremistakes or manual loops. When you score a point against a model that already contains it, the point is its own nearest neighbour. This inflates results most at small k. Every validation point must be absent from the training set. - Ignoring scaling. The best k depends on the distance, and the distance depends on feature scale. A k tuned on unscaled features can be quite different from the k tuned on scaled ones. Fix the preprocessing first, then tune k.
- Searching a range that is too narrow. If the best value lands at the edge of your range, extend the range.
A practical procedure
- Fix the preprocessing, including scaling and any feature selection.
- Choose a range of k, for example odd values from 1 up to about 2√n.
- Score each k on held-out data. A single split is fine for exploration. The next chapters use repeated splits for stability.
- Plot or print training and validation scores side by side. A large gap means overfitting. Two low, close scores mean underfitting.
- Pick the k with the best validation score. If several values are close, prefer the larger one. It gives a smoother model that is cheaper to defend, although prediction takes slightly longer.
- Report the final score on the untouched test set.
Exercise
A k-NN classifier trained on 1,000 points scores 1.00 on the training set and 0.78 on a validation set. A colleague suggests raising k from 1 to 15. Explain what you expect to happen to training accuracy and validation accuracy, and why. Then say what you would conclude if validation accuracy fell as k kept rising from 15 to 500.
Show answer
At k = 1 the model is overfitting: each training point is its own nearest neighbour, so training accuracy is 1.00, but predictions depend on single noisy points, so variance is high. Raising k to 15 averages over more points. Training accuracy should fall below 1.00, because a point can now be outvoted by its neighbours. Validation accuracy should rise, because the predictions are less sensitive to individual noisy points. The gap between the two scores should shrink. If validation accuracy then falls steadily from 15 to 500, the neighbourhoods have become too large to describe local structure. That is rising bias, meaning underfitting, and the best k lies near or below 15. You would choose k near the peak of the validation curve, then confirm it once on a separate test set.
Exercise
You are classifying into two classes and your tuning range contains only even values of k. What problem can this cause, and what is the simple fix?
Show answer
With an even k, the votes can split evenly between the two classes, which produces a tie that must be broken by some arbitrary rule. The simple fix is to use odd values of k. This guarantee holds only for two classes. With three or more classes, ties can still happen at any k.