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.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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

Découvrez SVM in Python with scikit-learn (SVC) avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  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.

Quand l’utiliser ?

  • Train and evaluate classic machine learning models on tabular data.
  • Prepare features: split, scale and encode data the way real projects do.
  • Compare models fairly with cross-validation and the right metric.

Code d’exemple

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}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

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

Explication du code

Cet exemple montre SVM in Python with scikit-learn (SVC) en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  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.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Outils pour cette leçon