AI
Support Vector Machine (SVM): A Plain Explanation
Support vector machine explained: margins, support vectors, the kernel trick, C and gamma, a worked example, scikit-learn code and when to use one.
A support vector machine (SVM) is a supervised machine learning model that classifies data by finding the boundary that separates two classes with the widest possible gap. Picture red and blue points on a page: many lines could split them, but an SVM picks the one that stays as far as possible from the nearest points of each colour. Those nearest points, the ones that pin the boundary in place, are the support vectors.
SVMs were among the most successful machine learning methods before deep learning took over, and they're still a strong choice for small and medium datasets, high-dimensional data such as text, and problems where you want a well-understood model that trains in seconds. With a kernel, the same idea handles curved boundaries too. This guide explains what an SVM is, how the margin and kernels work with worked numbers, what the C and gamma settings do, how to train one in scikit-learn, and how SVMs compare with logistic regression and neural networks.
Support Vector Machine at a Glance
| Item | Detail |
|---|---|
| Type | Supervised learning: classification (SVC) and regression (SVR) |
| Core idea | Choose the separating boundary with the maximum margin |
| Key points | Support vectors: the training examples closest to the boundary |
| Non-linear data | Handled with kernels (RBF, polynomial, sigmoid) |
| Main settings | C (how much to penalise mistakes), kernel, gamma (for RBF) |
| Loss function | Hinge loss plus a margin term |
| Strengths | Works well in high dimensions; effective on small datasets; few settings |
| Weaknesses | Slow on very large datasets; needs feature scaling; no native probabilities |
| History | Kernel method by Boser, Guyon and Vapnik (1992); soft margin by Cortes and Vapnik (1995) |
What Is SVM?
What is SVM in one sentence? It's a classifier that draws the widest street between two classes and puts the dividing line down the middle.
In two dimensions the boundary is a line; in three, a plane; in more, a hyperplane. Mathematically, the SVM learns a weight vector w and a bias b, and classifies a point x by the sign of:
f(x) = w · x + b
Positive means one class, negative the other. The "street" is the region where f(x) is between −1 and +1, and its width is 2 ÷ ‖w‖. Making ‖w‖ small makes the street wide. Training therefore looks for the smallest w that still puts every training point on the correct side of the street.
Only the points on the edge of the street matter. Move any other point around, as long as it stays outside the street, and the boundary doesn't change. That's why the model is named after the support vectors, and why it often generalises well: it depends on a handful of critical examples rather than every data point.
Support Vector Machine: A Worked Example
This support vector machine example uses four training points in two dimensions:
| Point | x₁ | x₂ | Class |
|---|---|---|---|
| A | 2 | 2 | +1 |
| B | 3 | 2 | +1 |
| C | 1 | 1 | −1 |
| D | 0 | 1 | −1 |
A maximum-margin solution is w = (1, 1) and b = −3, so f(x) = x₁ + x₂ − 3.
| Point | f(x) | Side | On the margin? |
|---|---|---|---|
| A | 2 + 2 − 3 = 1 | +1 | Yes: support vector |
| B | 3 + 2 − 3 = 2 | +1 | No |
| C | 1 + 1 − 3 = −1 | −1 | Yes: support vector |
| D | 0 + 1 − 3 = −2 | −1 | No |
The street width is 2 ÷ ‖(1, 1)‖ = 2 ÷ √2 ≈ 1.41, which is exactly the distance between A and C, the two closest opposite points. A new point at (2.5, 1) gives f = 0.5, so it's classified +1, but because it's inside the street, the model is less confident about it.
Soft Margins and the C Parameter
Real data is rarely perfectly separable. A few points sit on the wrong side, or deep inside the street. The soft-margin SVM, introduced by Corinna Cortes and Vladimir Vapnik in 1995, allows some violations but charges for them using the hinge loss:
hinge loss = max(0, 1 − y · f(x))
A point correctly outside the street costs nothing. A point inside the street or on the wrong side costs more the further it strays. Training balances two goals, a wide street and few violations, controlled by C:
| C value | Behaviour | Risk |
|---|---|---|
| Small (for example 0.01) | Wide street; tolerates many violations | Underfitting: too simple |
| Medium (for example 1) | Balanced; the usual default | |
| Large (for example 1000) | Narrow street; tries to classify every training point correctly | Overfitting to noise and outliers |
C plays the same role as regularisation strength in other models, only inverted: larger C means less regularisation. Our guide to regularization in machine learning explains the general idea, and our explainer on the loss function covers hinge loss alongside other losses.
The SVM Kernel Trick
An SVM kernel lets the model draw curved boundaries without changing the core algorithm. The idea: map the data into a higher-dimensional space where a straight boundary works, then solve the usual SVM there.
Example: one-dimensional data where class +1 sits at x = −3 and x = 3, and class −1 at x = −1, 0 and 1. No single cut on the number line separates them. Now add a second feature, x². The +1 points have x² = 9; the −1 points have x² of 0 or 1. In the new space, the line x² = 2.5 separates them perfectly.
The "trick" is that SVM training only ever needs dot products between pairs of points. A kernel function computes the dot product in the high-dimensional space directly from the original data, without ever building the new features. Bernhard Boser, Isabelle Guyon and Vladimir Vapnik proposed applying this to maximum-margin classifiers in 1992.
| Kernel | Formula idea | Good for |
|---|---|---|
| Linear | x · x′ | Text, high-dimensional sparse data, very large datasets |
| Polynomial | (x · x′ + c)ᵈ | Interactions between features up to degree d |
| RBF (Gaussian) | exp(−γ ‖x − x′‖²) | General-purpose curved boundaries; the common default |
| Sigmoid | tanh(α x · x′ + c) | Rarely the best choice in practice |
Gamma for the RBF kernel
With the RBF kernel, gamma sets how far each training point's influence reaches:
- Low gamma: each point influences a wide area, giving smooth, simple boundaries (risk of underfitting).
- High gamma: each point influences only its close neighbourhood, giving wiggly boundaries that can wrap around individual points (risk of overfitting).
C and gamma interact, so tune them together, usually with a grid search over powers of ten.
SVM in Machine Learning Practice
Using SVM in machine learning projects comes down to three habits: scale the features, tune C and gamma, and pick the right implementation for the data size. In scikit-learn:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
model = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
grid = {"svc__C": [0.1, 1, 10, 100], "svc__gamma": ["scale", 0.01, 0.1, 1]}
search = GridSearchCV(model, grid, cv=5)
search.fit(X_train, y_train)
print(search.best_params_, search.score(X_test, y_test))Practical notes:
- Always scale features. SVMs measure distances, so a feature measured in thousands swamps one measured in fractions. Putting the scaler in a pipeline avoids leaking test data into scaling.
- Mind the dataset size. scikit-learn's documentation notes that the solver behind
SVCscales between quadratically and cubically with the number of samples. For hundreds of thousands of rows, useLinearSVCorSGDClassifierwith hinge loss instead. - Probabilities need extra work. SVMs output a distance from the boundary, not a probability.
SVC(probability=True)adds an internal cross-validated calibration, which slows training. - Imbalanced classes: set
class_weight="balanced"so the rare class isn't ignored. - More than two classes: scikit-learn handles this automatically by training several binary classifiers.
Support Vector Regression
The same idea works for predicting numbers. Support vector regression (SVR) fits a tube of width ε around the prediction line and ignores errors inside the tube, penalising only points outside it. It suits smaller regression problems with non-linear relationships, using the same kernels.
SVM vs Logistic Regression
On SVM vs logistic regression: both draw linear boundaries by default, and both can be regularised. The difference is in what they optimise and what they output:
| SVM | Logistic regression | |
|---|---|---|
| Loss | Hinge loss: only points near or across the boundary matter | Log loss: every point contributes |
| Output | Distance from the boundary (a score) | A probability |
| Non-linear boundaries | Natural with kernels | Needs hand-made features |
| Outliers far on the correct side | Ignored | Still slightly influence the fit |
| Interpretability | Linear SVM weights are readable; kernel SVMs less so | Coefficients are readable, with odds ratios |
| Large datasets | Linear SVM scales well; kernel SVM doesn't | Scales well |
If you need calibrated probabilities, such as for risk scores, start with logistic regression. If you need a strong classifier on modest data with complex boundaries, try an RBF SVM.
SVM vs Neural Networks and Tree Models
| Situation | Usually best |
|---|---|
| A few thousand rows, many features (text, genomics) | SVM, or linear models |
| Tabular business data with mixed feature types | Gradient-boosted trees |
| Images, audio, raw text at scale | Neural networks |
| Millions of rows | Linear models, trees or neural networks; not kernel SVMs |
| Need a fast, strong baseline with little tuning | Linear SVM or logistic regression |
Neural networks learn their own features from raw data, which is why they replaced SVMs for images and language. SVMs still shine when data is limited and features are already meaningful. Our guide to supervised vs unsupervised learning places SVMs among other supervised methods.
Where Support Vector Machines Are Used
- Text classification: spam filtering, topic labelling and sentiment, where linear SVMs on word features work very well.
- Bioinformatics: classifying genes or proteins from thousands of measurements and few samples.
- Image classification on engineered features, such as handwritten digit recognition and object detection with hand-crafted descriptors, before deep learning.
- Anomaly detection with the one-class SVM variant, which learns the boundary of normal data.
- Small industrial datasets, such as quality inspection and sensor fault detection.
Common Mistakes
- Not scaling features.
- Using default C and gamma without tuning.
- Running a kernel SVM on millions of rows and waiting hours.
- Treating SVM scores as probabilities.
- Ignoring class imbalance.
FAQ
What are support vectors?
The training points that lie on the edge of the margin or violate it. They alone determine where the boundary sits.
Is SVM supervised or unsupervised?
Standard SVMs are supervised: they learn from labelled examples. The one-class SVM variant is used for unsupervised anomaly detection.
Can SVM handle more than two classes?
Yes. Libraries combine several binary SVMs, either one class versus each other class, or one versus the rest.
Is SVM still used?
Yes, especially for small and medium datasets, text classification and as a strong baseline, though deep learning dominates images, audio and language at scale.
What is the difference between SVM and SVC?
SVM is the general method; SVC (support vector classifier) is the classification version, and SVR is the regression version. In scikit-learn, SVC is the class name for kernel SVM classification.