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.
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
- 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.
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}")
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.
- 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.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
Outils pour cette leçon
- Bases de la classification : softmax et k plus proches voisins en PythonTransformez des scores en probabilités de classes avec softmax, évaluez-les avec l'entropie croisée et classez des points avec les k plus proches voisins.
- Jupyter Notebook en ligne : exécuter des cellules Python dans le navigateurJupyter Notebook en ligne gratuit : exécutez des cellules Python avec pandas, NumPy et Matplotlib, ajoutez du texte en Markdown, ouvrez et téléchargez des fichiers .ipynb. Sans installation, sans compte.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.