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.
- SVC with kernel="linear" and kernel="rbf"
- Scaling features in a pipeline
- Choosing a kernel by test accuracy
- moons: 0.811
- breast cancer: 0.953
- 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.
SVC(kernel="linear")🛣️ A straight roadSVC(kernel="rbf")🌀 A road that can curvesupport vectors🏠 The houses that touch the road's edgeC=1.0🚧 How strictly houses must stay off the roadA 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
- On the curved moons data the linear kernel reaches 0.811 and the RBF kernel 0.956.
- On the breast cancer data both kernels score 0.953, so the linear one is enough.
StandardScalercomes first in the pipeline because SVMs compare distances.Ccontrols 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
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}")
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.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Training an SVM without scaling
Features with large values dominate the margin and accuracy drops.
SVC(kernel="rbf").fit(X_train, y_train)
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
- Classification Basics: Softmax and k-Nearest Neighbors in PythonTurn scores into class probabilities with softmax, score them with cross-entropy and classify points with k-nearest neighbors.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.