KatInterview

Build and Tune a K-Nearest Neighbors Classifier from Scratch

Machine LearningModel answer
HardModel answerMachine Learningknnclassificationhyperparameter-tuning

Last 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.

  1. Load and inspect the labeled dataset. Check shapes, summary statistics, class balance, and missing values.
  2. Split the labeled data into a training set and a held-out test set. Preserve class proportions in both halves.
  3. 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 — not sklearn.neighbors or any other KNN library.
  4. Evaluate your classifier on the held-out test set and report accuracy.
  5. 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.
  6. Predict labels for every row in unlabeled.csv using your best configuration.
  7. 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.