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.
What runs in CodeSplash
- Support vector machine Verified in Python and R
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
The widest street
ReadAmong 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.
Bending without new columns
ReadA 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:
is Kernel width (gamma): large values make similarity very local.
Bias and variance again
PredictPredict first
You raise a lot on noisy data. What happens to the boundary?
Reveal
Wiggly, around single rows. With a huge , each row is similar only to itself, so training accuracy approaches perfect and new-data accuracy falls. Low and low cost both push towards smoothness. So tune them together, on a log scale.
Draw it
ExploreFor this model, Flexibility is . 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?
Data
Model
k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.
Commit your prediction above to see the result
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.
Does the kernel pay?
PredictPredict 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?
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.
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.
Check your understanding
CheckpointCheck 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
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.
Fit one
In the appIn 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….
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))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), ]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