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 - which we saw in Hyperparameters and Model Validation - 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 (as described in Duda et al.):

  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

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