Reduce dimensions with PCA
scikit-learn 1.9.1
Project numeric features into fewer components, and validate what that choice does to a downstream model.
On this page
Read components and explained variance
Principal component analysis creates orthogonal directions that capture variance. scikit-learn PCA centers the input. Use a scaler first when feature units or scales would otherwise dominate. Explained variance measures how much variation the chosen components retain.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, _ = load_iris(return_X_y=True)
reducer = make_pipeline(StandardScaler(), PCA(n_components=2))
coordinates = reducer.fit_transform(X)
print(X.shape, coordinates.shape)
Example output
(150, 4) (150, 2)
Compare a reduced model with a baseline
In a prediction pipeline, fit PCA on each training fold and transform its validation fold. Compare against the same estimator without PCA. A low-variance component can still carry predictive information, so use the appropriate validation metric to choose how many components to retain.