Support Vector Machine in Python (scikit-learn SVC)

To build a support vector machine in Python, use scikit-learn’s SVC class inside a pipeline with StandardScaler, then call fit() and predict(). The SVM finds the boundary with the widest margin between classes:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
model = make_pipeline(StandardScaler(), SVC(kernel="rbf")).fit(X_train, y_train)

Because the breast cancer dataset ships with scikit-learn, you can run every example offline; I used Python 3.12.5 and scikit-learn 1.9.1.

We’ll train and evaluate an SVM, compare kernels, tune C and gamma with a grid search, and plot a decision boundary.

Support vector machine in Python with scikit-learn

The dataset has 569 tumors described by 30 measurements, labeled malignant or benign. I hold back 25% for testing:

from sklearn.datasets import load_breast_cancer
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = load_breast_cancer(return_X_y=True)
print("samples, features:", X.shape)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

model = make_pipeline(StandardScaler(), SVC(kernel="rbf", C=1.0))
model.fit(X_train, y_train)
pred = model.predict(X_test)

print(f"test accuracy: {accuracy_score(y_test, pred):.3f}")
print("support vectors per class:", model[-1].n_support_)
print(classification_report(y_test, pred, target_names=["malignant", "benign"], digits=3))

Output:

samples, features: (569, 30)
test accuracy: 0.979
support vectors per class: [50 46]
              precision    recall  f1-score   support

   malignant      0.963     0.981     0.972        53
      benign      0.989     0.978     0.983        90

    accuracy                          0.979       143
   macro avg      0.976     0.979     0.978       143
weighted avg      0.979     0.979     0.979       143
Command Prompt output of a scikit-learn SVC pipeline on the breast cancer dataset with test accuracy, support vectors and a classification report
High accuracy on unseen data, with precision and recall for each class.

n_support_ shows how many training points became support vectors: the ones closest to the boundary that actually define it.

Which SVM kernel should you use?

The kernel decides the shape of the boundary. Here’s 5-fold cross-validation for each built-in kernel, plus RBF without scaling:

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = load_breast_cancer(return_X_y=True)
for kernel in ["linear", "poly", "rbf", "sigmoid"]:
    model = make_pipeline(StandardScaler(), SVC(kernel=kernel))
    scores = cross_val_score(model, X, y, cv=5)
    print(f"{kernel:<8} mean accuracy {scores.mean():.3f} (+/- {scores.std():.3f})")

unscaled = cross_val_score(SVC(kernel="rbf"), X, y, cv=5).mean()
print(f"rbf without scaling: {unscaled:.3f}")

Output:

linear   mean accuracy 0.972 (+/- 0.009)
poly     mean accuracy 0.903 (+/- 0.023)
rbf      mean accuracy 0.974 (+/- 0.015)
sigmoid  mean accuracy 0.953 (+/- 0.029)
rbf without scaling: 0.912
Command Prompt output comparing linear, poly, rbf and sigmoid SVM kernels with cross-validation accuracy in Python
Linear and RBF lead; dropping the scaler hurts RBF noticeably.

Start with RBF, and try linear when you have many features. Always scale: SVMs measure distances, so a feature in the thousands would dominate one between 0 and 1.

Tune C and gamma with GridSearchCV

C controls how much the model tolerates misclassified training points, and gamma controls how far each point’s influence reaches. A grid search tests the combinations:

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
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("best params:", grid.best_params_)
print(f"best cross-validation accuracy: {grid.best_score_:.3f}")
print(f"test accuracy with best model:  {grid.score(X_test, y_test):.3f}")

Output:

best params: {'svc__C': 10, 'svc__gamma': 0.001}
best cross-validation accuracy: 0.977
test accuracy with best model:  0.979
Command Prompt output of scikit-learn GridSearchCV tuning SVM C and gamma with the best parameters and test accuracy
The best C and gamma from cross-validation, then a check on the untouched test set.

The svc__ prefix tells the pipeline which step a parameter belongs to. Large C with large gamma tends to overfit; small values underfit.

Plot an SVM decision boundary

With two features, you can see what the RBF kernel does: the solid line is the boundary, the dashed lines are the margins, and circled points are support vectors:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_moons
from sklearn.svm import SVC

X, y = make_moons(n_samples=200, noise=0.2, random_state=0)
model = SVC(kernel="rbf", C=10, gamma=1).fit(X, y)

xx, yy = np.meshgrid(np.linspace(-1.6, 2.6, 300), np.linspace(-1.1, 1.6, 300))
zz = model.decision_function(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)

plt.figure(figsize=(8, 5))
plt.contourf(xx, yy, zz > 0, alpha=0.25, cmap="coolwarm")
plt.contour(xx, yy, zz, levels=[-1, 0, 1], linestyles=["--", "-", "--"], colors="k", linewidths=1)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", s=18, edgecolors="k", linewidths=0.3)
sv = model.support_vectors_
plt.scatter(sv[:, 0], sv[:, 1], s=80, facecolors="none", edgecolors="k", label=f"support vectors ({len(sv)})")
plt.title("SVM with an RBF kernel: decision boundary and margins")
plt.legend(loc="lower left"); plt.tight_layout()
plt.show()
Matplotlib plot of an RBF support vector machine decision boundary with dashed margins and circled support vectors on moon-shaped data
A curved boundary that a straight line couldn’t draw, defined only by the circled points.

Plotting decision regions is a good habit with any classifier. Compare with how clusters look in k-means clustering in Python.

SVM pros and cons

StrengthsWeaknesses
Works well with many featuresSlow to train on very large datasets
Flexible boundaries through kernelsNeeds feature scaling
Robust to overfitting with a good CNo direct probability output (use probability=True)
Only support vectors define the modelC and gamma need tuning

For more than about 100,000 rows, LinearSVC or SGDClassifier train much faster.

Here are more machine learning guides in Python:

Frequently asked questions

How do I create a support vector machine in Python?

Use scikit-learn: make_pipeline(StandardScaler(), SVC()).fit(X_train, y_train), then predict() on new data.

What’s the difference between SVC and LinearSVC?

SVC supports any kernel; LinearSVC only does linear boundaries but scales much better to big datasets.

Do I need to scale data for SVM?

Yes. SVMs rely on distances, so unscaled features distort the boundary.

What do C and gamma do?

C sets how strictly the model fits training points; gamma sets how far a single point’s influence reaches in the RBF kernel.

Can SVM do regression?

Yes, with sklearn.svm.SVR.

Where are SVMs documented?

See Support Vector Machines in the scikit-learn user guide.