StandardScaler in Python with scikit-learn
Rescale every feature to mean 0 and standard deviation 1, learning the numbers from the training set only.
- fit_transform on the training set
- transform on the test set
- Reading mean_ and scale_
- alcohol: mean 13.0, std 0.8
- proline: mean 749.81, std 302.18
- alcohol: mean 0.0, std 1.0
- proline: mean 0.0, std 1.0
Putting features on the same scale
Découvrez StandardScaler in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.
Points clés
fit_transform(X_train)learns the mean and standard deviation of each column and rescales the training set.transform(X_test)reuses the training numbers, so the test set is scaled the same way.- The test means are near 0 (0.01 and -0.04), not exactly 0, because they use the training statistics.
scaler.mean_andscaler.scale_store what was learned.
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
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
# Two columns on very different scales: alcohol and proline
print("Before mean:", np.round(X_train[:, [0, 12]].mean(axis=0), 2).tolist())
print("Before std: ", np.round(X_train[:, [0, 12]].std(axis=0), 2).tolist())
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # learn mean and std from the training set only
X_test_scaled = scaler.transform(X_test) # reuse them for the test set
print("Train mean:", (np.round(X_train_scaled[:, [0, 12]].mean(axis=0), 2) + 0.0).tolist()) # + 0.0 turns -0.0 into 0.0
print("Train std: ", np.round(X_train_scaled[:, [0, 12]].std(axis=0), 2).tolist())
print("Test mean:", np.round(X_test_scaled[:, [0, 12]].mean(axis=0), 2).tolist())
print("Learned mean:", np.round(scaler.mean_[[0, 12]], 2).tolist())
Résultat de l’exécution
Before mean: [13.0, 749.81]
Before std: [0.8, 302.18]
Train mean: [0.0, 0.0]
Train std: [1.0, 1.0]
Test mean: [0.01, -0.04]
Learned mean: [13.0, 749.81]
Explication du code
Cet exemple montre StandardScaler in Python with scikit-learn 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.
S'entraîner avec un défi
Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.
- Standardisation par z-score Centrez une variable en 0 et ramenez son écart-type à 1. Facile
- Normalisation min-max Remettez une variable à l'échelle pour que sa plus petite valeur devienne 0 et sa plus grande 1. Facile
Outils pour cette leçon
- Préparation des données pour l'apprentissage automatique en PythonMettez les variables à l'échelle avec la normalisation min-max et la standardisation par score z, et multipliez des matrices à la main.
- 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.