Sub topic 4
How k shapes the decision boundary
This chapter assumes you can run scikit-learn code and know how k-NN classifies by majority vote. It also assumes you know what a training and a test set are. Here you will see how the value of k changes the shape of the boundary between classes.
What a decision boundary is
A decision boundary is the set of points where the predicted class changes. If you label every point in the plane with the prediction k-NN would give, the boundary is where neighbouring labels differ.
k-NN has no fitted equation, so its boundary is implied by the stored training points and by k. The boundary is built from pieces of the perpendicular bisectors between points of different classes. It can be curved or fragmented, and it can enclose isolated islands.
k = 1: a boundary that follows every point
With k = 1, each query takes the label of its single closest training point. Every training point owns the region of space nearer to it than to any other point. The class boundary is the edge between regions owned by points of different classes.
Consequences:
- The boundary is jagged and follows individual points.
- A mislabelled or noisy point creates a small island of the wrong class around itself.
- Training accuracy is 1.0 whenever no two identical points have different labels. Each training point is its own nearest neighbour.
Larger k: smoother boundaries
With larger k, a prediction depends on a neighbourhood. One stray point is outvoted, so islands around noisy points disappear. The boundary becomes smoother and simpler.
If k grows too large, the neighbourhood spans several clusters. Real structure gets smoothed away. In the extreme case, k equals the number of training points. Every query then sees the same set of neighbours, so every prediction is the majority class.
Seeing it in code
This example trains k-NN on a noisy two-class dataset. It compares training and test accuracy for several values of k.
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=300, noise=0.35, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
for k in [1, 5, 25, 101]:
model = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
train_acc = model.score(X_train, y_train)
test_acc = model.score(X_test, y_test)
print(f"k={k:>3} train={train_acc:.2f} test={test_acc:.2f}")You should see training accuracy of exactly 1.00 at k = 1. It should fall as k grows. Test accuracy usually does not follow that pattern. It tends to be lower at k = 1 than at a moderate k, then drops again at very large k. Exact numbers depend on your scikit-learn version, so focus on the trend.
To draw the boundary itself, scikit-learn provides sklearn.inspection.DecisionBoundaryDisplay.from_estimator. It evaluates the fitted model on a grid of points and colours each cell by its predicted class. Plot it for k = 1 and k = 25 side by side to compare them.
Summary of the effect
| Row | Small k | Large k |
|---|---|---|
| Boundary | Jagged, follows single points | Smooth, follows broad trends |
| Reaction to one noisy point | Creates a wrong-class island | Usually outvoted |
| Training accuracy | High, 1.0 at k = 1 | Lower |
| Typical failure | Overfitting | Underfitting |
Common errors
- Judging k from training accuracy. It always favours k = 1, so use held-out data.
- Using an even k in a two-class problem. Votes can tie, and the winner is then decided by an arbitrary rule.
- Reading the boundary plot without checking scaling. If features have very different ranges, the boundary is distorted along the large-range axis. Later chapters cover this.
The next chapter turns this visual intuition into the bias and variance trade-off, and shows how to choose k systematically.
Exercise
You set k equal to the number of training points and use uniform voting. What does the classifier predict for a new point, and why?
Show answer
It predicts the majority class of the training set for every query. All training points are always the neighbours, so the vote is identical for every input and the boundary disappears.
Exercise
Why is training accuracy at k = 1 usually 1.0, and why does that not show the model is good?
Show answer
Each training point is its own nearest neighbour at distance zero, so it always receives its own label. This only shows the model memorised the training data. Test accuracy on unseen points measures generalisation.