I'm using PCA(n_components=2) because every tutorial does, but I don't know how many components I actually need for my model.
Why this matters
Each principal component captures some share of the total variance in your data. The first component captures the most, the second the next most, and so on. Too few components throws away useful information, and too many keeps noise and defeats the purpose of reducing dimensions. Two components is common in tutorials because it's easy to plot, not because it's the right number for modeling.
Answer 1: Keep enough components to explain a target share of the variance
Fit PCA with all components, then look at the cumulative explained variance. A common target is 90–95%.
import numpy as np
from sklearn.decomposition import PCA
pca = PCA().fit(X_scaled)
cumvar = np.cumsum(pca.explained_variance_ratio_)
n_95 = np.argmax(cumvar >= 0.95) + 1
print(f"{n_95} components explain 95% of the variance")
