Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 3 of 10
Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
An SVM builds the widest road between two groups, and only the houses on the edge decide it. See C squeeze the road from 4.36 to 1.46, a kernel lift a dose problem from 0.67 to 1.0, gamma overfit two moons, and a scaled SVC reach 0.972 on wine.
What you will learn
- Explain the margin and why only the support vectors decide it
- Use C to trade a wide, forgiving road against a narrow, strict one
- See the kernel trick lift data so a straight cut works, and how gamma bends an RBF boundary
- Scale, tune C and gamma with cross-validation, and use SVR for numbers
Before you start
- Feature Scaling: StandardScaler and MinMaxScaler
- Cross-Validation with StratifiedKFold
- K-Nearest Neighbours
Two villages sit side by side, and you're the town planner. Many straight lines would split them, but you want the safest one: the widest road that fits between the villages without knocking down a single house. When a new house is built, the side of the road it lands on tells you its village.
That road is what a Support Vector Machine (SVM) looks for. The road's width is called the margin. The houses that touch its edges are the support vectors. Move any other house a little and the road doesn't change. Only the houses on the edge decide it.
The widest road with SVC
Twelve houses: village A has six, village B has six. X holds each house's x and y, and y is its village.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.svm import SVC, SVR
from sklearn.datasets import load_wine, make_moons
from sklearn.inspection import DecisionBoundaryDisplay as DBD
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
villages = pd.read_csv("villages.csv")
X = villages[["x", "y"]]
y = villages["village"]
print(X.shape)
(12, 2)
SVC with a linear kernel draws a straight road. A very big C means no house is allowed on the road:
road = SVC(kernel="linear", C=1000).fit(X, y)
w = road.coef_[0]
print(road.support_vectors_)
print("road width:", round(2 / np.linalg.norm(w), 2))
[[3. 3.6]
[5. 4.5]]
road width: 2.19
villages.csv. The widest straight road touches only two houses, the support vectors. Width 2.19 is exactly the distance between them.Only two of the twelve houses decide the road. Here they face each other straight across it, so the width, 2.19, is just the distance between them.
C: what if one house is in the way?
Real data is messy. Add one extra village A house at (4.6, 3.0), right beside village B, and try two values of C:
extra = pd.DataFrame({"x": [4.6], "y": [3.0]})
X2 = pd.concat([X, extra], ignore_index=True)
y2 = pd.concat([y, pd.Series(["A"])], ignore_index=True)
for C in [0.1, 100]:
m = SVC(kernel="linear", C=C).fit(X2, y2)
width = 2 / np.linalg.norm(m.coef_[0])
print("C =", C, "width", round(width, 2))
print("support vectors", len(m.support_))
C = 0.1 width 4.36
support vectors 6
C = 100 width 1.46
support vectors 3
- Small C (0.1) forgives that house. The road stays wide, 4.36, with 6 support vectors.
- Big C (100) forgives nothing. The road squeezes to 1.46, with 3 support vectors.
Small C gives a wide, relaxed road; big C a narrow, strict one that bends to every odd point. You pick C with cross-validation.
The kernel trick: lift, then cut straight
What if no straight line can split the data at all? Imagine a medicine that only works at a medium dose: doses 4, 5 and 6 work, too little or too much doesn't.
dose = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
works = np.array([0, 0, 0, 1, 1, 1, 0, 0, 0])
D = dose.reshape(-1, 1)
flat = SVC(kernel="linear").fit(D, works)
print("straight cut:", round(flat.score(D, works), 2))
straight cut: 0.67
One cut on a line gets two thirds right at best. So add a second column: how far the dose is from the middle, squared.
lifted = np.c_[dose, (dose - 5) ** 2]
lift = SVC(kernel="linear", C=1000).fit(lifted, works)
print("after the lift:", lift.score(lifted, works))
after the lift: 1.0
That's the kernel trick. A kernel does this kind of lift for you, without building the new column by hand. The RBF kernel does it on the raw doses:
rbf = SVC(kernel="rbf").fit(D, works)
print("rbf kernel:", rbf.score(D, works))
rbf kernel: 1.0
gamma: how much the road can bend
With the RBF kernel the road can curve around the data, and gamma decides how much. Two curved moons, three values of gamma:
Xm, ym = make_moons(300, noise=0.3, random_state=42)
Xtr, Xte, ytr, yte = train_test_split(
Xm, ym, test_size=0.3, random_state=42)
fig, axes = plt.subplots(1, 3, figsize=(9, 2.3))
for ax, g in zip(axes, [0.1, 1, 50]):
m = SVC(gamma=g).fit(Xtr, ytr)
tr, te = m.score(Xtr, ytr), m.score(Xte, yte)
print(f"gamma={g:<4} train {tr:.2f} test {te:.2f}")
DBD.from_estimator(m, Xtr, ax=ax, alpha=.4)
ax.scatter(*Xtr.T, c=ytr, s=8)
ax.set_title(f"gamma={g}")
plt.show()
gamma=0.1 train 0.85 test 0.87
gamma=1 train 0.89 test 0.90
gamma=50 train 0.96 test 0.89

gamma 0.1 is too smooth. gamma 1 follows the moons nicely and scores best on test, 0.90. gamma 50 pushes train up to 0.96 but test falls to 0.89: it is memorising points, which is overfitting.
Wine: scale first, then tune C and gamma
An SVM measures distances, so, exactly like KNN, it needs scaling. Split the wine data first, then cross-validate a scaled pipeline on the train rows:
Xw, yw = load_wine(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
Xw, yw, test_size=0.2, stratify=yw, random_state=42)
for C, gamma in [(1, "scale"), (1, 1), (10, 0.01)]:
svc = make_pipeline(StandardScaler(),
SVC(C=C, gamma=gamma))
cv = cross_val_score(svc, X_train, y_train, cv=5)
print(f"C={C} gamma={gamma} CV {cv.mean():.3f}")
raw = cross_val_score(SVC(), X_train, y_train, cv=5)
print(f"no scaling CV {raw.mean():.3f}")
C=1 gamma=scale CV 0.986
C=1 gamma=1 CV 0.556
C=10 gamma=0.01 CV 0.979
no scaling CV 0.648
The defaults, C = 1 with gamma="scale", win with 0.986. gamma = 1 is far too wiggly: 0.556. And without scaling, only 0.648.
Cross-validation picked the winner, so fit it on the train rows and touch the test set once:
svc = make_pipeline(StandardScaler(), SVC())
svc.fit(X_train, y_train)
acc = svc.score(X_test, y_test)
print("test accuracy:", round(acc, 3))
n = len(svc[-1].support_)
print("support vectors:", n, "of", len(X_train))
test accuracy: 0.972
support vectors: 61 of 142
0.972 on the test wines. The model keeps 61 of the 142 training wines as support vectors; the rest don't affect the boundary at all.
SVR: a tube for numbers
An SVM can also predict numbers. Instead of a road that keeps points out, SVR fits a tube that keeps points in. Points within epsilon of the line cost nothing, and only points outside the tube push the line.
houses = pd.read_csv("houses.csv")
Xh = houses[["size_m2", "bedrooms"]]
yh = houses["price_k"]
svr = SVR(kernel="linear", C=100, epsilon=10)
model = make_pipeline(StandardScaler(), svr)
model.fit(Xh, yh)
new = pd.DataFrame([[82, 4]], columns=Xh.columns)
print(model.predict(new).round(1))
[315.8]
The 82 m², 4-bedroom house gets 315.8 thousand. Scaled KNN said 296.7: same house, another model.
Common mistakes
- No scaling. On wine, CV drops from 0.986 to 0.648.
- A huge gamma. Train goes up and test goes down: the boundary wraps around single points.
- A huge C on noisy data. The road squeezes to fit every odd point.
- Tuning C and gamma on the test set. Tune with cross-validation on the train rows, test once.
Quick recap
| Idea | What it means | In this example |
|---|---|---|
| Margin | The widest road between the classes | Width 2.19 |
| Support vectors | The points on the edge; only they decide | 2 of 12 houses; 61 of 142 wines |
| C | Small: wide and forgiving. Big: narrow and strict | C 0.1 width 4.36; C 100 width 1.46 |
| Kernel trick | Lift the data so a straight cut works | Dose: 0.67 to 1.0 |
| gamma | How much an RBF boundary can bend | Moons test: 0.87, 0.90, 0.89 |
| SVR | A tube for numbers; points within epsilon cost nothing | New house 315.8 |
Try it yourself
Run the wine loop with C = 0.1, 1, 10 and 100 and gamma="scale". Where does the score stop improving?
Before this: Naive Bayes. Next, a model that needs no scaling at all: Decision Trees.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
Next →Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.