PCA in Python with scikit-learn
Compress 13 features into 2 with PCA, see how much information each component keeps, and pick the number of components.
- PCA with n_components
- explained_variance_ratio_
- How many components keep 90%
- 1
(178, 13)13 original features - 2
StandardScalerSame scale for every feature - 3
(178, 2)2 components, 55.4% of the variance
Fewer columns, most of the information
Découvrez PCA in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.
Points clés
- Standardize first, or proline alone decides the first component.
fit_transformturns the (178, 13) data into shape (178, 2).- The first component keeps 36.2% of the variance and the second 19.2%, 55.4% together.
- 8 components are needed to keep 90% of the variance.
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.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
print("Original shape:", X.shape)
# PCA is sensitive to scale, so standardize the 13 features first
X_scaled = StandardScaler().fit_transform(X)
pca = PCA(n_components=2)
X_2d = pca.fit_transform(X_scaled)
print("Reduced shape: ", X_2d.shape)
ratios = pca.explained_variance_ratio_
print("Variance explained:", np.round(ratios, 3).tolist())
print(f"Total kept: {ratios.sum():.1%}")
# How many components keep 90% of the variance?
full = PCA().fit(X_scaled)
needed = int(np.argmax(np.cumsum(full.explained_variance_ratio_) >= 0.90)) + 1
print("Components for 90%:", needed)
Résultat de l’exécution
Original shape: (178, 13)
Reduced shape: (178, 2)
Variance explained: [0.362, 0.192]
Total kept: 55.4%
Components for 90%: 8
Explication du code
Cet exemple montre PCA 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.
Tous les défisOutils pour cette leçon
- 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.
- Exercices Python corrigés : s'entraîner en ligne gratuitementExercices Python corrigés pour débutants et défis vérifiés automatiquement, du plus facile au plus difficile. À faire dans le navigateur, sans installation.