Knowledge / Artificial Intelligence and Data Science / Support vector machines and k-nearest neighbours

Support vector machines and k-nearest neighbours

Artificial Intelligence and Data Science (B.E./B.Tech) · Machine learning · free study notes for exams, placements and interviews

In short

Support vector machines (SVM) and k-nearest neighbours (KNN) are two classical supervised learning algorithms that sit at opposite ends of the modelling spectrum: SVM fits one global decision boundary that maximises the margin between classes, while KNN stores the training data and decides each query locally by majority vote of its nearest neighbours. SVM dominates small-to-medium, high-dimensional problems (text, gene expression, handwriting) and KNN is the standard baseline, recommender-style matcher and teaching example for instance-based learning. Both are examined heavily in AICTE/CBCS machine learning papers and in GATE DA (Data Science and AI), where margin geometry, kernels, distance metrics and the curse of dimensionality are recurring questions. In Indian placement tests (TCS Digital, Infosys, Wipro, Accenture, Mu Sigma, Fractal, ZS, Flipkart, Swiggy) interviewers use them to test whether a candidate understands scaling, regularisation and the bias-variance effect of a single hyperparameter.

Explained

Separating hyperplanes and the maximum-margin idea

Hard margin, soft margin and the C parameter

  1. Hard-margin primal: minimise ½||w||² subject to yᵢ(wᵀxᵢ + b) ≥ 1 for all i. A convex quadratic programme (QP) - a single global optimum, no local minima.
  2. Real data overlap, so slack variables ξᵢ ≥ 0 are introduced: yᵢ(wᵀxᵢ + b) ≥ 1 − ξᵢ. ξᵢ = 0 means correctly classified outside the margin; 0 < ξᵢ ≤ 1 means inside the margin; ξᵢ > 1 means misclassified.
  3. Soft-margin primal: minimise ½||w||² + C Σξᵢ. C is the penalty for violations.
  4. Role of C: large C → few violations tolerated, narrow margin, low bias / high variance (approaches hard margin, risks overfitting noise). Small C → wide margin, more violations, high bias / low variance. C is therefore the regularisation knob; in the loss view, 1/C plays the role of λ.
  5. Hinge-loss view: soft-margin SVM is equivalent to minimising Σ max(0, 1 − yᵢ f(xᵢ)) + (1/2C)·... i.e. hinge loss + L2 penalty. The hinge loss is zero once a point is correctly classified beyond the margin - unlike logistic loss, which is never exactly zero.
  6. Dual formulation: maximise Σαᵢ − ½ΣΣ αᵢαⱼyᵢyⱼ xᵢᵀxⱼ subject to 0 ≤ αᵢ ≤ C and Σαᵢyᵢ = 0. Then w = Σαᵢyᵢxᵢ, and only points with αᵢ > 0 (support vectors) contribute.
  7. KKT conditions (examined as a derivation outline): αᵢ = 0 → point outside margin; 0 < αᵢ < C → point exactly on margin (used to compute b); αᵢ = C → point inside margin or misclassified.
  8. Why the dual matters: it depends on data only through inner products xᵢᵀxⱼ, which opens the door to kernels. Solvers use SMO (sequential minimal optimisation), which optimises two multipliers at a time.

Kernels and non-linear SVM

Multi-class SVM, SVR and practical notes

k-nearest neighbours: how it works

  1. Instance-based, lazy, non-parametric: there is no training phase beyond storing the data (and perhaps building an index). All computation happens at query time - hence "lazy learning". It is also a memory-based and non-generalising method.
  2. For a query x: compute distance to all n training points, take the k smallest, and (classification) assign the majority class, or (regression) the mean/median of the k neighbours' targets.
  3. Distance metrics:
    • Euclidean (L2): √Σ(xᵢ − zᵢ)² - the default for continuous features.
    • Manhattan (L1): Σ|xᵢ − zᵢ| - more robust in high dimensions and for grid-like data.
    • Minkowski (Lp): (Σ|xᵢ − zᵢ|p)1/p; p = 2 is Euclidean, p = 1 is Manhattan.
    • Hamming - categorical/binary features; cosine distance - text and TF-IDF vectors; Mahalanobis - accounts for feature covariance.
  4. Choosing k: k = 1 gives zero training error but very high variance (fits noise); large k smooths the boundary, raises bias, and k = n predicts the overall majority always. Choose by cross-validation; a common rough start is k ≈ √n. Use odd k for two-class problems to avoid ties.
  5. Weighted KNN: weight each neighbour by 1/distance (or a kernel), so closer points count more - reduces sensitivity to k and breaks ties naturally.
  6. Decision boundary is piecewise linear and irregular; with k = 1 it is exactly the Voronoi tessellation of the training points.
  7. Speed-ups: KD-tree (efficient for d ≲ 20), ball-tree (better for higher d and non-Euclidean metrics), and approximate nearest neighbour libraries (LSH, HNSW, FAISS) for large-scale search. Brute force is O(nd) per query.
  8. Curse of dimensionality: as d grows, all pairwise distances become nearly equal, so "nearest" loses meaning and the data needed to keep a neighbourhood locally dense grows exponentially. Remedy: feature selection or reduction before KNN.
  9. Editing and condensing: condensed nearest neighbour (CNN) keeps a consistent subset (consistent with the full set's 1-NN labels, though not guaranteed to be the minimal such subset); edited NN (ENN) removes noisy/misclassified points - both shrink the stored set.
  10. Missing values and categorical data must be handled explicitly (imputation, one-hot with care, or a mixed metric such as Gower).

Comparing the two, and when to use which

Key points

Formulas and examples

Hyperplane and prediction: f(x) = wᵀx + b; ŷ = sign(f(x)), y ∈ {−1, +1}
Distance of point x from hyperplane: r = |wᵀx + b| / ||w|| (same units as x)
Margin width (canonical scaling, |wᵀx + b| = 1 at the closest points): M = 2 / ||w||
Hard-margin primal: min ½||w||² s.t. yᵢ(wᵀxᵢ + b) ≥ 1 ∀i
Soft-margin primal: min ½||w||² + C Σᵢ₌₁ⁿ ξᵢ s.t. yᵢ(wᵀxᵢ + b) ≥ 1 − ξᵢ, ξᵢ ≥ 0; C > 0 (dimensionless penalty)
Hinge loss form: min (1/2)||w||² + C Σ max(0, 1 − yᵢ(wᵀxᵢ + b))
Dual: max_α Σαᵢ − ½ ΣᵢΣⱼ αᵢαⱼ yᵢyⱼ K(xᵢ, xⱼ) s.t. 0 ≤ αᵢ ≤ C, Σαᵢyᵢ = 0
Weights and prediction from the dual: w = Σ αᵢ yᵢ xᵢ; f(x) = Σ αᵢ yᵢ K(xᵢ, x) + b
Kernels: linear xᵀz; polynomial (γxᵀz + r)p; RBF exp(−γ||x − z||²), γ = 1/(2σ²); sigmoid tanh(γxᵀz + r)
SVR: min ½||w||² + C Σ(ξᵢ + ξᵢ*), errors within ±ε not penalised (ε in target units)
Minkowski distance: d(x, z) = (Σᵏⱼ₌₁ |xⱼ − zⱼ|p)1/p; p = 2 Euclidean, p = 1 Manhattan
KNN regression: ŷ = (1/k) Σ_{i∈N_k(x)} yᵢ; distance-weighted: ŷ = Σ wᵢyᵢ / Σ wᵢ, wᵢ = 1/d(x, xᵢ)
Standardisation (needed by both): z = (x − μ) / σ
Brute-force KNN query cost: O(n d) distance computations per query point

Example 1 - margin width and classification from a given hyperplane. A linear SVM trained on two features (experience in years, CTC in ₹ lakh per annum) gives w = (2, −1), b = −3, i.e. 2x₁ − x₂ − 3 = 0.

Example 2 - deriving w and b for a two-point separable problem. Positive point x⁺ = (3, 3), y = +1; negative point x⁻ = (1, 1), y = −1; both are support vectors.

Example 3 - KNN classification by hand, with and without scaling. Training data for shortlisting candidates; query Q = (CGPA 7.6, coding score 62).

#CGPACoding score (0-100)Class
18.070Shortlisted
27.055Rejected
37.865Shortlisted
46.560Rejected
58.550Rejected

Raw Euclidean distances from Q = (7.6, 62):

k = 3 nearest: P4 (2.283, Rejected), P3 (3.007, Shortlisted), P2 (7.026, Rejected) → majority Rejected. Note the CGPA term contributes almost nothing - the coding score dominates purely because of its scale.

Now min-max scale each column to [0,1] (CGPA range 6.5-8.5 → divide by 2.0; score range 50-70 → divide by 20). Q becomes ((7.6−6.5)/2, (62−50)/20) = (0.55, 0.60).

k = 3 nearest: P3 (0.180, Shortlisted), P1 (0.447, Shortlisted), P2 (0.461, Rejected) → majority Shortlisted. Scaling flipped the answer - this is the single most common KNN exam/interview point.

Example 4 - KNN regression, plain and distance-weighted. Predict monthly rent (₹) from flat area; the k = 3 nearest flats have targets ₹18,000 (d = 1.0), ₹22,000 (d = 2.0), ₹28,000 (d = 4.0).

Example 5 - RBF kernel value and the effect of γ. x = (1, 2), z = (2, 4): ||x − z||² = (−1)² + (−2)² = 5.

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV, StratifiedKFold

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

# Scaler inside the pipeline so it is re-fitted on each CV training fold only
svm = Pipeline([("sc", StandardScaler()), ("clf", SVC(kernel="rbf"))])
gs_svm = GridSearchCV(svm,
                      {"clf__C": [0.1, 1, 10, 100],
                       "clf__gamma": [1e-3, 1e-2, 0.1, 1]},
                      cv=cv, scoring="f1_macro").fit(X, y)

knn = Pipeline([("sc", StandardScaler()), ("clf", KNeighborsClassifier())])
gs_knn = GridSearchCV(knn,
                      {"clf__n_neighbors": [1, 3, 5, 7, 11, 15, 21],
                       "clf__weights": ["uniform", "distance"],
                       "clf__p": [1, 2]},
                      cv=cv, scoring="f1_macro").fit(X, y)

print(gs_svm.best_params_, gs_svm.best_score_)
print(gs_knn.best_params_, gs_knn.best_score_)
print("support vectors per class:", gs_svm.best_estimator_["clf"].n_support_)
AspectSVMKNN
Learning styleEager, global boundaryLazy, local, instance-based
Parameters storedw, b, support vectorsThe entire training set
Training costO(n²d)-O(n³d)~O(1) (or index build)
Prediction costO(#SV × d)O(nd) brute force
Key hyperparametersC, kernel, γ / degreek, distance metric, weights
High dimensionsWorks well, even d > nDegrades (distance concentration)
Outlier sensitivityLow with small CHigh with small k
Probability outputNeeds Platt scalingNatural: fraction of neighbours
Multi-classNeeds OvR / OvONative
InterpretabilityWeights (linear kernel only)Shows the actual neighbours

Where it is used

Interview questions

Common mistakes

Related topics

Linear and logistic regression · Overfitting, bias-variance and regularisation · Dimensionality reduction and PCA · Model evaluation metrics · Clustering: k-means and hierarchical · Anomaly detection

Open in the Knowledge reader →Find jobs →