Skip to content

Support vector machines

Find the widest margin, let a kernel bend it, and let cost and gamma set the balance. Strong on small and medium tables with clear structure.

Advanced ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Describe the margin and what support vectors are
  • Explain how a kernel lets a linear method draw curves
  • Set cost and gamma with the bias–variance trade in mind

Read first

01

The widest street

Read

Among all lines that separate two classes, a support vector machineSupport vector machineFinds the widest margin between classes, shaped only by rows on or inside it. takes the one with the widest margin: the street between the classes.

Only the rows on or inside the street shape it. These are the support vectors. Move any other row a little and the answer doesn't change.

Real classes overlap, so Cost (C) sets the price of a row on the wrong side. High cost hugs the training rows. Low cost tolerates mistakes and keeps a wider street.

02

Bending without new columns

Read

A kernelKernelA similarity between rows that lets a linear method draw curves without building new columns. measures similarity between two rows, and the optimization only ever needs those similarities. That lets a linear method work as if in a much richer feature space, without ever building it.

The RBF kernel is the usual choice:

k(x,x′)=exp⁡(−γ∥x−x′∥2)k(x, x') = \exp\big(-\gamma \lVert x - x' \rVert^2\big)

γ\gamma is Kernel width (gamma): large values make similarity very local.

03

Bias and variance again

Predict

Predict first

You raise γ\gamma a lot on noisy data. What happens to the boundary?

Smooth and nearly linearA wiggly boundary around single rowsNo change to the boundary
Reveal

Wiggly, around single rows. With a huge γ\gamma, each row is similar only to itself, so training accuracy approaches perfect and new-data accuracy falls. Low γ\gamma and low cost both push towards smoothness. So tune them together, on a log scale.

04

Draw it

Explore

For this model, Flexibility is γ×2\gamma \times 2. Move it from low to high, and raise Noise SD. Then compare with Logistic regression on Ring around a core.

DExplorable · Decision boundary zoo

What shapes of boundary can each kind of model draw?

Which model will score highest on new data from this shape?

How sure?

Data

Model

3

k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.

0.20
150
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Find the check that asks for a near-perfect training score with a clear drop on new data.

05

Does the kernel pay?

Predict

Predict first

Pima, cross-validated AUC. One SVM uses an RBF kernel on five features. Another uses a linear kernel on three, with balanced class weights. Which do you expect to score higher?

The RBF kernel on five featuresThe linear kernel on three featuresThey tie exactly
Reveal

The linear kernel: 0.847 against 0.833. A kernel doesn't always pay, and these effects are close to additive. On penguins an RBF kernel has a log loss of 0.0561, and a degree-2 polynomial on two bill measurements 0.121. On ozone, ε-regression with a large cost has an RMSE of 20.7.

06

Scale, cost and probabilities

Read
  • Scale: distance drives the kernel, so inputs are standardized.
  • Size: training time grows quickly with rows. Above tens of thousands of rows, prefer boosting or a linear model.
  • Probabilities: an SVM produces a margin, not a probability. The app fits Platt scaling on out-of-fold decision values, with 5 internal folds from the shared random stream.
07

Check your understanding

Checkpoint

Check yourself

Which rows determine a fitted SVM?

Show the answer

Answer: b

Rows well outside the margin have zero influence. A very large share of support vectors is a sign that the classes overlap heavily, or the cost is low.

Check yourself

You raise Cost (C) a long way. What's the effect?

Show the answer

Answer: a

CC is roughly the inverse of a penalty: raising it reduces regularization.

Check yourself

How does the app get class probabilities out of an SVM?

Show the answer

Answer: b

The decision value isn't a probability, so it needs calibrating. LIBSVM's pairwise coupling handles more than two classes.

08

Fit one

In the app

In the Learners step, select Support vector machine. Kernel offers rbf, linear, poly and sigmoid. Leave Kernel width (gamma) empty to use the default, and search Cost (C) and gamma together with Tune….

Python
import pandas as pd
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

df = pd.read_csv("pima.csv")
X, y = df[["glu", "bmi", "age", "ped", "npreg"]], df["diabetic"]
grid = {"svc__C": [0.1, 1, 10], "svc__gamma": [0.01, 0.1, 1]}
search = GridSearchCV(make_pipeline(StandardScaler(), SVC()), grid, scoring="roc_auc",
                      cv=StratifiedKFold(5, shuffle=True, random_state=1)).fit(X, y)
print(search.best_params_, round(search.best_score_, 3))
R
library(e1071)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
cv_auc <- function(C, g) mean(sapply(1:5, function(k) {
  fit <- svm(type ~ glu + bmi + age + ped + npreg, df[fold != k, ], cost = C, gamma = g)
  d <- attr(predict(fit, df[fold == k, ], decision.values = TRUE), "decision.values")
  as.numeric(pROC::auc(df$type[fold == k], as.vector(d), quiet = TRUE))
}))
grid <- expand.grid(C = c(0.1, 1, 10), g = c(0.01, 0.1, 1))
grid$auc <- mapply(cv_auc, grid$C, grid$g)
grid[which.max(grid$auc), ]
09

Recap

Recap
  • An SVM finds the widest margin, and only support vectors shape it.
  • A kernel lets it draw curves, and cost and gamma set the bias–variance trade.
  • Standardize, tune on log scales, and calibrate for probabilities.

Concepts in this lesson