Build and Tune a K-Nearest Neighbors Classifier from Scratch
Machine LearningModel answerLast updated
Implement KNN without using a pre-built classifier, tune k via cross-validation, and generate predictions for an unlabeled dataset.
Task
You have two CSV files for a three-class plant-leaf identification problem.
train.csv— three numeric columns (feature_0,feature_1,feature_2) and one class-label column.unlabeled.csv— the same three feature columns, no labels.
Complete the following steps in a Jupyter notebook.
- Load and inspect the labeled dataset. Check shapes, summary statistics, class balance, and missing values.
- Split the labeled data into a training set and a held-out test set. Preserve class proportions in both halves.
- Implement KNN from scratch. You may use NumPy, pandas, and general utilities (e.g.,
train_test_split,StratifiedKFold), but the distance calculation, neighbor selection, and voting logic must be your own code — notsklearn.neighborsor any other KNN library. - Evaluate your classifier on the held-out test set and report accuracy.
- Tune hyperparameters — especially
k, but also weighting scheme and distance metric — using cross-validation on the training split only. Do not touch the test set during tuning. - Predict labels for every row in
unlabeled.csvusing your best configuration. - Write those predictions to
predictions.csv.
What is expected
- Clean, readable notebook with explanations of each decision.
- Evidence that the scaler was fit on training data only (no leakage).
- A cross-validation curve or table showing how accuracy varies with
k. - One final test-set accuracy reported after all tuning is complete.
- A well-formed output CSV with one prediction per row.
Hints
Hint 1
Euclidean distance is dominated by features with large ranges. Standardize each feature using the mean and standard deviation computed on the training fold only — never on the full dataset or the test fold.
Hint 2
To tune k efficiently, precompute the full sorted neighbor list once per fold. You can then evaluate every candidate k from the same structure without recomputing distances.
Hint 3
Handle vote ties explicitly: when two or more classes receive equal weight, predict the tied class whose nearest representative is closest to the query point. Also guard against edge cases like k larger than the training set size and zero distances under inverse-distance weighting.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach and key decisions
Why scaling matters first
KNN uses raw distances, so a feature measured in the hundreds will swamp one measured in the tens. Standardize every feature to zero mean and unit variance. The critical rule: compute the mean and standard deviation on the training fold, then apply those same values to the validation fold, test set, and unlabeled data. Fitting the scaler on any data outside the training fold is leakage and will give an optimistic accuracy estimate that does not generalize.
What "from scratch" actually means
KNN has no gradient step. fit just stores the training points. predict does three things:
- Compute the distance from each query point to every stored point.
- Select the k closest neighbors.
- Return the majority class among those neighbors (optionally weighting each vote by inverse distance).
The vectorized distance computation is the performance-critical piece. For Euclidean distance, expand the squared norm:
||q - x||² = ||q||² + ||x||² − 2·(q · xᵀ)
This turns the distance matrix into two broadcast additions and a single matrix multiply, which NumPy executes in near-optimal BLAS speed. Use np.argpartition for O(n) exact top-k selection rather than sorting the full distance array.
Hyperparameter tuning without leakage
Use stratified k-fold cross-validation on the training split. For each fold:
- Fit the scaler on the fold's training portion.
- Precompute and sort the full neighbor list once (up to
k_maxneighbors). - Evaluate every candidate
kfrom 1 tok_maxfrom that same sorted list.
This makes tuning cheap: you pay the distance-computation cost once per fold, not once per candidate k. Typical candidates: odd values from 1 to ~30, plus a few even values to verify tie-breaking behavior. Also cross-validate over weights ("uniform" vs "distance") and optionally the distance metric (Euclidean vs Manhattan).
Report mean ± std cross-validation accuracy for each configuration, pick the configuration with the highest mean, then report test accuracy exactly once.
Complexity
| Step | Time | Space |
|---|---|---|
| Fit | O(nd) — just stores data | O(nd) |
| Distance matrix (m queries) | O(mnd) | O(mn) |
| Top-k selection per query | O(mn) via argpartition | — |
| Voting | O(mk) | — |
| CV over K candidates, F folds | O(F·n²d) amortized | O(n²) |
With n ≈ 1,000 and d = 3 this is trivially fast. For larger n, batch queries or use approximate neighbor search (ball trees, KD-trees).
Edge cases to handle
- Unknown label column name. Detect it as any column not named
feature_*. - Missing values. Check with
isna(). Impute with the training-fold median; never use test or validation statistics. - Zero standard deviation. Replace std = 0 with 1 to avoid division by zero during scaling.
- k > training size. Clamp k to the number of available training points.
- Vote ties. With three classes, ties occur even with odd k if weights are non-uniform. Break ties by predicting the tied class whose single nearest neighbor is closest to the query.
- Distance = 0 under inverse-distance weighting. Add a small epsilon (e.g., 1e-9) to every distance before inverting.
- Class imbalance. Use stratified splits and stratified folds. Report a confusion matrix alongside overall accuracy so per-class weaknesses are visible.
Python implementation
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
RNG = 42
# 1. Load and inspect
df = pd.read_csv("train.csv")
unlabeled = pd.read_csv("unlabeled.csv")
FEATURES = ["feature_0", "feature_1", "feature_2"]
LABEL = [c for c in df.columns if c not in FEATURES][0]
print(df.shape, df[LABEL].value_counts(), df.isna().sum())
df = df.dropna(subset=[LABEL])
X_all = df[FEATURES].to_numpy(dtype=float)
y_all = df[LABEL].to_numpy()
X_unl = unlabeled[FEATURES].to_numpy(dtype=float)
class Standardizer:
def fit(self, X):
self.median_ = np.nanmedian(X, axis=0)
X = np.where(np.isnan(X), self.median_, X)
self.mean_ = X.mean(axis=0)
std = X.std(axis=0)
self.std_ = np.where(std == 0, 1.0, std)
return self
def transform(self, X):
X = np.where(np.isnan(X), self.median_, X)
return (X - self.mean_) / self.std_
class KNNClassifier:
def __init__(self, k=5, weights="uniform"):
self.k = k
self.weights = weights
def fit(self, X, y):
self.X_ = np.asarray(X, dtype=float)
self.classes_, self.y_ = np.unique(y, return_inverse=True)
return self
def _dist_matrix(self, Q):
Q = np.asarray(Q, dtype=float)
sq = (Q ** 2).sum(1)[:, None] + (self.X_ ** 2).sum(1)[None, :] \
- 2 * Q @ self.X_.T
return np.sqrt(np.maximum(sq, 0))
def _sorted_neighbors(self, Q, k_max):
D = self._dist_matrix(Q)
k_max = min(k_max, D.shape[1])
part = np.argpartition(D, k_max - 1, axis=1)[:, :k_max]
d_part = np.take_along_axis(D, part, axis=1)
order = np.argsort(d_part, axis=1)
return (np.take_along_axis(part, order, axis=1),
np.take_along_axis(d_part, order, axis=1))
def predict(self, Q, k=None):
k = min(k or self.k, len(self.X_))
idx, dist = self._sorted_neighbors(Q, k)
n_cls = len(self.classes_)
preds = np.empty(len(idx), dtype=int)
for i in range(len(idx)):
labs, d = self.y_[idx[i, :k]], dist[i, :k]
w = 1.0 / (d + 1e-9) if self.weights == "distance" \
else np.ones(k)
scores = np.bincount(labs, weights=w, minlength=n_cls)
tied = np.flatnonzero(np.isclose(scores, scores.max()))
preds[i] = tied[0] if len(tied) == 1 \
else next(l for l in labs if l in tied)
return self.classes_[preds]
# 2. Stratified split
X_tr, X_te, y_tr, y_te = train_test_split(
X_all, y_all, test_size=0.2, stratify=y_all, random_state=RNG)
# 5. Cross-validation over k and weights
candidates = [(k, w)
for k in range(1, 32, 2)
for w in ("uniform", "distance")]
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=RNG)
results = {}
for k_val, w in candidates:
fold_acc = []
for tr_idx, val_idx in skf.split(X_tr, y_tr):
Xf_tr, Xf_val = X_tr[tr_idx], X_tr[val_idx]
yf_tr, yf_val = y_tr[tr_idx], y_tr[val_idx]
sc = Standardizer().fit(Xf_tr)
clf = KNNClassifier(k=k_val, weights=w).fit(
sc.transform(Xf_tr), yf_tr)
preds = clf.predict(sc.transform(Xf_val))
fold_acc.append(np.mean(preds == yf_val))
results[(k_val, w)] = np.mean(fold_acc)
best = max(results, key=results.get)
best_k, best_w = best
print(f"Best config: k={best_k}, weights={best_w}, "
f"CV acc={results[best]:.4f}")
# 4. Final evaluation on held-out test set
sc_final = Standardizer().fit(X_tr)
clf_final = KNNClassifier(k=best_k, weights=best_w).fit(
sc_final.transform(X_tr), y_tr)
test_preds = clf_final.predict(sc_final.transform(X_te))
print(f"Test accuracy: {np.mean(test_preds == y_te):.4f}")
# 6–7. Predict unlabeled and write output
unl_preds = clf_final.predict(sc_final.transform(X_unl))
pd.DataFrame({"label": unl_preds}).to_csv("predictions.csv", index=False)
print("predictions.csv written.")
Common mistakes
- Fitting the scaler on the full dataset before splitting — the most frequent leakage error.
- Tuning k by evaluating different values on the test set, then reporting that test accuracy as unbiased.
- Forgetting to handle ties, leading to non-deterministic predictions that differ across runs.
- Using Manhattan distance without re-tuning k; the optimal k often shifts because the effective neighborhood size changes.
- Not reporting a confusion matrix, which hides that 97% overall accuracy might mask one class with 60% recall.