Machine Learning with scikit-learn

SVM in Python with scikit-learn (SVC)

Train a support vector machine, compare the linear and RBF kernels, and see when a curved boundary helps.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • SVC with kernel="linear" and kernel="rbf"
  • Scaling features in a pipeline
  • Choosing a kernel by test accuracy
Test accuracy
linear
  • moons: 0.811
  • breast cancer: 0.953
rbf
  • moons: 0.956
  • breast cancer: 0.953

The widest gap between classes

The problem

You want a classifier that draws a clean boundary between classes, works well with many features and can bend the boundary when the classes are not separated by a straight line.

Think of it like this

An SVM is like building the widest possible road between two villages: the road's edges just touch the nearest houses on each side, called support vectors. The RBF kernel lets the road curve around the houses instead of running straight.

From a road between villages to code
SVC(kernel="linear")🛣️ A straight road
SVC(kernel="rbf")🌀 A road that can curve
support vectors🏠 The houses that touch the road's edge
C=1.0🚧 How strictly houses must stay off the road
The boundary keeps the biggest margin.
In one sentence

A support vector machine finds the boundary with the largest margin to the nearest training points; a kernel such as RBF lets that boundary be curved.

Key points

  1. On the curved moons data the linear kernel reaches 0.811 and the RBF kernel 0.956.
  2. On the breast cancer data both kernels score 0.953, so the linear one is enough.
  3. StandardScaler comes first in the pipeline because SVMs compare distances.
  4. C controls how much the model tolerates points inside the margin.

When should you use it?

  • Small and medium datasets with many features.
  • Text and image features after vectorising.
  • Problems with a clear but curved class boundary.

When not to use it

  • Hundreds of thousands of rows: training gets slow; try LinearSVC or SGDClassifier.
  • When you need probabilities by default: logistic regression gives them directly.

Example code

Open in editor →
main.py
from sklearn.datasets import make_moons, load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

datasets = {
    "moons (curved)": make_moons(n_samples=300, noise=0.2, random_state=0),
    "breast cancer": load_breast_cancer(return_X_y=True),
}

for name, (X, y) in datasets.items():
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
    for kernel in ["linear", "rbf"]:
        # SVMs need scaled features, so the scaler goes first in the pipeline
        model = make_pipeline(StandardScaler(), SVC(kernel=kernel, C=1.0))
        model.fit(X_train, y_train)
        print(f"{name:<15} {kernel:<6} accuracy {model.score(X_test, y_test):.3f}")
Get a Run button for this example

Result of running the code

moons (curved)  linear accuracy 0.811
moons (curved)  rbf    accuracy 0.956
breast cancer   linear accuracy 0.953
breast cancer   rbf    accuracy 0.953

Code explanation

datasets holds two problems: make_moons draws two interleaving half circles, and the breast cancer data is a real table with 30 features. For each one the loop trains SVC with kernel="linear" and kernel="rbf", always after StandardScaler because SVMs compare distances. On the moons a straight line can only reach 0.811, while the curved RBF boundary reaches 0.956. On the breast cancer data both kernels score 0.953, so the simpler linear model is enough there.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Training an SVM without scaling

Features with large values dominate the margin and accuracy drops.

Problem
SVC(kernel="rbf").fit(X_train, y_train)
Fix
make_pipeline(StandardScaler(), SVC(kernel="rbf")).fit(X_train, y_train)

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson