Module 10 · Intermediate · Support vector machines (SVM)

Support vector machines (SVM) explained

Support vector machines explained for beginners: maximum margin, support vectors, the C parameter, kernels for curved boundaries, and SVM in scikit-learn.

By theprogrammers team · · 10 min read

Draw a line to separate two groups of points, and usually many lines would work. Which is best? A support vector machine (SVM) answers: the line that leaves the widest possible gap, or margin, between the groups. A wide margin means the boundary isn't squeezed against either group, so new points are less likely to land on the wrong side.

With a trick called the kernel, SVMs can also draw curved boundaries. Before deep learning took over, SVMs were among the most accurate classifiers available, and they remain excellent for small and medium datasets with many features, such as text or genetic data. This lesson explains margins, support vectors, the C setting, kernels, the maths behind them, and how to use SVMs in scikit-learn.

What you need first: logistic regression, feature scaling and the dot product explained.

Key terms

  • Decision boundary: the line (or flat plane, in more dimensions) where the SVM switches from one class to the other.
  • Margin: the empty street on either side of the boundary. The SVM makes it as wide as possible.
  • Support vectors: the training points on the edge of the margin or inside it. They alone decide the boundary.
  • C: how much the SVM is charged for each point inside the margin or on the wrong side.
  • Kernel: a similarity function that lets an SVM draw curved boundaries, as if the data had extra features.

The maximum margin idea

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.svm import SVC
from sklearn.inspection import DecisionBoundaryDisplay

X, y = make_blobs(n_samples=40, centers=2, cluster_std=1.0, random_state=6)
svm = SVC(kernel="linear", C=1000).fit(X, y)

fig, ax = plt.subplots()
ax.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", s=30, edgecolor="k")
DecisionBoundaryDisplay.from_estimator(
    svm, X, ax=ax, plot_method="contour", response_method="decision_function",
    levels=[-1, 0, 1], linestyles=["--", "-", "--"], colors="k")
ax.scatter(*svm.support_vectors_.T, s=150, facecolors="none", edgecolors="k")
ax.set_title("The widest gap between two classes")
plt.show()
print("Support vectors:", len(svm.support_vectors_))
Two groups of points, red and blue, separated by a solid black line, with two dashed parallel lines on either side marking the margin; three points touching the dashed lines are circled as support vectors.
Support vectors: 3
  • The solid line is the decision boundary.
  • The dashed lines mark the edges of the margin. The SVM makes the gap between them as wide as possible.
  • The circled points are the support vectors: the training points touching the margin. Only they decide where the boundary goes. Move any other point (without crossing the margin), and the boundary doesn't change.

That's where the name comes from: the boundary is "supported" by a few critical points. make_blobs just generates example clusters of points.

Soft margins and C

Real data overlaps, so a perfect separating line usually doesn't exist. A soft margin allows some points inside the margin, or even on the wrong side, at a cost. The C parameter sets that cost:

CBehaviourRisk
Small (0.01)Wide margin, tolerates many mistakesUnderfitting
Large (100+)Narrow margin, tries hard to classify every training pointOverfitting
X, y = make_blobs(n_samples=100, centers=2, cluster_std=2.2, random_state=4)

fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
for ax, C in zip(axes, [0.01, 100]):
    model = SVC(kernel="linear", C=C).fit(X, y)
    ax.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", s=25, edgecolor="k")
    DecisionBoundaryDisplay.from_estimator(
        model, X, ax=ax, plot_method="contour", response_method="decision_function",
        levels=[-1, 0, 1], linestyles=["--", "-", "--"], colors="k")
    ax.set_title(f"C = {C}: {len(model.support_vectors_)} support vectors")
plt.show()
Two charts of the same overlapping red and blue points: with C = 0.01 the dashed margin lines are far apart and many points fall inside them; with C = 100 the margin is much narrower and fewer points are inside it.

Small C gives a wide, tolerant margin with many support vectors. Large C gives a narrow margin that bends to individual points. Choose C with cross-validation.

Kernels: curved boundaries

Some data can't be separated by any straight line, like one class forming a ring around the other:

from sklearn.datasets import make_circles

X, y = make_circles(n_samples=200, factor=0.4, noise=0.1, random_state=0)
linear = SVC(kernel="linear").fit(X, y)
rbf = SVC(kernel="rbf").fit(X, y)
print("Linear kernel:", linear.score(X, y))
print("RBF kernel:   ", rbf.score(X, y))
Linear kernel: 0.625
RBF kernel:    1.0

A straight line gets only 62.5%, barely better than guessing, while the RBF kernel classifies every point correctly. The kernel trick solves this: it implicitly maps the data into a higher-dimensional space where a straight boundary (a flat plane) does separate the classes, without ever computing that space directly. In the original space, the boundary looks curved:

fig, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(rbf, X, ax=ax, alpha=0.3, cmap="coolwarm")
ax.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", s=20, edgecolor="k")
ax.set_title("RBF kernel: a circular boundary")
plt.show()
Red points forming an outer ring and blue points in the centre, with the shaded blue region forming a rough circle around the inner points, separating them from the ring.

Imagine adding a third feature, the distance from the centre. Inner points would sit low and outer points high, and a flat sheet could slice between them. That's the intuition behind kernels.

KernelBoundaryUse when
"linear"Straight line or flat planeMany features (like text), or the data is roughly linearly separable
"rbf" (default)Flexible, curvedGeneral purpose; a good default for numeric data
"poly"Polynomial curvesOccasionally; usually RBF works as well

The RBF kernel has a second setting, gamma: how far each training point's influence reaches. Large gamma gives very wiggly boundaries (overfitting), small gamma smooth ones. Tune C and gamma together.

The maths behind an SVM

You can use an SVM without the maths, but four short ideas explain everything above. Each has its own lesson if you want to go deeper:

IdeaEquationIn wordsLearn it in
Predictionsign(w · x + b)The side of the boundary the point is onThe dot product explained
Margin width2 ÷ ‖w‖A smaller weight vector means a wider streetVector projection explained
Training (soft margin)minimise ½‖w‖² + C × Σ max(0, 1 − yᵢ(w · xᵢ + b))A wide street, plus a hinge loss for every point inside it or on the wrong sideLoss functions explained
Support vectorsw = Σ αᵢ yᵢ xᵢ, with αᵢ = 0 for points beyond the marginOnly points on or inside the margin shape the boundaryLagrange multipliers explained

The labels yᵢ are +1 and −1. The training objective is the same shape as regularisation: a penalty on the size of the weights plus an error term, with C setting the balance. The kernel trick works because, written with the Lagrange multipliers αᵢ, the SVM only ever needs dot products between pairs of points, and a kernel replaces those dot products. SVM from scratch in Python builds the whole thing with NumPy and checks it against scikit-learn.

SVM on real data

SVMs need scaled features, because the margin is measured in distances. Here's an SVM spam filter on the Spambase data: 4,601 emails described by 57 word and character frequencies.

Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("spambase.csv").

from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = fetch_openml(data_id=44, as_frame=True, return_X_y=True)   # Spambase
y = y.astype(int)                                                  # 1 = spam, 0 = not spam
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)

pipe = make_pipeline(StandardScaler(), SVC())
search = GridSearchCV(pipe, {"svc__C": [0.1, 1, 10, 100],
                             "svc__gamma": ["scale", 0.01, 0.1]}, cv=5)
search.fit(X_train, y_train)
print(search.best_params_)
print("Test accuracy:", round(search.score(X_test, y_test), 3))
{'svc__C': 10, 'svc__gamma': 'scale'}
Test accuracy: 0.921

92.1% test accuracy after tuning C and gamma with a grid search inside a pipeline. On this data that's no better than plain logistic regression, which scores 92.9% on the same split, and a random forest does better still. SVMs shine on smaller datasets with clean numeric features; always compare them with a simpler baseline.

Probabilities

By default, SVC gives classes but not probabilities. decision_function gives a signed distance from the boundary, which is fine for ROC curves. If you need probabilities, use SVC(probability=True), which adds an internal calibration step and slows training.

Strengths and weaknesses

StrengthsWeaknesses
Very accurate on small and medium datasetsTraining gets slow beyond tens of thousands of rows
Works well with many features, even more features than rowsNeeds scaling and tuning of C (and gamma)
Kernels give flexible boundariesNo probabilities by default; harder to explain
Depends only on support vectors, so it's fairly robustLess suited to very noisy, heavily overlapping classes

For large datasets, LinearSVC (a fast linear-only version) or tree ensembles such as random forests are usually more practical.

When to use an SVM

Your data and problemUse an SVM?Instead, or as well
Classification, hundreds to tens of thousands of rows, numeric featuresYes: RBF kernel, tune C and gammaCompare with a random forest or gradient boosting
Many features, even more than rows (text, genes)Yes: linear kernel or LinearSVCLogistic regression
Small images, such as 8 × 8 digitsYes, a strong baselineKNN; convolutional neural networks for larger images
Millions of rowsOnly LinearSVC or SGDClassifierGradient boosting, logistic regression
You need probabilities or explanationsNot idealLogistic regression, trees
Mostly categorical or tabular business data with mixed typesRarely the bestGradient boosting
Predicting a numberSVR exists, but it's rarely the first choiceLinear regression, gradient boosting

Practice

  1. What happens to the number of support vectors as C gets smaller? Why?
Show the answer

It grows. A small C allows a wider margin with more points inside it, and every point on or inside the margin is a support vector.

  1. Fit SVC(kernel="rbf", gamma=100) on the circles data. Compare training accuracy and what you'd expect on new data.
Show the answer

Training accuracy is about perfect, because each point gets its own tiny region. On new data it would do worse: very large gamma overfits.

  1. Your SVM takes hours to train on 2 million rows. What could you do?
Show the answer

Use LinearSVC or SGDClassifier (fast linear models), train on a sample, or switch to a tree ensemble such as gradient boosting, which scales better.

Interview questions

What is a support vector machine?

A classifier that finds the boundary maximising the margin between classes. The training points closest to the boundary, the support vectors, determine it. Soft margins allow some errors, controlled by C.

What is the kernel trick?

A way to compute similarities as if the data had been mapped into a higher-dimensional space, without computing that mapping. It lets a linear separator in that space produce non-linear boundaries in the original space. RBF and polynomial kernels are common.

What do C and gamma control in an RBF SVM?

C is the penalty for misclassifying training points: large C means a narrow margin and risk of overfitting. Gamma controls how far a single point's influence reaches: large gamma means very local, wiggly boundaries.

Key takeaways

  • An SVM chooses the boundary with the widest margin; only the support vectors decide where it goes.
  • C trades margin width against mistakes: small C is tolerant and simple, large C is strict and can overfit.
  • Kernels, usually RBF, give curved boundaries; gamma controls how wiggly they are. Tune C and gamma together with cross-validation.
  • Always scale the features, and put the scaler and SVM in one pipeline.
  • SVMs are excellent on small and medium datasets with many numeric features, but slow on millions of rows.

Frequently asked questions

Is an SVM better than logistic regression?

Not in general. On linearly separable or text data they're often equally accurate. An RBF SVM can beat logistic regression when the boundary is curved, but logistic regression gives probabilities, trains faster and is easier to explain. Try both with cross-validation.

Can an SVM handle more than two classes?

Yes. scikit-learn's SVC trains one SVM for every pair of classes (one-vs-one) and lets them vote; LinearSVC trains one per class (one-vs-rest). You just pass labels with several classes.

Can SVMs be used for regression?

Yes, as support vector regression (SVR). It fits a tube of width epsilon around the data and ignores errors smaller than that. It's useful on small datasets but rarely the first choice for tabular data.

What to learn next

  1. Build one yourself in SVM from scratch in Python, the next lesson in this module.
  2. Put it to work in handwritten digit recognition with SVM.
  3. Learn the most explainable classifier in decision trees explained.