Sub topic 12
Practical pitfalls: ties, imbalance, categorical data and memory
This chapter assumes you know how k-NN classifies by majority vote, how distance metrics work, and why features must be scaled. It covers four problems that appear once you move from toy data to real data. For each one, it explains what goes wrong and what to do about it.
Ties in the vote
A tie happens when two or more classes receive the same number of votes. With two classes and an odd k, a tie cannot occur. With three or more classes, it can occur at any k. For example, with k = 3 the neighbours may carry labels A, B and C, one vote each.
The tie-breaking rule is an implementation detail, and it can change your predictions. In the from-scratch code, Counter.most_common returns the class it saw first among equal counts. That order depends on the order of the sorted neighbours, which is arbitrary when distances are equal. In scikit-learn, a tie goes to the class with the smaller label value, which is rarely what you want.
You can reduce ties in several ways:
- Use an odd k for binary problems.
- Use
weights="distance", because exact ties in summed weights are rare. - Break the tie by reducing k by one until one class wins.
A second kind of tie involves distances. If several points sit at exactly the same distance as the k-th neighbour, the choice among them is arbitrary. This is common with integer or duplicated features.
Class imbalance
Majority vote favours common classes. Suppose 95% of your training points are class 0. In any region where the classes overlap, most of the k neighbours will be class 0, so the rare class is almost never predicted. Accuracy looks high, but recall on the rare class is poor.
Three remedies work for k-NN:
- Use distance weighting. A rare-class point that is very close can then outvote several distant majority points.
- Resample the training set. Undersample the majority class or oversample the minority class. Do this only on the training folds, never before splitting.
- Judge the model with recall, precision, or F1 for the rare class. Plain accuracy hides the problem.
Scikit-learn's KNeighborsClassifier has no class_weight option. If you need one, you can write a custom weight function, or you can lower the decision threshold on predict_proba. The probability is the fraction of the neighbours' weight in each class.
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(0, 1, (190, 2)), rng.normal(1.5, 1, (10, 2))])
y = np.array([0] * 190 + [1] * 10)
model = KNeighborsClassifier(n_neighbors=7).fit(X, y)
proba = model.predict_proba(X)[:, 1]
print("default threshold 0.5:", int((proba >= 0.5).sum()), "predicted positive")
print("lowered threshold 0.25:", int((proba >= 0.25).sum()), "predicted positive")Lowering the threshold trades precision for recall on the rare class. Choose the threshold using validation data.
Categorical features
Euclidean distance assumes that numbers have a meaningful order and spacing. A column such as colour encoded as red = 0, green = 1, blue = 2 claims that red is closer to green than to blue. That claim is false.
Your options depend on the data:
| Situation | Approach |
|---|---|
| Few categories, no order | One-hot encoding, then scale |
| Ordered categories (small, medium, large) | Ordinal encoding, then scale |
| Mostly categorical data | A mismatch-based distance such as Hamming distance, or Gower distance for mixed types |
| High-cardinality categories | Consider another model, because one-hot columns swamp the numeric features |
One-hot columns are 0 or 1, so a mismatch adds a distance of 1 (or √2 for Euclidean distance, since two columns change). Check that this contribution is comparable to your scaled numeric columns. Otherwise the categories dominate, or vanish.
Memory and prediction cost
k-NN has no training cost, but it pays for that at prediction time. The model stores the whole training set, so memory grows linearly with the number of rows. Each query compares against all stored points when you use brute force, which costs O(n·d) per query for n points in d dimensions.
Practical consequences:
- The saved model file is as large as your training data.
- Latency grows with the dataset, which matters for online services.
- Every query needs access to all training data, so you cannot discard the raw rows after fitting.
Ways to cope:
- Use a KD-tree or ball tree when the dimension is low.
- Reduce dimensions or remove irrelevant features first.
- Remove redundant training points, for example by keeping only points near class boundaries.
- Switch to approximate search for very large datasets, as the last chapter describes.
Exercise
A fraud dataset has 99% legitimate transactions and 1% fraud. A k-NN model with k = 15 reaches 99% accuracy but finds almost no fraud. Why, and what two changes would you try?
Show answer
With k = 15, a fraud point's neighbourhood almost always contains more legitimate points, so majority vote predicts "legitimate". Accuracy is high only because legitimate cases dominate. Try distance-weighted voting or a lower probability threshold for the fraud class. You could also undersample legitimate cases in the training folds. Evaluate with recall and F1 for the fraud class instead of accuracy.
Exercise
A dataset has a numeric column age and a category column city with 3,000 distinct values. Why is one-hot encoding plus k-NN a poor fit?
Show answer
One-hot encoding adds 3,000 binary columns. Any two rows from different cities differ in two of them, and that difference can outweigh the age gap. The data also becomes sparse and high-dimensional, which hurts neighbour quality and speed. Group rare cities, use a different representation such as region or coordinates, or choose a model that handles high-cardinality categories better.