Sub topic 4
How k shapes the decision boundary
This chapter assumes you know how k-NN classifies by majority vote, can compute Euclidean distance, and can read basic scikit-learn code. Choosing k by cross-validation comes in a later chapter. Here the goal is to see what k does to the geometry of the predictions.
What a decision boundary is
A decision boundary is the set of points where the predicted class changes. A classifier labels every point in feature space. The boundary is the border between regions that receive different labels.
Most models store the boundary in their parameters. A logistic regression stores a line as a weight vector. k-NN stores no boundary at all. It stores the training points, and the boundary appears only when you ask for predictions everywhere. Changing k changes the rule that turns those stored points into regions, so the boundary changes with it.
k = 1: the Voronoi picture
With k = 1, each query gets the label of its single closest training point. Around every training point there is a cell: the set of locations closer to that point than to any other. These cells form a Voronoi diagram. The decision boundary is made of the cell edges that separate points with different labels.
Each cell edge lies on the perpendicular bisector of two training points. So the boundary is piecewise linear, built from straight segments, and it hugs the data closely.
Three consequences follow:
- Every training point is classified correctly. A point's own cell contains it, so training accuracy is 1.0. The exception is duplicate points that carry different labels.
- Noise gets its own territory. A single mislabelled point inside a cluster of the other class creates a small island of the wrong label. Any query landing in that island is misclassified.
- The boundary is jagged. Moving one training point slightly can move a boundary segment, so predictions have high variance.
Increasing k: smoothing by averaging
With k > 1 the label depends on a vote among several points. A lone noisy point is outvoted by its neighbours, so its island shrinks and eventually disappears. The boundary still consists of straight segments, but they are far fewer and follow the broad shape of the classes instead of every individual point.
The effect on a vote can be stated simply. For a query to be classified as class A, A must hold the majority among the k closest points. A small cluster of fewer than about k/2 points cannot win any region by itself. Larger k therefore erases structures smaller than the neighbourhood it uses.
k = n: the opposite extreme
If k equals the number of training points, every query sees the entire training set as its neighbourhood. With uniform voting, the result is the majority class for every query. The boundary vanishes, and the model is a constant predictor.
Between the two extremes the model moves from low bias and high variance (k = 1) toward high bias and low variance (large k). This chapter looks at that trade-off through the boundary's shape. The next chapter treats it as a selection problem.
Seeing the effect in numbers
You can study boundaries without plotting. The first script trains k-NN on a noisy two-class dataset and reports 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=200, noise=0.35, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
print(f"n_train = {len(X_train)}")
for k in [1, 5, 15, 51, 150]:
model = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
print(
f"k={k:>3} train={model.score(X_train, y_train):.2f} "
f"test={model.score(X_test, y_test):.2f}"
)The exact values depend on the sample, but the pattern is reliable:
- At k = 1 the training score is 1.00 while the test score is clearly lower. That gap is the signature of overfitting.
- At moderate k the training score drops and the test score usually rises or holds. The model has stopped memorising noise.
- At k = 150, which equals the training set size here, both scores fall to roughly the share of the majority class. The stratified split keeps the classes balanced, so expect about 0.50.
The training score at k = 1 is 1.00 for a specific reason. When you call score on the training data, each point is its own nearest neighbour at distance 0. Training accuracy is therefore a poor guide for choosing k. Always compare on held-out data.
Measuring how rough the boundary is
A second experiment measures roughness directly. It walks along a horizontal line through the feature space, predicts a label at 400 evenly spaced positions, and counts how often the label changes between neighbouring positions. Fewer changes mean a smoother boundary along that line.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.neighbors import KNeighborsClassifier
X, y = make_moons(n_samples=200, noise=0.35, random_state=0)
xs = np.linspace(-1.5, 2.5, 400)
line = np.column_stack([xs, np.full_like(xs, 0.25)])
for k in [1, 5, 15, 51, 199]:
model = KNeighborsClassifier(n_neighbors=k).fit(X, y)
labels = model.predict(line)
flips = int(np.sum(np.diff(labels) != 0))
print(f"k={k:>3} label changes along the line: {flips}")Here the model trains on all 200 points, so k = 199 is the largest value that still leaves a distinct set of neighbours. For k = 1 you should see many changes, because the line crosses many small Voronoi cells. The count falls as k grows. The count depends on where the line sits, so treat it as a comparison between values of k and not as a measurement of the data.
Odd k, even k, and ties
In a two-class problem, an even k can produce a tie. With k = 4, a 2-to-2 split has no majority. Choosing an odd k removes ties for two classes.
Odd k does not guarantee a winner with three or more classes. With k = 5 and three classes, a 2-2-1 split is a tie between two classes. Scikit-learn breaks ties deterministically, in favour of the class that comes first in the sorted order of labels. This is consistent and reproducible, but arbitrary. It can also hide a problem: if many queries are tied, your k may be too small for the number of classes.
Ties also occur at the distance level. If several training points sit at exactly the same distance as the k-th neighbour, the choice among them depends on the order of the data. This is rare with continuous features but common with integer or binary features.
Boundaries depend on the distance, too
Everything above assumes a fixed distance. The geometry of a neighbourhood comes from the metric:
- With Euclidean distance, neighbourhoods are round.
- With Manhattan distance, they are diamond-shaped.
- With unscaled features, they are stretched along any feature with a large numeric range, so the boundary mostly reflects that one feature.
So two models with the same k can have very different boundaries if their metrics or scaling differ. Scaling gets its own chapter, but keep it in mind when you interpret any boundary picture.
Edge cases to watch for
- Class imbalance. With a large k and a rare class, the rare class loses almost every vote and its region shrinks or vanishes, even if its points form a tight cluster. A k larger than the size of the smallest class is a warning sign.
- Isolated points. Far from all training data, a query still gets k neighbours, and they are all far away. The label is still produced, with no signal about low confidence. Boundaries in empty regions of feature space are artefacts of the vote and not evidence.
- k larger than the data. Scikit-learn raises an error if
n_neighborsexceeds the number of training samples. Inside cross-validation, remember that each fold's training set is smaller than your full training set. - Weighted voting. With
weights="distance"and k = n, the result is no longer constant, because closer points count more. Distance weighting makes the boundary hug nearby points more closely at any k, and it is covered in a later chapter.
Summary
- k = 1 gives Voronoi cells: a piecewise-linear boundary that fits every training point, including noise.
- Growing k removes small islands, reduces the number of boundary segments, and smooths the shape, at the cost of ignoring fine structure.
- k = n predicts the majority class everywhere under uniform voting.
- Training accuracy at k = 1 is trivially perfect, so evaluate on held-out data.
- Ties, class imbalance and the choice of metric all change what a given k does.
Exercise
You train a k-NN classifier on 120 samples with two balanced classes. At k = 1 the training accuracy is 1.00 and the test accuracy is 0.78. At k = 120 the training and test accuracies are both about 0.50. Explain both results in terms of the decision boundary, and say what you would try next.
Show answer
At k = 1 each training point is its own nearest neighbour, so training accuracy is perfect. The boundary follows Voronoi cell edges and includes islands around noisy points, so it generalises poorly (0.78 on test data). At k = 120 every query sees the whole training set and receives the majority class, which in a balanced problem gives about 50% accuracy: the boundary has disappeared. The useful values lie between these extremes. Try odd values such as 3, 5, 9 and 15, and compare them on held-out data or with cross-validation, then pick the k with the best validation score.
Exercise
Why can an even k cause trouble in a binary problem, and why does an odd k not fully solve ties in a problem with three classes?
Show answer
With two classes and even k, the neighbours can split evenly (for example 2 to 2), so there is no majority. An odd k always gives one class more votes. With three classes, the votes can split among classes in a way that leaves two classes tied for first even when k is odd (for example 2, 2 and 1 with k = 5). Scikit-learn then resolves the tie by label order, which is deterministic but arbitrary.