Concepts / Train and Test Splitting

Train and Test Splitting

A loop that trains KNeighborsClassifier for each n_neighbors value and records training and test accuracy is a direct way to study how the model behaves.

  • Programming

Why Sweep the Neighbor Count

KNeighborsClassifier predicts a class for a new point by looking at the training points closest to it. One setting controls how many of those neighbors take part in the vote: n_neighbors. A natural question follows immediately: which value should you choose, and what does that choice do to the model? Rather than starting from a rule, this article studies the question by running a loop that trains the classifier many times and records how well it performs each time.

The experiment uses the Breast Cancer dataset. The model is trained once per candidate value, and two numbers are kept for each value: accuracy on the training set and accuracy on a held-out test set. Reading those recorded numbers, and the plot they produce, is the skill this article builds.

Following the Sweep Loop Step by Step

The program first loads the dataset and splits it into a training set and a test set. The stratify argument keeps the proportion of each class similar in both sets, and random_state fixes the split so every run produces the same division of the data. Then the program tries every value of n_neighbors from 1 to 10. The listing below follows the steps described in the source.

python
Notes on the code
  • stratify keeps the class proportions similar in the training and test sets
  • random_state fixes the split so every run gives the same division
  • range(1, 11) supplies the values 1 through 10, one per pass
  • A fresh classifier is created on every pass with the current n_neighbors

Each pass through the loop does four things in order. It creates a new KNeighborsClassifier using the current value of n_neighbors. It fits that classifier on the training data only, which is where the classifier stores the training examples it will later compare new points against. It then computes the training score, and finally the test score. Because the model never saw the test data during fitting, the second score estimates how well the model handles new examples.

One pass of the loop builds a fresh model, trains it, and records two scores before the next value of n_neighbors is tried.

The two lists are filled in the same order the loop runs. The first entry of each list belongs to n_neighbors equal to 1, the second to 2, and so on. This alignment is what lets the plotting lines pair each score with the correct x-axis value. If you change the range, or add a step in the middle of the loop, the lists stay aligned only if every append happens inside the same pass.

What Each Recorded Score Measures

Definition

clf.score returns the fraction of predictions that match the true labels for the data you pass in. It is a number between 0 and 1, and the higher it is, the more often the model was right on that data.

The sweep records two scores for each value of n_neighbors, and they answer two different questions. The training score asks how well the model fits the examples it was built from. The test score asks how well the same model handles examples it never saw. Keeping these two questions separate is what makes the plot informative. A single score cannot reveal whether a model is memorizing its training data or generalizing beyond it.

How the Decision Boundary Changes

When a dataset has exactly two features, the model's behavior can be seen directly. Imagine predicting a class for every possible point in the xy-plane, then coloring each region by the class that would be assigned there. The line where the color changes from one class to the other is the decision boundary. It is the divide between where the algorithm assigns class 0 and where it assigns class 1. The boundary is a property of the trained model, not of the data alone, so changing n_neighbors changes the boundary even when the training points stay exactly the same.

n_neighbors = 1boundary wraps individualpointsn_neighbors = manymore neighbors voteBoundary shapejagged, follows trainingdataBoundary shapesmooth, simpler model
What does the decision boundary look like with n_neighbors equal to 1 versus a large value, and how does it smooth out as the value grows?

With a single neighbor, each test point simply takes the class of its one nearest training point, so the boundary follows the training data closely and wraps around individual points. As more neighbors are included, the vote is spread over more points and the boundary becomes smoother. A smoother boundary corresponds to a simpler model. Put in terms of complexity, few neighbors means high model complexity and many neighbors means low model complexity.

Follow this idea to its extreme. If n_neighbors equals the number of all points in the training set, every test point has exactly the same neighbors, namely all the training points. The vote is then identical for every test point, and every prediction is the class that is most frequent in the training set. The boundary disappears entirely because the model predicts one class everywhere.

Complexity and the Two Failure Patterns

The plot produced by the sweep puts accuracy on the y-axis and n_neighbors on the x-axis, with one line for training accuracy and one for test accuracy. Two failure patterns can be recognized in this single picture. Overfitting occurs when the model is too complex: it fits the training data very well but does worse on new data. Underfitting occurs when the model is too simple: it performs poorly even on the data it was trained on.

High trainingaccuracyfew neighborsLow training accuracymany neighborsLower test accuracylarge gap between the twoLow test accuracypoor on both sets
Which pattern of train-versus-test accuracy signals overfitting, and which signals underfitting, at each end of the n_neighbors range?

Tracing the Plot From Left to Right

Worked example

Reading the sweep at its three landmarks

Given the recorded training and test accuracies for n_neighbors from 1 to 10, what does the pattern at the left edge, the middle, and the right edge tell you?

  1. 1
    Left edge, n_neighbors = 1

    The training prediction is perfect, but test accuracy is lower than at larger neighbor counts. The model is very good on training data and weaker on test data, which is the gap that signals overfitting.

  2. 2
    Middle of the range

    As more neighbors are included, the model becomes simpler and training accuracy drops. Performance peaks between the extremes, which in this experiment was around six neighbors.

  3. 3
    Right edge, n_neighbors = 10

    The model is too simple and performance is even worse on both sets. This pattern of poor accuracy everywhere signals underfitting.

Result

The best choice lies between the extremes, around six neighbors in this experiment, because that is where test accuracy is strongest without the model memorizing the training data.

When you read a plot like this, follow the same order every time: start at the left edge, note the gap between the two lines, move to the right, and watch where the lines separate or both fall. The landmarks of the sweep are the points where you can see a pattern, not single numbers to memorize.

Where a Sweep Goes Wrong

When the output of a sweep does not match what you expect, the sweep's data flow gives you a checklist. The data moves through four stages on each pass: split, fit, score, and record. A wrong picture usually comes from one of these stages, so check them in that order before blaming the model.

  • Common mistake

    Scoring the test data with a model that was fitted on something else

    Why it fails

    The test score only estimates performance on new examples if the model was fitted on the training data alone.

    Do this instead

    Fit with X_train and y_train only, then score on X_test and y_test.

  • Common mistake

    Appending to the lists outside the loop body

    Why it fails

    The lists stay aligned with n_neighbors only if each pair of appends happens inside the same pass.

    Do this instead

    Keep both append calls inside the loop so each score lines up with its n_neighbors value.

  • Common mistake

    Changing the range without checking that the plot's x-axis values still match the list lengths

  • Common mistake

    Reading a plot with the complexity direction assumed to be normal

    Why it fails

    Here n_neighbors increases to the right, so few neighbors, which mean high complexity, sit on the left.

    Do this instead

    Read the x-axis labels first and map left and right to complexity explicitly.

Predicting the Left Edge of the Sweep

What do you think happens?

With n_neighbors equal to 1, what do you expect the training accuracy to be compared with the test accuracy?

Reveal answer
Answer:

The training accuracy is perfect, and the test accuracy is lower.

The source reports a perfect training prediction at one neighbor while test accuracy is lower than at larger neighbor counts. That large gap is the signal of overfitting at the left edge of the plot.

MEDIUM

Using the sweep listing in this article, change the range to 1 through 15 and predict whether the training accuracy at the largest n_neighbors value will drop, and whether the test accuracy will still be lower than the training accuracy at one neighbor. Then run the loop and compare your prediction against the recorded lists.

Hints
  • Recall that more neighbors make the model simpler and lower the training accuracy.
  • Check that the two lists have the same length as the range before reading the plot.

Key Takeaways

  • A loop that fits KNeighborsClassifier for each n_neighbors value and records training and test accuracy shows how the model's behavior changes with complexity.
  • The decision boundary follows the training points closely at one neighbor and becomes smoother as more neighbors vote; a very large value predicts the most frequent training class everywhere.
  • Few neighbors means high model complexity, and many neighbors means low model complexity, so the sweep's x-axis runs from complex on the left to simple on the right.
  • A large gap with high training accuracy and lower test accuracy indicates overfitting, while poor accuracy on both sets indicates underfitting; in this experiment the best region was around six neighbors.
  • When the sweep output looks wrong, check the split, fit, score, and record stages in order, and confirm that the lists stay aligned with the n_neighbors values.

Related concepts

More concepts starting with T