Skip to main content
Albero Academy

KNN & SVM

Two intuitive classifiers — nearest neighbours and margins.

Classification9 min

Two more classic classifiers with very different ideas. KNN classifies by the majority vote of nearby points; SVM finds the boundary with the widest margin between classes.

K-nearest neighbours

vote of the k closest points
from sklearn.neighbors import KNeighborsClassifier
KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
# a new point gets the majority label of its 5 nearest neighbours

Support vector machines

widest-margin boundary
from sklearn.svm import SVC
SVC(kernel="rbf", C=1.0).fit(X_train, y_train) # non-linear boundaries via the kernel

Key takeaways

  1. 01KNN classifies by the majority label of the k nearest points.
  2. 02SVM finds the maximum-margin boundary; kernels enable non-linear boundaries.
  3. 03Both are distance-based — feature scaling is essential.
  4. 04KNN is slow to predict on big data; SVM doesn't scale to huge datasets.

Finished this chapter?

Mark it complete to track your progress through Scikit-learn.