Machine Learning with scikit-learn

StandardScaler in Python with scikit-learn

Rescale every feature to mean 0 and standard deviation 1, learning the numbers from the training set only.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • fit_transform on the training set
  • transform on the test set
  • Reading mean_ and scale_
Two wine features in the training set
Before
  • alcohol: mean 13.0, std 0.8
  • proline: mean 749.81, std 302.18
After
  • 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

  1. fit_transform(X_train) learns the mean and standard deviation of each column and rescales the training set.
  2. transform(X_test) reuses the training numbers, so the test set is scaled the same way.
  3. The test means are near 0 (0.01 and -0.04), not exactly 0, because they use the training statistics.
  4. scaler.mean_ and scaler.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

main.py
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())
Obtenir un bouton Run pour cet exemple

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.

  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.

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.

Tous les défis

Outils pour cette leçon