Sub topic 10
Using PCA in scikit-learn
This chapter assumes you know basic Python and NumPy, understand covariance and eigenvectors at the level of the earlier chapters, and keep data as a matrix with samples in rows and features in columns. You have already built PCA by hand. Here you will use sklearn.decomposition.PCA, learn what each fitted attribute means, and avoid the usual mistakes.
The estimator API
PCA follows the standard scikit-learn pattern.
fit(X)centersXusing the column means, then finds the principal axes.transform(X)subtracts the stored mean and projects onto the axes. The result is the matrix of scores.fit_transform(X)does both in one call.inverse_transform(Z)multiplies the scores by the components and adds the mean back. This is the reconstruction from the earlier chapter.
After fitting, these attributes are available:
| Attribute | Shape | Meaning |
|---|---|---|
| `components_` | (n_components, n_features) | Principal axes, one per row, sorted by decreasing variance. Each row has unit length. |
| `explained_variance_` | (n_components,) | Variance along each axis. These are the covariance eigenvalues, computed with the `n - 1` divisor. |
| `explained_variance_ratio_` | (n_components,) | Each variance divided by the total variance of all original features. |
| `singular_values_` | (n_components,) | Singular values of the centered data. |
| `mean_` | (n_features,) | Per-feature mean learned during `fit`. |
| `n_components_` | scalar | The number of components actually kept. |
The ratio is measured against the total variance of the original data, not against the kept components. If you keep only two components, explained_variance_ratio_ will usually sum to less than 1.
Standardize first, inside a pipeline
PCA centers the data but does not scale it. A feature measured in large units dominates the covariance matrix and therefore the first component. When features have different units or spreads, put a StandardScaler in front of PCA. A pipeline keeps the two steps together.
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_)Z has shape (150, 2). For standardized iris data, the first component explains roughly 73% of the variance and the second roughly 23%. components_ has shape (2, 4). Each row lists the weight of the four original features in one component, and these weights are the loadings you will interpret in a later chapter.
Checking against the from-scratch version
The scikit-learn result should match the eigendecomposition you wrote earlier. Each axis can differ by a sign flip, because an eigenvector v and -v span the same direction, so compare absolute values.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
X, _ = load_iris(return_X_y=True)
pca = PCA(n_components=2).fit(X)
Xc = X - X.mean(axis=0)
vals, vecs = np.linalg.eigh(np.cov(Xc, rowvar=False))
vecs = vecs[:, ::-1][:, :2] # eigh sorts ascending, so reverse
vals = vals[::-1][:2]
print(np.allclose(np.abs(pca.components_), np.abs(vecs.T)))
print(np.allclose(pca.explained_variance_, vals))Both lines print True.
Choosing `n_components`
The n_components argument accepts several kinds of value.
| Value | Behavior |
|---|---|
| An integer `k` | Keep exactly `k` components. It must not exceed `min(n_samples, n_features)`. |
| A float between 0 and 1 | Keep the smallest number of components whose cumulative explained variance reaches that fraction. |
| `"mle"` | Estimate the dimension with Minka's maximum likelihood method. It needs `n_samples >= n_features`. |
| `None` | Keep `min(n_samples, n_features)` components. Use this to inspect the full variance spectrum. |
The float form implements the variance-threshold rule from the previous chapter. It needs a solver that computes the full spectrum, and svd_solver="auto" picks one for you. After fitting, read the result from n_components_.
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 64 pixel features reduce to a much smaller number of components. The second printed value is the mean squared reconstruction error in standardized units. Because the data is standardized, each feature has variance 1. The error is therefore about 5% of the total variance per feature, which matches the 95% threshold.
To draw a scree plot, fit with n_components=None and plot explained_variance_ratio_ against the component index. Plot np.cumsum(pca.explained_variance_ratio_) to see where the threshold is crossed.
Solvers
The svd_solver parameter selects the algorithm. Both the available names and the "auto" rules depend on your scikit-learn version, so check the documentation for your installed release.
| Solver | What it does | Use when |
|---|---|---|
| `"full"` | Complete SVD through LAPACK. Exact. | The data is small or medium, or you need all components. |
| `"covariance_eigh"` | Eigendecomposition of the covariance matrix (newer versions only). | There are many samples and few features. |
| `"arpack"` | Iterative truncated SVD. | You need a few components and `n_components` is below the smaller data dimension. |
| `"randomized"` | Approximate truncated SVD. | The data is large and you need a small number of components. Set `random_state` for repeatable results. |
| `"auto"` | Chooses among the above from the data shape and `n_components`. | This is the default, and it is usually fine. |
The randomized solver is approximate, so its variances can differ slightly from the exact result. Axes from the iterative and randomized solvers may also differ in sign between runs unless you fix random_state.
Whitening
PCA(whiten=True) divides each score column by the square root of its explained variance. Every output feature then has unit variance and the features are uncorrelated. This helps models that assume similar feature scales, such as some clustering or kernel methods. It also amplifies the low-variance components, which are often mostly noise. inverse_transform undoes whitening correctly, but the scores are no longer in the original units.
PCA inside model selection
Treat PCA as a learned transformation, like any other. Fit it on training data only, and let cross-validation refit it in each fold. A pipeline does this automatically, and it lets you tune the number of components as a hyperparameter.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
pipe = Pipeline([
("scale", StandardScaler()),
("pca", PCA()),
("clf", LogisticRegression(max_iter=2000)),
])
grid = GridSearchCV(pipe, {"pca__n_components": [10, 20, 30, 40]}, cv=5)
grid.fit(X_train, y_train)
print(grid.best_params_)
print(grid.score(X_test, y_test))The double underscore in pca__n_components reaches into the pipeline step named pca. The scaler and PCA are refit on each training fold, so the validation fold never influences the learned axes.
Common errors
- Forgetting to scale. Features in different units give a first component that mostly tracks the largest-scale feature. Scale with
StandardScalerunless all features share a unit and the scale differences are meaningful. - Scaling outside the pipeline. Scaling all the data before cross-validation leaks statistics from the validation folds. Put the scaler in the pipeline.
- Requesting too many components. An integer larger than
min(n_samples, n_features)raises aValueError. With 50 samples and 1000 features, you can get at most 50 components. - Passing sparse matrices.
PCAcenters the data, which would make a sparse matrix dense, so it does not accept sparse input. UseTruncatedSVDinstead, which skips centering. - Reading the ratio as accuracy. A high explained variance ratio says the kept axes capture variance. It does not say they capture the signal your model needs. A low-variance direction can still separate your classes.
- Treating the transform as fixed.
transformusesmean_andcomponents_fromfit. New data with a different distribution is projected onto the old axes, not onto new ones. - Assuming whitened scores keep their scale. After
whiten=True, compare scores only in standardized terms.
Exercises
Exercise
You fit PCA(n_components=3) on a standardized dataset with 10 features and find that explained_variance_ratio_.sum() is 0.82. What does 0.82 mean, and what is the mean squared reconstruction error per feature after inverse_transform, in standardized units?
Show answer
The three components together capture 82% of the total variance of the 10 original features. Standardized features each have variance 1, so the total variance is 10, and the discarded 18% is 1.8 in total. Spread over 10 features, the mean squared reconstruction error per feature is about 0.18, up to the small difference between the n and n - 1 divisors.
Exercise
A colleague runs StandardScaler().fit_transform(X) and PCA(n_components=0.9).fit_transform(...) on the full dataset, then does 5-fold cross-validation on the scores. What is wrong, and how do you fix it?
Show answer
The scaler and PCA were fit on all rows, including the rows that later serve as validation folds, so information from the validation data leaks into the transformation and inflates the cross-validation score. Fix it by building Pipeline([("scale", StandardScaler()), ("pca", PCA(n_components=0.9)), ("clf", ...)]) and passing the pipeline to cross_val_score or GridSearchCV, so each fold refits the scaler and PCA on its own training portion.