Sub topic 10
Using PCA in scikit-learn
This chapter assumes you know basic NumPy, the covariance matrix, and why PCA needs centered data. It also assumes you have seen the from-scratch version. Here you will use sklearn.decomposition.PCA, which does the same work behind a standard interface.
The fit and transform workflow
PCA follows the usual estimator pattern. fit learns the mean and the principal axes from training data. transform centers new data with the learned mean and projects it onto the axes. inverse_transform maps scores back to the original feature space.
Internally, PCA centers the data for you, but it does not scale it. Features with large units will dominate the components unless you standardize them first. A pipeline keeps the two steps together.
A pipeline on the iris data
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), PCA(n_components=2))
Z = pipe.fit_transform(X)
pca = pipe.named_steps["pca"]
print(Z.shape)
print(pca.explained_variance_ratio_)
print(pca.components_)The fitted object exposes these attributes:
| Attribute | Meaning |
|---|---|
| `components_` | Principal axes, one per row, shape `(n_components, n_features)`. These are the loadings. |
| `explained_variance_` | Variance along each axis, which is the covariance eigenvalue. |
| `explained_variance_ratio_` | Each variance divided by the total variance of all features. |
| `mean_` | Per-feature mean used for centering. |
| `n_components_` | Number of components actually kept. |
The ratios of the kept components sum to less than 1 whenever you drop components. The remainder is the variance you discard.
Choosing n_components
n_components accepts three kinds of value:
- An integer keeps exactly that many components.
- A float strictly between 0 and 1 keeps the smallest number of components whose cumulative explained variance reaches that fraction.
Nonekeepsmin(n_samples, n_features)components.
The float form is convenient when you do not know the right number in advance.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X, _ = load_digits(return_X_y=True)
X_std = StandardScaler().fit_transform(X)
pca = PCA(n_components=0.95)
Z = pca.fit_transform(X_std)
X_back = pca.inverse_transform(Z)
print(pca.n_components_)
print(((X_std - X_back) ** 2).mean())The digits data has 64 features. Check n_components_ to see how many survive the 95% threshold. The printed mean squared error is the reconstruction error in standardized units.
Common errors
- Skipping scaling. If one feature is measured in thousands and another in fractions, the first dominates the first component. Standardize unless the features already share a meaningful unit.
- Fitting on all the data before splitting. The mean, scale, and axes must come from the training set only. Put the scaler and PCA in a pipeline, then fit the pipeline on the training split.
- Treating the sign of a component as meaningful. The axis
vand-vdescribe the same direction. Signs can differ between runs or library versions, so do not compare them directly. - Reading ratios as accuracy. A high cumulative ratio means the components keep variance. It does not mean they keep the information your downstream model needs, which may live in low-variance directions.
- Using
whiten=Trueby accident. Whitening rescales each score to unit variance. This helps some models, but it removes the relative size of the components and changes reconstruction behavior.
Exercise
You standardize and fit PCA(n_components=0.9) on a training set. A colleague says to refit PCA on the test set so the test scores "use the best axes". What is wrong with this, and what should you call instead?
Show answer
Refitting learns different axes and a different mean from the test data, so the test scores live in a different coordinate system from the training scores and leak test information into the preprocessing. Fit the pipeline on the training set only, then call transform (not fit_transform) on the test set.