K-Nearest Neighbors and SVMs

Updated · 4 min read
mediumPython 3.13aimachine-learningknnsvmscaling

k-nearest neighbors (k-NN) predicts by finding the k most similar training examples and taking a vote among them, so it learns nothing up front and does all its work at prediction time. A support vector machine (SVM) finds the boundary that separates the classes with the widest margin, and with a "kernel" it can draw curved boundaries. Both measure distances between examples, so both need scaled features.

Why Scaling Matters

Distances need features on the same scale
ModelDescription
k-NNIt is used to predict from the k most similar training examples
SVMIt is used to separate classes with the widest-margin boundary
StandardScalerIt is used to rescale each feature to mean 0 and standard deviation 1
PipelineIt is used to chain scaling and the model so they're always applied together

Example

This program uses payments_history.csv from "Supervised Learning".

Python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
 
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
models = {
    "k-NN, raw features": KNeighborsClassifier(n_neighbors=5),
    "k-NN, scaled": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)),
    "SVM, scaled": make_pipeline(StandardScaler(), SVC()),
}
for name, model in models.items():
    model.fit(X_train, y_train)
    print(f"{name:20} test accuracy {model.score(X_test, y_test):.1%}")
 
print("Feature ranges:", {c: int(X[c].max() - X[c].min()) for c in X.columns})
Output
k-NN, raw features   test accuracy 85.6%
k-NN, scaled         test accuracy 87.2%
SVM, scaled          test accuracy 88.4%
Feature ranges: {'amount': 235, 'past_late': 5, 'autopay': 1, 'months_enrolled': 58, 'opened_reminder': 1}

Explanation: The fee amount spans 235 dollars while autopay spans just 1, so on raw features k-NN's distances are almost all about the fee amount, and it does no better than guessing "on time" (85.6%). After StandardScaler puts every feature on the same scale, k-NN reaches 87.2% and the SVM 88.4%. make_pipeline makes sure the same scaling learned from the training data is applied to every new example.

When to Use Them

ModelGood forWatch out for
k-NNSmall datasets, a quick baseline, "find similar" tasksSlow on large data; needs scaling
SVMMedium-sized data with clear marginsSlow on very large data; needs scaling and tuning

Common Mistakes

Skipping scaling. k-NN and SVMs silently perform badly.

Scaling before splitting. Fit the scaler on training data only, which a pipeline does for you.

A tiny k. k = 1 copies the noise of a single neighbor; try a few values.

Interview Corner

How does k-nearest neighbors classify a new example?

It finds the k training examples closest to it, usually by Euclidean distance, and predicts the majority label among them.

Why do k-NN and SVMs need feature scaling?

They rely on distances, so features with large numeric ranges dominate. Scaling gives each feature a comparable influence.

Practice

Exercise: choose k. Try k = 1, 5, 15 and 51 with scaling. Which k gives the best test accuracy? Explain what happens at k = 1 and at k = 51.

Check your understanding:

  1. How does k-NN make a prediction?
  2. Why did k-NN on raw features match the baseline?
  3. What does a pipeline guarantee?

Quick check: k-NN and SVMs

4 questions
1What does k-NN use to predict?
2Which feature dominated distances before scaling?
3What did the scaled SVM score?
4Why put scaling inside a pipeline?

Key Takeaways

Quick reference

NeedCode
k-NNKNeighborsClassifier(n_neighbors=5)
SVMSVC()
Scale in a pipelinemake_pipeline(StandardScaler(), model)

Was this tutorial helpful?

Lesson 125 of 186