K-Nearest Neighbors and SVMs
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
| Model | Description |
|---|---|
| k-NN | It is used to predict from the k most similar training examples |
| SVM | It is used to separate classes with the widest-margin boundary |
| StandardScaler | It is used to rescale each feature to mean 0 and standard deviation 1 |
| Pipeline | It is used to chain scaling and the model so they're always applied together |
Example
This program uses payments_history.csv from "Supervised Learning".
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})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
| Model | Good for | Watch out for |
|---|---|---|
| k-NN | Small datasets, a quick baseline, "find similar" tasks | Slow on large data; needs scaling |
| SVM | Medium-sized data with clear margins | Slow 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:
- How does k-NN make a prediction?
- Why did k-NN on raw features match the baseline?
- What does a pipeline guarantee?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| k-NN | KNeighborsClassifier(n_neighbors=5) |
| SVM | SVC() |
| Scale in a pipeline | make_pipeline(StandardScaler(), model) |
Was this tutorial helpful?