Machine Learning with scikit-learn

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.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • PCA with n_components
  • explained_variance_ratio_
  • How many components keep 90%
Wine data
  1. 1(178, 13)13 original features
  2. 2StandardScalerSame scale for every feature
  3. 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

  1. Standardize first, or proline alone decides the first component.
  2. fit_transform turns the (178, 13) data into shape (178, 2).
  3. The first component keeps 36.2% of the variance and the second 19.2%, 55.4% together.
  4. 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

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

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.

  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