TExcelTAD
Home › Machine Learning › Support Vector Machines

Support Vector Machines

A support vector machine (SVM) is a classifier with a clear geometric idea: separate the classes with the boundary that has the widest possible margin — the widest "street" between the two groups of points. The points that sit on the edges of the street are the support vectors; they alone determine where the boundary goes.

Why the widest street? A boundary that passes very close to some training points is fragile: a new point slightly off from those would land on the wrong side. A wide margin leaves room for error.

A linear SVM

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.svm import SVC

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

# evaluate the decision function on a grid to draw the boundary and margins
xx, yy = np.meshgrid(np.linspace(X[:, 0].min() - 1, X[:, 0].max() + 1, 200),
                     np.linspace(X[:, 1].min() - 1, X[:, 1].max() + 1, 200))
zz = model.decision_function(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)

plt.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", s=30)
plt.contour(xx, yy, zz, levels=[-1, 0, 1], colors="k", linestyles=["--", "-", "--"])
sv = model.support_vectors_
plt.scatter(sv[:, 0], sv[:, 1], s=120, facecolors="none", edgecolors="k")
plt.show()
print("support vectors:", len(sv), "of", len(X), "points")
print("weights:", model.coef_.round(3), " intercept:", model.intercept_.round(3))
support vectors: 3 of 40 points
weights: [[-0.254 -0.838]]  intercept: [-3.211]

The solid line is the boundary, the dashed lines are the edges of the margin, and the circled points are the support vectors. Delete any other point and the boundary wouldn't move at all.

The C parameter: hard vs soft margin

Real data overlaps, so a perfect street rarely exists. C controls how much the SVM is penalised for points inside the margin or on the wrong side:

  • Large C: violations are expensive → narrow margin, fits training data tightly (risk of overfitting).
  • Small C: violations are cheap → wide margin, more tolerant (risk of underfitting).
python · try it yourself
from sklearn.datasets import make_blobs
from sklearn.svm import SVC

X, y = make_blobs(n_samples=200, centers=2, cluster_std=2.2, random_state=3)
for C in [0.01, 0.1, 1, 100]:
    model = SVC(kernel="linear", C=C).fit(X, y)
    print(f"C={C:<5} support vectors={len(model.support_):3}  train accuracy={model.score(X, y):.3f}")
C=0.01  support vectors= 72  train accuracy=0.920
C=0.1   support vectors= 49  train accuracy=0.930
C=1     support vectors= 45  train accuracy=0.925
C=100   support vectors= 45  train accuracy=0.925

With small C, many points sit inside the wide margin and all become support vectors.

Kernels: curved boundaries

When classes can't be separated by a straight line, SVMs use the kernel trick: they behave as if the data were mapped into a higher-dimensional space where a straight separator exists — without ever computing that mapping explicitly. The most popular kernel is the RBF (radial basis function) kernel.

make_moons creates two interleaving half-circles, impossible to split with a line:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

X, y = make_moons(n_samples=300, noise=0.2, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)

xx, yy = np.meshgrid(np.linspace(-1.5, 2.5, 200), np.linspace(-1, 1.5, 200))
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, kernel in zip(axes, ["linear", "rbf"]):
    model = SVC(kernel=kernel, C=1.0).fit(X_tr, y_tr)
    zz = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
    ax.contourf(xx, yy, zz, alpha=0.3, cmap="coolwarm")
    ax.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", s=10)
    ax.set_title(f"{kernel} kernel")
    print(f"{kernel:6} test accuracy: {model.score(X_te, y_te):.3f}")
plt.show()
linear test accuracy: 0.867
rbf    test accuracy: 1.000

Tuning C and gamma

The RBF kernel adds a second knob, gamma: how far the influence of a single training point reaches. Large gamma = very local influence = wiggly boundaries (overfitting); small gamma = smooth boundaries. Tune C and gamma together, and always scale features first — SVMs are distance-based:

python · try it yourself
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)

pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
grid = {"svc__C": [0.1, 1, 10], "svc__gamma": [0.001, 0.01, 0.1]}
search = GridSearchCV(pipe, grid, cv=5).fit(X_tr, y_tr)

print("best:", search.best_params_)
print("CV accuracy:  ", round(search.best_score_, 3))
print("test accuracy:", round(search.score(X_te, y_te), 3))

unscaled = SVC(kernel="rbf").fit(X_tr, y_tr)
print("without scaling, test accuracy:", round(unscaled.score(X_te, y_te), 3))
best: {'svc__C': 10, 'svc__gamma': 0.01}
CV accuracy:   0.981
test accuracy: 0.972
without scaling, test accuracy: 0.916

Pros and cons

Strengths Weaknesses
Very accurate on small and medium data sets Training slows down a lot beyond ~50 000 rows
Works well with many features (e.g. text) Needs feature scaling and tuning of C/gamma
Kernels give flexible boundaries No natural probabilities (probability=True adds a slow calibration step)

SVR is the regression version; LinearSVC is a faster implementation for the linear kernel on large data.

Go further: Kernel SVMs: RBF, C and gamma rebuilds the kernel decision function by hand and tunes C and gamma together.

Test yourself

What are support vectors?

  1. All training points
  2. The training points on or inside the margin that define the boundary
  3. The model's coefficients
  4. Outliers that are removed

What does a very large C do in an SVM?

  1. Widens the margin and tolerates many errors
  2. Makes margin violations expensive, giving a narrow margin that fits training data tightly
  3. Switches to the RBF kernel
  4. Removes the need for scaling

Which kernel lets an SVM separate the two half-moons of make_moons?

  1. linear
  2. rbf
  3. No kernel can
  4. Only a decision tree can