A Support Vector Machine (SVM) classifier finds the boundary that separates classes with the widest possible margin. With kernels it can draw curved boundaries, and it is very effective on small and medium datasets with many features.
What You Will Learn
- Hyperplanes, margins and support vectors
- Soft margin and the C parameter
- The kernel trick
- Training and tuning SVC
Prerequisites
The Idea
Many lines (hyperplanes) can separate two classes. SVM picks the one with the largest gap (margin) to the nearest points of each class. Those nearest points are the support vectors; the other points do not affect the boundary.
C controls the soft margin: a small C allows some misclassified points for a wider, simpler margin; a large C tries to classify every training point correctly.
The kernel trick lets SVM work as if the data were mapped to a higher-dimensional space where it becomes separable, without computing that mapping. The RBF kernel is the default.
Step 1: Data
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import pandas as pd
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
print(X.shape, y.value_counts().to_dict())
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
def evaluate(name, model):
model.fit(X_train, y_train)
p = model.predict(X_test)
print(f'{name:26s} acc={accuracy_score(y_test, p):.3f}')
return model, p
Explanation: We use the built-in Breast Cancer Wisconsin dataset: 569 tumour samples, 30 numeric measurements each, and a label 0 = malignant or 1 = benign. stratify=y keeps the same class balance in the train and test sets. Every classification tutorial in this series uses this exact split, so you can compare algorithms fairly.
(569, 30) {1: 357, 0: 212}
Step 2: Scaling Matters
from sklearn.svm import SVC
evaluate('SVC rbf noscale', SVC())
sv, psv = evaluate('SVC rbf scaled', make_pipeline(StandardScaler(), SVC()))
evaluate('SVC linear scaled', make_pipeline(StandardScaler(), SVC(kernel='linear')))
print(confusion_matrix(y_test, psv))
print('n SV', sv[-1].n_support_)
Explanation: Scaling lifts accuracy from 93.0% to 98.2%, tied with logistic regression for the best result on this split. Only 97 of the 455 training samples (51 malignant, 46 benign) are support vectors.
SVC rbf noscale acc=0.930 SVC rbf scaled acc=0.982 SVC linear scaled acc=0.974 [[41 1] [ 1 71]] n SV [51 46]
Step 3: Tune C and gamma
from sklearn.model_selection import GridSearchCV
pipe = make_pipeline(StandardScaler(), SVC())
grid = GridSearchCV(pipe, {'svc__C': [0.1, 1, 10, 100], 'svc__gamma': ['scale', 0.001, 0.01, 0.1]}, cv=5)
grid.fit(X_train, y_train)
print(grid.best_params_, round(grid.best_score_, 3))
| Parameter | Effect |
|---|---|
| C | Small = wider margin, more tolerant; large = fits training data tightly |
| kernel | ‘rbf’, ‘linear’, ‘poly’, ‘sigmoid’ |
| gamma (rbf) | Small = smooth boundary; large = wiggly boundary that can overfit |
| probability=True | Enables predict_proba (slower) |
Pros and Cons
| Advantages | Disadvantages |
|---|---|
| Excellent accuracy on small/medium data | Slow on large datasets |
| Works with many features | Needs scaling and tuning |
| Kernels for non-linear problems | No direct probabilities; harder to interpret |
Common Errors
| Problem | Cause and fix |
|---|---|
| Poor accuracy | Scale features; tune C and gamma. |
AttributeError: predict_proba is not available |
Create SVC(probability=True). |
Practice Exercises
- Plot the decision boundary on two features of the iris dataset.
- Compare kernels with cross-validation.
Interview Questions
Q: What are support vectors?
The training points closest to the boundary that define it.
Q: What does C control?
The trade-off between margin width and training errors.
Q: What is the kernel trick?
Computing similarities as if in a higher-dimensional space without explicit mapping.
Summary
SVC maximises the margin between classes; scale features, choose a kernel, and tune C and gamma with cross-validation.
Machine Learning Tutorials, Courses and Certifications