Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 88/ 160
05. Classical Machine Learning

Support Vector Machines (SVM) & Kernels

Separate classes with margins and kernel tricks for non-linear decision boundaries.

AdvancedMargin · Support Vectors3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

An SVM draws the line between two groups so that it stays as far as possible from the closest points of both, and a kernel lets that line curve when the groups aren't separable by a straight line.

Think of it like…

Laying the widest possible road between two neighbourhoods: only the houses right at the edge of the road (support vectors) decide where it goes, and a kernel lets you bend the road around curves by looking at the map from a higher dimension.

Where you’ve seen it

Take w = (3, 4) and b = −10. The norm is ‖w‖ = 5, so the margin width is 2 / ‖w‖ = 0.4. A point at (4, 2) has w·x + b = 12 + 8 − 10 = 10, so it lies 10 / 5 = 2.0 units from the boundary (a functional margin of 10, far outside the margin). Support vectors satisfy |w·x + b| = 1. For data that forms concentric rings, a linear SVM scores near chance, but an RBF kernel with γ = 0.5 separates them: two points at squared distance 2 have similarity exp(−0.5 × 2) = 0.368, while with γ = 5 the similarity drops to exp(−10) = 0.00005, so the model becomes extremely local and overfits. A grid search over C = 2⁻⁵ to 2¹⁵ and γ = 2⁻¹⁵ to 2³ with 5-fold CV on standardised features finds C = 8 and γ = 0.125, giving 94% accuracy on 8,000 rows with 1,350 support vectors (17% of the data); prediction cost scales with that count.

Words you’ll hear

Margin
The distance between the boundary and the nearest points; the SVM maximises it.
Support vectors
Training points on or inside the margin that define the boundary.
C
Penalty on margin violations: larger C fits training data harder.
Kernel / γ
A similarity function replacing dot products; γ sets how local the RBF kernel is.

Visual diagram

Loading interactive diagram

Theory & deep dive

Margins, hinge loss and the soft margin

For labels y ∈ {−1, +1} and a linear function f(x) = w·x + b, the hard-margin SVM requires y f(x) ≥ 1 for all points and minimises ½‖w‖², which maximises the margin 2/‖w‖. Real data is rarely separable, so the soft-margin objective minimises ½‖w‖² + C Σ max(0, 1 − yᵢ f(xᵢ)): the hinge loss is zero for points outside the margin and grows linearly for violations. The solution depends only on the support vectors, points with yᵢ f(xᵢ) ≤ 1; points far from the boundary can be removed without changing the model. C is the knob: large C punishes violations heavily and can overfit noisy data; small C accepts more errors for a simpler, wider-margin boundary.

Because the margin is measured in feature space distance, feature scaling is essential: standardise inputs inside a pipeline. SVMs don't output probabilities natively; scikit-learn's probability=True fits Platt scaling by internal cross-validation (slow), or you can calibrate separately with CalibratedClassifierCV. For large sparse data (text with 100,000 features), LinearSVC or SGD with hinge loss trains fast and often matches kernel SVMs. For regression, support vector regression (SVR) uses an ε-insensitive loss that ignores errors smaller than ε.

Geometry of a boundary

w = (3, 4), b = −10, ‖w‖ = 5. Margin width = 2/5 = 0.4. Point (4, 2): f = 3×4 + 4×2 − 10 = 10, distance = 10/5 = 2.0, so its functional margin is 10 and it's not a support vector (support vectors have |f| = 1, a distance of 0.2 from the boundary).

Key takeaway: SVMs maximise the margin with a hinge-loss soft margin controlled by C; only support vectors matter, and scaling is mandatory.

Kernels, tuning and practical limits

The kernel trick exploits that the SVM's dual formulation uses only dot products between points; replacing x·z with K(x, z) fits the margin in an implicit high-dimensional space. Common kernels: linear (K = x·z), polynomial (K = (γ x·z + r)^d; for d = 2, r = 1, x = (1, 2), z = (3, 1): (5 + 1)² = 36, which equals the dot product of explicit degree-2 feature maps, so no features need to be built) and RBF (K = exp(−γ‖x − z‖²)), the usual default. In RBF, γ sets locality: small γ gives smooth, nearly linear boundaries (high bias), large γ gives islands around individual points (high variance). C and γ interact, so tune them together on a log-spaced grid with cross-validation (C from 2⁻⁵ to 2¹⁵, γ from 2⁻¹⁵ to 2³ is a classic recipe) after standardising features.

Limits: kernel SVM training is roughly O(n²) to O(n³) in the number of samples and memory for the kernel matrix grows as n², so it is practical up to tens of thousands of rows, not millions; prediction cost grows with the number of support vectors (1,350 of 8,000 in the example); there are no native probabilities; and interpretability is limited for nonlinear kernels. Compared with gradient-boosted trees, SVMs are less competitive on heterogeneous tabular data, but they do well on high-dimensional, small-sample problems (text, genomics), with clean scaled features, and when you want a convex optimisation with a global optimum. Alternatives for big data: linear SVMs, kernel approximation (Nystroem, random Fourier features) followed by a linear model, or neural networks.

RBF similarity

Two points at squared distance 2. γ = 0.5: K = exp(−1) = 0.368 (moderately similar). γ = 5: K = exp(−10) ≈ 0.00005 (essentially unrelated), so each point influences only its immediate neighbourhood and the boundary hugs the training data.

Key takeaway: RBF kernels bend the boundary; tune C and γ jointly on a log grid, and mind the cost for large n.

How it works, step by step

Step 1 of 4
Analyst

1. Standardise features

Scale inside a pipeline so margins and RBF distances are meaningful.

StandardScaler + SVC
Key numbers at this step
Fit scaler
on train only

When to use it & trade-offs

What it is

A support vector machine (SVM) finds the decision boundary that maximises the margin, the gap between the boundary and the closest training points of each class. Those closest points are the support vectors; only they determine the boundary. A soft margin allows some violations at a cost controlled by C (large C: few violations, narrow margin, higher variance; small C: wider margin, more tolerance). The kernel trick replaces dot products with a kernel function K(x, z) so the SVM can fit nonlinear boundaries (for example the RBF kernel exp(−γ‖x − z‖²)) without explicitly computing high-dimensional features.

Why it matters: SVMs were the state of the art on small to medium, high-dimensional problems (text, images before deep learning, bioinformatics), and their ideas (margins, hinge loss, kernels, convex optimisation) recur throughout ML. They remain a strong choice on smaller datasets with clean features, and they are a classic test of whether you understand regularisation (C), scaling and model capacity (γ).

When to reach for it

  • Text classification with linear SVMs
  • Small-sample, high-dimensional problems
  • Problems with clear margins between classes

When to avoid or be careful

  • Unscaled features
  • Kernel SVMs on millions of rows
  • Tuning C without tuning γ

SVM kernels and alternatives

Linear SVM
Best for: High-dimensional sparse data such as text

Strengths: Fast; scales to large data; good baseline.

Watch out: Linear boundary only.

RBF-kernel SVM
Best for: Small to medium data with nonlinear boundaries

Strengths: Flexible; strong with clean scaled features.

Watch out: Slow for big n; two hyperparameters.

Gradient-boosted trees
Best for: Heterogeneous tabular data

Strengths: Handles mixed types and missing values.

Watch out: Different tuning; less margin-based intuition.

Interview signals & numbers to know

When this topic comes up

  • “Maximum margin classifier”
  • “Kernel trick”
  • Support vectors
  • C and gamma tuning
  • Hinge loss

Benchmarks & rules of thumb

2 / ‖w‖ -
margin width
O(n²) – O(n³) -
kernel SVM training cost
(5 + 1)² = 36 -
degree-2 polynomial kernel in the worked example

Common mistakes & follow-ups

Common interview mistakes

  • Tuning γ on unscaled features, where distances are meaningless.
  • Using a very large C and overfitting noisy labels.
  • Treating decision-function values as calibrated probabilities.

Likely interviewer follow-ups

  • What is the kernel trick?
  • How do C and gamma affect the decision boundary?
  • When would you choose an SVM over gradient boosting?
Interview tip: State the geometry (margin = 2/‖w‖, only support vectors matter) and the C and γ effects. It shows you understand why SVMs behave as they do.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Support Vector Machines (SVM) & Kernels with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
K-Nearest Neighbors (KNN)
Next topic
Naive Bayes Classifiers