Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

🔎 Principal Component Analysis

Principal Component Analysis (PCA) is a dimensionality reduction technique. It is considered an unsupervised machine learning method, since we do not model any relationship with a target/response variable. Instead, PCA finds a lower-dimensional representation of our data.

Simply put, PCA finds the principal components (the eigenvectors) of the centered data matrix XX. Each eigenvector points in a direction of maximal variance, ordered by how much variance it explains.

Source
<Figure size 640x480 with 1 Axes>

This example illustrates how PCA finds the two orthogonal directions (eigenvectors) along which the data vary most.

Next, we apply PCA to the Iris dataset (4 features). First, we can inspect which features are most discriminative with a pairplot:

<Figure size 1120x1000 with 20 Axes>

The pairplot shows petal length and petal width separate the three species most clearly.

Feature names:
 ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']

Principal components (loadings):
 [[ 0.36138659 -0.08452251  0.85667061  0.3582892 ]
 [ 0.65658877  0.73016143 -0.17337266 -0.07548102]
 [-0.58202985  0.59791083  0.07623608  0.54583143]]

Explained variance ratio:
 [0.92461872 0.05306648 0.01710261]

Since PC1 explains over 92% of the variance, projecting onto it alone already captures most of the dataset’s structure.

Finally, we can project the data with the .transform(X) method. This does the following:

  1. Centers X by subtracting each feature’s mean.

  2. Computes dot-products with the selected eigenvectors.

The resulting X_pca matrix has shape (n_samples, 3), giving the coordinates of each sample in the PCA subspace.

<Figure size 1200x400 with 3 Axes>

The 3D panel above is fixed at one viewing angle, which makes it hard to judge how the species actually sit in the component space. Here is the same projection as a figure you can rotate and zoom with the mouse — drag to spin it, scroll to zoom, double-click to reset:

Source
Loading...

Spin it around and you will see that almost all of the separation happens along PC1: viewed down that axis the three species stay apart, while PC2 and PC3 mostly spread the points within each species. That is the visual counterpart of PC1 alone explaining over 92% of the variance.