Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

k-Nearest Neighbors and Classification Evaluation Metrics

This notebook covers:

  1. Review of k-Nearest Neighbors (kNN) algorithm

  2. Classification evaluation metrics: Accuracy, Precision, Recall, and F1-Score

Notebook Cell

Review of k-Nearest Neighbors (kNN)

The k-Nearest Neighbors algorithm is a non-parametric, instance-based learning method used for classification and regression. The algorithm works by finding the k training samples closest in distance to a new sample and predicting the class label based on a majority vote.

Key Characteristics of kNN:

  • Non-parametric: The algorithm doesn’t make assumptions about the underlying data distribution.

  • Instance-based (lazy learning): No explicit training phase; the model simply stores the training data.

  • Distance-based: Predictions are made based on the distance between points.

The kNN Algorithm:

  1. Store all training samples with their class labels.

  2. For a new sample x:

    • Calculate the distance between x and all training samples.

    • Select the k closest training samples (k-nearest neighbors).

    • Assign the class label based on majority voting among the k neighbors.

Distance Metrics:

The most common distance metrics used in kNN are:

  1. Euclidean Distance: d(x,y)=∑i=1n(xi−yi)2d(x, y) = \sqrt{\sum_{i=1}^{n} (x_i - y_i)^2}

  2. Manhattan Distance: d(x,y)=∑i=1n∣xi−yi∣d(x, y) = \sum_{i=1}^{n} |x_i - y_i|

  3. Minkowski Distance: d(x,y)=(∑i=1n∣xi−yi∣p)1/pd(x, y) = (\sum_{i=1}^{n} |x_i - y_i|^p)^{1/p}

Let’s implement and visualize the kNN algorithm:

Source
<Figure size 1000x600 with 2 Axes>
Source
<Figure size 1500x500 with 3 Axes>

Observations on kNN Behavior:

  1. Effect of k:

    • Small k: Decision boundaries are more complex and can lead to overfitting

    • Large k: Decision boundaries are smoother but may miss important patterns

  2. Computational Complexity:

    • Training: O(1) - just stores the data

    • Prediction: O(nd) where n is the number of training samples and d is the number of features

  3. Curse of Dimensionality:

    • As the number of dimensions increases, the distance metric becomes less meaningful

    • In high dimensions, all points tend to be equidistant from each other

Classification Evaluation Metrics

To evaluate the performance of classification models, we need appropriate metrics. The choice of metric depends on the problem context and the relative importance of different types of errors.

Confusion Matrix

A confusion matrix is a table that describes the performance of a classification model. For a binary classification problem, it contains:

  • True Positives (TP): Correctly predicted positive cases

  • False Positives (FP): Incorrectly predicted positive cases (Type I error)

  • True Negatives (TN): Correctly predicted negative cases

  • False Negatives (FN): Incorrectly predicted negative cases (Type II error)

Let’s create a binary classification problem using make_classification and visualize its confusion matrix:

Source
<Figure size 1000x600 with 2 Axes>
Source
<Figure size 800x400 with 2 Axes>
True Negatives (TN): 141
False Positives (FP): 6
False Negatives (FN): 13
True Positives (TP): 140

Accuracy

Accuracy is the ratio of correctly predicted instances to the total instances.

Accuracy=TP+TNTP+TN+FP+FN\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}

Pros:

  • Simple and intuitive

  • Works well for balanced datasets

Cons:

  • Misleading for imbalanced datasets

  • Doesn’t distinguish between types of errors

Accuracy: 0.9367
Manually calculated accuracy: 0.9367

Precision & Recall

Precision

Precision is the ratio of correctly predicted positive observations to the total predicted positives. It answers the question: “Of all instances predicted as positive, how many are actually positive?”

Precision=TPTP+FP\text{Precision} = \frac{TP}{TP + FP}

Key Applications and Examples:

  • Spam Email Detection - incorrectly flagging important emails is costly

  • Medical Testing - avoiding false diagnoses that lead to unnecessary treatment

  • Autonomous Vehicles - misidentifying obstacles could cause dangerous reactions

Pros:

  • Critical when false positives (FP) have severe consequences

  • Essential for applications where incorrect positive predictions are costly

  • Particularly valuable in information retrieval systems where relevance is key

Cons:

  • Ignores false negatives (may miss important cases)

  • Can be misleadingly high if the model is overly conservative in predictions

  • Not sufficient alone for imbalanced datasets where negatives dominate

Precision: 0.9589
Manually calculated precision: 0.9589

Recall (Sensitivity)

Recall is the ratio of correctly predicted positive observations to all actual positives. It answers the question: “Of all actual positive instances, how many did we predict correctly?”

Recall=TPTP+FN\text{Recall} = \frac{TP}{TP + FN}

Key Applications and Examples:

  • Medical Diagnostics

  • Fraud Detection

  • Landmine Detection

  • Security Surveillance

  • Earthquake Early Warning Systems

  • Cybersecurity Threat Detection

  • Search and Rescue Operations

Pros:

  • Critical when the cost of false negatives (FN) is high (e.g., life-threatening scenarios).

  • Essential for medical screening and public safety applications.

Cons:

  • Does not account for false positives (FP) (may lead to unnecessary alerts).

  • Can be inflated artificially if a model labels everything as positive.

Trade-off Note: In many real-world systems, there’s an inverse relationship between precision and recall - improving one typically worsens the other. The right balance depends on which type of error (FP vs FN) is more costly for your specific application.

Recall: 0.9150
Manually calculated recall: 0.9150

F1-Score

F1-Score is the harmonic mean of Precision and Recall. It provides a balance between precision and recall.

F1-Score=2×Precision×RecallPrecision+Recall\text{F1-Score} = 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}

Pros:

  • Balances precision and recall

  • Works well for imbalanced datasets

Cons:

  • May not be appropriate if one metric is more important than the other

  • Doesn’t consider true negatives

F1-Score: 0.9365
Manually calculated F1-Score: 0.9365

Precision-Recall Trade-off

There is often a trade-off between precision and recall. Increasing one typically decreases the other.

Let’s visualize this trade-off by adjusting the decision threshold for a probabilistic classifier:

<Figure size 1000x600 with 2 Axes>
Source

See this example of sklearn about weights in kNN

Source
<Figure size 1000x500 with 6 Axes>
Source
<Figure size 1200x600 with 2 Axes>

Choosing the Right Metric

The choice of evaluation metric depends on the specific problem and the relative costs of different types of errors:

  • Accuracy: Use when classes are balanced and all types of errors have similar costs

  • Precision: Use when false positives are more costly (e.g., spam detection)

  • Recall: Use when false negatives are more costly (e.g., disease detection)

  • F1-Score: Use when you need a balance between precision and recall

Is There an “Optimal Point” on the Precision-Recall Curve?

Short answer: No, there is no single, universally optimal point on a Precision-Recall Curve. However, the concept of an “optimal point” can be defined in several meaningful ways, depending on the problem context.

Why There Is No Absolute Optimal Point

1. The Nature of the Trade-off

Every point on the Precision-Recall Curve corresponds to a different decision threshold. As we move along the curve:

  • Increasing the threshold raises Precision but lowers Recall.

  • Decreasing the threshold raises Recall but lowers Precision.

Therefore, each point represents a different balance between the two metrics, and no single point simultaneously maximizes both (except in the ideal case where the curve reaches the top-right corner).

2. Dependence on Error Costs

“Optimal” is defined by the relative cost of False Positives vs. False Negatives in a given application:

  • If FPs are more costly (e.g., spam detection), a point with high Precision is optimal.

  • If FNs are more costly (e.g., cancer diagnosis), a point with high Recall is optimal.

  • If the costs are balanced, the point that maximizes the F1-Score is a reasonable choice.

What Can Be Considered “Optimal”?

1. The Point with the Highest F1-Score

This is the most common criterion for selecting a point on the curve. F1-Score is the harmonic mean of Precision and Recall, and the point that maximizes it provides a sensible balance between the two.

Looking at the left plot above (Precision, Recall, and F1-Score vs. Threshold), the F1-Score (green line) reaches a peak at a specific threshold. Note that this peak may not occur at 0.5 — especially for imbalanced datasets, the optimal F1 threshold is often lower than 0.5 (in this example, around 0.29–0.32).

2. The Point Closest to the Top-Right Corner

In some analyses, the point with the minimum Euclidean distance to (Precision=1, Recall=1) is selected as optimal. This criterion is simple but ignores the actual costs of the problem.

Finding the Optimal Threshold Using a Dense Grid

This code evaluates 100 evenly spaced thresholds between 0 and 1 to find the one that maximizes the F1-Score, providing a fine-grained approximation of the optimal decision boundary.

Best threshold: 0.29, Best F1: 0.8757

Finding the Optimal Threshold Using Scikit-learn’s precision_recall_curve

This code uses Scikit-learn’s built-in precision_recall_curve function, which computes precision and recall at every distinct probability value produced by the model, yielding a more precise and principled estimate of the optimal threshold.

Best threshold: 0.32

Why the Visual “Optimal Point” at 0.5 Differs from the Computational Result

In the original notebook, only five thresholds (0, 0.1, 0.5, 0.9, 1) were evaluated. The resulting plot is therefore a very coarse approximation — just five points connected by lines. Visually, F1 appears to peak at 0.5 simply because no finer thresholds were tested between 0.1 and 0.5.

When a dense grid of thresholds (e.g., 100 points via np.linspace) or precision_recall_curve is used, the true maximum of F1-Score is found at a lower threshold (around 0.29–0.32 in this example). This is expected for imbalanced datasets:

  • At a high threshold (e.g., 0.5), the model predicts the positive class only when highly confident, resulting in low Recall.

  • At a lower threshold (e.g., 0.3), the model predicts the positive class more often, raising Recall at a small cost to Precision. Since F1 is the harmonic mean, this balance typically yields a higher F1-Score.

Small Differences Between the Two Methods (0.29 vs. 0.32)

The two approaches find slightly different optimal thresholds:

  • The np.linspace method evaluates 100 evenly spaced thresholds and returns the closest one (0.29).

  • The precision_recall_curve method evaluates thresholds at every distinct probability value produced by the model, yielding a more principled estimate (0.32).

The difference of ~0.03 is negligible and both methods point to the same optimal region. For final reporting, precision_recall_curve is generally preferred because it is based on the actual distribution of predicted probabilities rather than an arbitrary grid.

CriterionOptimal Point
Maximize F1-ScoreThe point with the highest F1 (≈ 0.29–0.32 in this example)
Minimize total costDepends on the relative costs of FP and FN
Closest to (1, 1)Minimum Euclidean distance to the top-right corner
Maximum Recall with acceptable PrecisionThe threshold that keeps Precision above a desired level

In short, the “optimal point” is a relative concept that depends on the selection criterion and the error costs of the specific problem. In this notebook, the most reasonable choice is the point that maximizes the F1-Score, which occurs at a threshold around 0.3, not at the default 0.5.

Further Reading

Metrics for Multi-class Classification

For multi-class problems, these metrics can be extended using different averaging strategies:

  • Macro-averaging: Calculate the metric for each class and take the average (treats all classes equally)

  • Micro-averaging: Calculate the metric using the total true positives, false positives, etc. (biased toward larger classes)

  • Weighted-averaging: Calculate the metric for each class and take the weighted average based on class frequency

Further Reading

Metrics for Multi-class Classification

For multi-class problems, these metrics can be extended using different averaging strategies:

  • Macro-averaging: Calculate the metric for each class and take the average (treats all classes equally)

  • Micro-averaging: Calculate the metric using the total true positives, false positives, etc. (biased toward larger classes)

  • Weighted-averaging: Calculate the metric for each class and take the weighted average based on class frequency

Source
Multi-class Classification Metrics:
            Macro   Micro  Weighted
Precision  0.9652  0.9667    0.9677
Recall     0.9648  0.9667    0.9667
F1-Score   0.9645  0.9667    0.9666

Summary

In this notebook, we’ve covered:

  1. k-Nearest Neighbors (kNN):

    • A non-parametric, instance-based learning algorithm

    • Uses distance metrics to find the k closest training examples

    • Makes predictions based on majority voting

    • The choice of k affects the complexity of decision boundaries

  2. Classification Evaluation Metrics:

    • Confusion Matrix: A table showing the counts of true/false positives/negatives

    • Accuracy: The proportion of correct predictions

    • Precision: The proportion of true positives among predicted positives

    • Recall: The proportion of true positives among actual positives

    • F1-Score: The harmonic mean of precision and recall

    • Precision-Recall Trade-off: Adjusting the decision threshold affects precision and recall

These concepts form the foundation for understanding classification algorithms and evaluating their performance. In the next notebook, we’ll explore Voronoi diagrams and their connection to kNN and Bayesian decision theory.

References

  1. Duda, R. O., Hart, P. E., & Stork, D. G. (2001). Pattern Classification (2nd ed.). Wiley-Interscience.

  2. Precision and Recall - Wikipedia

  3. Confusion Matrix - Wikipedia

  4. Scikit-learn Documentation - Model Evaluation