Sub topic 12
Practical pitfalls: ties, imbalance, categorical data and memory
This chapter assumes you can already fit a KNeighborsClassifier, you know why features must be scaled, and you have used cross-validation to pick k. The basic algorithm is simple. Most real failures come from details it leaves out: what happens when the vote is level, what happens when one class dominates, how to measure distance on non-numeric columns, and what the stored training set costs.
Ties in the vote
A tie happens in two ways.
- Vote tie. With
k = 4and two classes, two neighbours can say 0 and two can say 1. With three or more classes, a tie is possible for anyk. For example,k = 5can split 2, 2, 1. - Distance tie at the boundary. Several training points can sit at exactly the same distance as the k-th neighbour, so "the k nearest" is not unique. This is common with integer or heavily rounded features and with duplicated rows.
For two classes, an odd k removes vote ties. It does nothing for three or more classes, and it does nothing for boundary distance ties.
Libraries break ties by rule, not by evidence. In scikit-learn the winner among tied classes is, in current versions, the one that comes first in the sorted class list. That is the lowest label. This is an implementation detail, so don't rely on it. For boundary ties, the point that comes first in the stored data order may be the one that gets picked. If you shuffle your rows, predictions for tied queries can change.
Your own tie-break should be deliberate. A common choice is to give the tie to the class whose tied neighbours are closer on average:
import numpy as np
from collections import Counter
def vote_with_tiebreak(labels, dists):
counts = Counter(labels.tolist())
top = max(counts.values())
tied = [c for c, n in counts.items() if n == top]
if len(tied) == 1:
return tied[0]
# Tie: choose the class whose neighbours are closest on average
return min(tied, key=lambda c: dists[labels == c].mean())
labels = np.array([0, 1, 0, 1])
dists = np.array([0.5, 0.2, 0.9, 0.4])
print(vote_with_tiebreak(labels, dists)) # 1Class 0 has mean distance 0.7 and class 1 has 0.3, so class 1 wins. Distance-weighted voting, covered earlier, gets a similar effect automatically. Ties become very unlikely because the weights are real numbers.
Class imbalance
Plain majority voting favours big classes. Suppose 95% of the training points are class 0. Around a minority-class query, a neighbourhood of k = 15 points is likely to contain mostly class 0 points, even when the query sits inside a minority cluster. This effect gets stronger as k grows. Large k smooths over small classes.
Accuracy hides the damage. A model that never predicts the minority class scores 95%. Use these instead:
- Recall and precision for the minority class.
- Balanced accuracy, which is the mean of per-class recall.
- Precision-recall curves, not ROC curves, when the positive class is rare.
KNeighborsClassifier has no class_weight option, so the remedies are different from those for linear models or trees:
- Lower the decision threshold.
predict_probareturns the fraction of neighbours in each class, or the weighted fraction whenweights="distance". Predict the minority class when its fraction passes a threshold below 0.5. - Resample the training set. Undersample the majority class or oversample the minority class. Do this only on training folds, never before splitting. Oversampling by duplication creates distance ties, because duplicates sit at identical positions.
- Use a smaller
k. Smallkis more sensitive to local minority clusters, at the cost of more variance. - Pass a custom
weightscallable that scales each neighbour's vote by its class. This is an advanced option. Test it carefully.
from sklearn.datasets import make_classification
from sklearn.metrics import balanced_accuracy_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=3000, n_features=10, n_informative=5,
weights=[0.95, 0.05], class_sep=1.0, random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
for threshold in (0.5, 0.2):
pred = (proba >= threshold).astype(int)
print(
threshold,
"recall:", round(recall_score(y_test, pred), 3),
"balanced acc:", round(balanced_accuracy_score(y_test, pred), 3),
)Lowering the threshold from 0.5 to 0.2 normally raises minority recall and costs some precision. Choose the threshold on validation data, not on the test set.
Categorical features
Euclidean distance assumes that the difference between 3 and 5 is meaningful. For a column such as plan with values basic and pro, it is not. There are two practical options.
Encode, then use a numeric metric. One-hot encoding turns each category into a 0/1 column. Two rows with different categories then differ by 1 in two columns, which adds 2 to the squared Euclidean distance. Some points to watch:
- Label-encoding (
basic=0,pro=1,enterprise=2) invents an order and a spacing. Use it only for truly ordinal data. - One-hot columns have a different scale from standardized numeric columns. A category mismatch contributes a fixed amount. If that is too much or too little compared with the numeric columns, you can multiply the one-hot block by a constant. Treat the constant as a hyperparameter.
- A column with 200 categories adds 200 dimensions. This worsens the curse of dimensionality. Group rare categories or drop the column.
- Pass
handle_unknown="ignore"so a category unseen in training doesn't crash prediction.
Use a matching metric. If all features are categorical or binary, Hamming distance (the fraction of positions that differ) is a natural fit. Scikit-learn supports metric="hamming" with brute-force search on encoded data. For mixed data, Gower distance is the standard choice, but scikit-learn doesn't provide it directly. You would have to pass a precomputed distance matrix.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [25, 32, 47, 51, 62, 23],
"income": [40000, 52000, 88000, 95000, 61000, 38000],
"plan": ["basic", "basic", "pro", "pro", "basic", "pro"],
})
y = [0, 0, 1, 1, 1, 0]
pre = ColumnTransformer([
("num", StandardScaler(), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
])
model = make_pipeline(pre, KNeighborsClassifier(n_neighbors=3)).fit(df, y)
new = pd.DataFrame({"age": [45], "income": [80000], "plan": ["pro"]})
print(model.predict(new)) # [1]The ColumnTransformer lives inside the pipeline. The scaler's mean and standard deviation are therefore learned only from training data, including inside each cross-validation fold.
Memory and query cost
k-NN has no fit step, but it has to keep the whole training set. A model is as large as its data. It pays for that at prediction time. With brute-force search, one query costs about n × d operations, where n is the number of training rows and d the number of features. Prediction latency grows linearly with n.
The numbers add up quickly:
| Rows | Features | float64 | float32 |
|---|---|---|---|
| 100,000 | 50 | 40 MB | 20 MB |
| 1,000,000 | 100 | 800 MB | 400 MB |
| 10,000,000 | 100 | 8 GB | 4 GB |
Search trees (KD-tree, ball tree) add a further index on top of the data. In high dimensions they often fail to beat brute force, as the curse-of-dimensionality chapter showed. Pickling a fitted model writes the data and the index to disk, so saved models can be large.
Batch prediction has its own cost. Computing distances for a large query set against a large training set can create very large temporary arrays. Scikit-learn processes queries in chunks to limit this, but you can still help by predicting in batches yourself.
import numpy as np
rng = np.random.default_rng(0)
X = rng.random((100_000, 50))
X32 = X.astype(np.float32)
print(X.nbytes / 1e6, "MB as float64") # 40.0
print(X32.nbytes / 1e6, "MB as float32") # 20.0Ways to reduce the cost, from least to most invasive:
- Convert features to
float32. Check that accuracy is unchanged on validation data. - Remove duplicate and uninformative rows, or reduce the dimension first with feature selection or PCA.
- Keep a condensed set of prototype points per class, for example cluster centres. This trades accuracy for size.
- Use approximate nearest neighbour indexes when
nreaches millions, as the next chapter describes.
A short checklist
- Count the classes and the distribution of distances. Check how often ties occur.
- Report minority-class recall, not only accuracy, when classes are unequal.
- Encode categories explicitly and decide how much weight they should carry.
- Estimate memory as
n × d × bytes per valuebefore you scale up. - Keep scaling, encoding and tuning inside one pipeline.
Exercise
A three-class k-NN model uses k = 5 and uniform weights. For one query the neighbour labels are A, A, B, B, C. Why does odd k not prevent a tie here, and what are two ways to resolve it?
Show answer
Odd k only prevents ties with two classes. With three classes the votes can split 2, 2, 1, so A and B tie. Two ways to resolve it are to switch to distance-weighted voting, which makes exact ties unlikely, or to choose the tied class whose neighbours have the smaller mean distance to the query.
Exercise
A fraud dataset has 99% legitimate and 1% fraudulent rows. A k-NN model with k = 25 reaches 99% accuracy. Name one reason this number is misleading and one change that could improve detection of fraud.
Show answer
A model that always predicts "legitimate" also scores 99%, so accuracy says nothing about fraud detection. Check recall and precision for the fraud class instead. To detect more fraud, lower the probability threshold for predicting fraud (for example from 0.5 to 0.1), reduce k, or undersample the legitimate class inside the training folds.
Exercise
A table holds 2,000,000 rows and 64 float64 features. About how much memory does the training matrix need, and how much if you convert to float32?
Show answer
2,000,000 × 64 × 8 bytes is 1.024 GB as float64. As float32 it is half of that, 0.512 GB. A tree index would add more on top of that.