Concepts / Understanding overfitting in classification models

Understanding overfitting in classification models

Model evaluation is the set of steps that turns a trained model into a measured claim.

  • Programming

Why Training Accuracy Is Not Enough

Training a classification model produces a set of learned behavior. That behavior, however, does not tell you by itself whether the model is any good. A model can look reasonable on the very examples it was built from and still fail on examples it has never seen. This gap is the heart of overfitting, and it is the reason model evaluation exists.

Model evaluation is the set of steps that turns a trained model into a measured claim. It answers two questions: how often is the model right, and on what data was that measurement taken? The second question matters as much as the first. A measured accuracy computed on the examples the model learned from is not the same kind of evidence as one computed on examples it never saw.

This article follows one classifier, the k-nearest neighbors classifier, through the full path: how it predicts, how it is built and measured in Python, and what its accuracy number can and cannot tell you about the future.

Predicting from the Closest Neighbors

The k-nearest neighbors classification algorithm has a local core idea. To predict the class of a new data point, it looks at the training points that lie closest to that new point and lets those neighbors inform the answer. Nothing global is computed, no equation is fitted to the whole dataset, and no rule is written down in advance.

The number of neighbors considered is controlled by a parameter, usually written as $k$. With $k=1$, the prediction is driven entirely by the single closest training point. With larger values of $k$, several nearby points contribute, and the predicted class reflects the neighbors together.

1.0class A1.0 and 2.0nearest class A votes2.0class A3.0new point, class unknown8.0class B9.0class Bdistance 1distance 2distance 5
Which training points are nearest to the new measurement, and how do their labels decide the predicted class? With k equal to 3, the three nearest training points are highlighted; two belong to class A and one to class B, so the prediction is class A.

The diagram shows a one-dimensional case for clarity. The new point 3.0 has three nearest training points: 2.0 at distance 1, 1.0 at distance 2, and 8.0 at distance 5. The classes of those three neighbors decide the outcome. The source describes the general principle; the specific numbers here are an illustrative choice made for this article.

Train, Test, and Apply Pipeline

In Python, the algorithm is provided by a class named KNeighborsClassifier. A single class of this kind holds two responsibilities: the procedure that builds the model from training data, and the procedure that uses the built model to make a prediction. You work with the class in three stages. You first instantiate the class and set its parameters, then build the model by calling its fit method, and finally evaluate it by calling its score method.

Taken together, these steps form a short pipeline. The model is configured, built from training data, measured on test data, and then, if the measurement is satisfactory, put to use. The order matters. The test data must stay separate from the training data throughout, so that the measurement is an honest check rather than a rereading of material the model already studied.

Configure classifierKNeighborsClassifierfit on training pairX_train and y_trainscore on test pairX_test and y_testaccuracy acceptable?apply to newmeasurementsunseen datayes
Which data goes into fit(), which goes into score(), and why must the two sets stay separate? The training pair builds the model, the held-out test pair measures it, and only an acceptable measurement leads to applying the model to new data.

What fit Actually Stores

Building the model means creating the object and then passing it two things: the training inputs, conventionally named X_train, and the training outputs, conventionally named y_train. The inputs describe each training example, and the outputs give the known class for each of those examples.

Notice that fit does not return a prediction. Its job is to build the model from the training pair. Evaluation and application are separate steps that come afterward. The nearest-neighbor model has no compact formula to memorize in advance; the stored training data is what the algorithm consults. That is why the training data must be supplied when the model is built, and why the same stored examples are needed whenever a prediction is made.

Programcalls the methodsKNeighborsClassifierbuilt modelStored training dataX_train and y_trainfit(X_train, y_train)keeps the examplesscore(X_test, y_test)accuracy
What actually happens inside the model during fit(), and when does the neighbor lookup occur? fit() stores the training inputs and outputs and returns no prediction; the lookup against those stored examples happens when predictions are requested, as score() does during evaluation.

Building and Scoring a Classifier in Python

The code below follows the pattern described above. The data is split into a training portion and a held-out test portion, the classifier is created and fitted on the training portion, and then score is called on the test portion. The value 3 for the number of neighbors is an illustrative choice made for this example, not a value taken from the source. The variables X and y stand for your input measurements and their known class labels.

python
Notes on the code
  • train_test_split keeps the test examples out of the training pair
  • KNeighborsClassifier is instantiated and its parameter is set before fitting
  • fit receives the training inputs and training outputs and returns no prediction
  • score receives held-out inputs and their correct labels and returns the accuracy

Tracing a Prediction by Hand

Worked example

Predicting one new point with k equal to 3

Training points are 1.0 (class A), 2.0 (class A), 8.0 (class B), and 9.0 (class B). Predict the class of the new point 3.0 using k equal to 3.

  1. 1
    Measure distances

    Distance from 3.0 to 1.0 is 2, to 2.0 is 1, to 8.0 is 5, and to 9.0 is 6.

  2. 2
    Select the nearest k

    The three closest training points are 2.0 (distance 1), 1.0 (distance 2), and 8.0 (distance 5). The point 9.0 is excluded.

  3. 3
    Count the neighbor classes

    Two of the three neighbors are class A and one is class B.

  4. 4
    Decide the prediction

    The majority among the neighbors is class A, so the predicted class for 3.0 is A.

Result

The new point 3.0 is predicted to be class A. The prediction came from the stored training points, not from a fitted formula.

Reading the Accuracy from score

The score method computes the accuracy of the model. Accuracy is the proportion of predictions that match the true labels. Written as a ratio, it is the count of correct predictions divided by the total number of test examples.

Rule

To measure accuracy honestly, you give score a set of data the model did not learn from, along with the correct labels for that data. This is the test set. A model is always tempted to look good on the examples it was built from, so a separate test set is what reveals how the model behaves on examples it has not seen. Accuracy is only a trustworthy measure when it is computed on data the model did not learn from.

Applying the Model to New Measurements

Once the measured accuracy is acceptable, the model can be applied to new data. In the source example, the new data consists of fresh flower measurements, meaning measurements that were not part of either the training set or the test set. The evaluation result is what gives confidence to take this step. The source states the expectation plainly: the model is expected to be correct about 97% of the time on such new data.

That expectation rests on assumptions. The test accuracy estimates performance only if the new measurements look like the data the model was evaluated on. The accuracy number is a measured claim about the test data, and it promises nothing beyond the conditions under which it was measured. It does not guarantee correctness on every future measurement, and it says nothing about data that comes from a different source or a different situation.

Common Mistakes in Model Evaluation

  • Common mistake

    Scoring on the training data

    What it looks like
    knn.score(X_train, y_train) is reported as the model's accuracy.
    Why it fails

    The model was built from those examples, so the number reflects how well it remembers them rather than how it handles unseen data.

    Do this instead

    Compute the accuracy with score on a held-out test set that the model did not learn from.

  • Common mistake

    Expecting fit to return predictions

    What it looks like

    Writing predictions = knn.fit(X_train, y_train) and expecting class labels.

    Why it fails

    fit builds the model from the training pair and does not return a prediction.

    Do this instead

    Call fit to build the model, then use the model's methods afterward to produce predictions or accuracy.

  • Common mistake

    Treating the accuracy as a guarantee

    Why it fails

    The accuracy is measured under specific conditions on specific test data.

    Do this instead

    Read the number as an estimate that holds for data resembling the test set, and keep the conditions in mind.

  • Common mistake

    Reusing the test set to tune the model until the score looks good, which quietly turns the test set into training material.

Predict Before Scoring

MEDIUM

Using the same four training points as the worked example (1.0 and 2.0 labeled class A, 8.0 and 9.0 labeled class B), predict the class of the new point 6.0 with k equal to 3. Before you calculate, guess whether the answer will be class A or class B and say why. Then compute the three nearest neighbors and their classes.

Hints
  • Compute the distance from 6.0 to each of the four training points first.
  • Only the three smallest distances matter when k is 3.
  • Count the classes among those three neighbors before deciding.

Key Takeaways

  • A k-nearest neighbors classifier predicts a new point by looking at its closest training neighbors, with the number of neighbors set by k, and it consults the stored training data at prediction time.
  • In Python, KNeighborsClassifier is instantiated, built with fit on training inputs and outputs, and measured with score on held-out test data; fit returns no prediction.
  • Accuracy is the proportion of correct predictions, and it is trustworthy only when computed on data the model did not learn from.
  • Overfitting means a model performs well on examples it was built from but poorly on unseen examples, so training accuracy alone cannot establish a good model.
  • A test accuracy estimate describes performance under stated conditions on data like the test set; it is not a guarantee for every future measurement.

Related concepts

More concepts starting with U