Principal Component Analysis (PCA)

Cover image is a PCA (Principal Component Analysis) visualization generated by ChatGPT. The prompt used was: “A detailed 2D scatter plot illustrating Principal Component Analysis (PCA). The data points are grouped into multiple clusters with different colors, representing various categories. The X and Y axes are labeled ‘PC1’ and ‘PC2’, with grid lines for reference. A semi-transparent convex hull encases each cluster to emphasize grouping. The background is clean white with subtle shadows. The title ‘PCA Visualization’ is prominently displayed at the top.” 。
Introduction
Principal Component Analysis (PCA) is a commonly used dimension reduction method. It transforms an originally linearly dependent dataset into a set of linearly independent new variables through an orthogonal transformation. This process minimizes the loss of information when projecting the dataset onto these new variables. These new variables are ranked based on their variance, with the one having the highest variance called the first principal component, the second highest called the second principal component, and so on.
PCA is widely used to map high-dimensional data into lower-dimensional space while preserving as much of the original data’s key features and information as possible.
PCA Principles: Maximum Separability and Minimum Reconstruction Error
PCA optimizes a dataset using two key concepts: maximum separability and minimum reconstruction error. Maximum separability ensures that when the data is projected onto a lower-dimensional space, the projected points remain as spread out as possible, preserving the variance in the data. Minimum reconstruction error minimizes the sum of squared distances between each original data point and its corresponding projected point, similar to the least squares method in regression analysis.
Maximum Separability
From the data points in Example 1, we can draw the M and N line segments as follows.

From the above data points, we can observe that the projections onto the M line segment are more spread out compared to those on the N line segment, meaning that more information is retained.
From a statistical perspective, this can be expressed as follows: the total variance of the data points along variable M is greater than that along variable N. Therefore, we tend to select the variable with the highest total variance as the first principal component (PC1), such as M in Example 1, followed by the second principal component (PC2), and so on.
Minimum Reconstruction Error
From the M and N line segments drawn in Maximum Separability, we can also observe that the sum of squared distances between the data points and their projections is smaller for the M line segment than for the N line segment.
In general, we prioritize the variable with the smallest sum of squared projection distances as the first principal component. In other words, the variable with the minimum projection error (sum of squared Euclidean distances between original points and projected points) is chosen as the first principal component, followed by subsequent components.
By the Pythagorean theorem, we know that when the data centroid is fixed and all data points are equidistant from the centroid, the longer the projection onto a given line segment, the shorter the distance from the projected point to the centroid. Conversely, the shorter the projection, the longer the distance from the projected point to the centroid.
This means that PCA selects directions that simultaneously maximize variance and minimize projection error, demonstrating that Maximum Separability and Minimum Reconstruction Error are fundamentally equivalent.
Centering
Centering transforms the data so that the coordinate origin aligns with the mean of the dataset without altering its distribution. This step is crucial for simplifying matrix operations and facilitating orthogonal transformations in PCA.
In simple terms, given the same data points as in Example 1, we can compute the mean of all data points to determine the original data centroid.
If $\overline{x}_j$ represents the mean of $X_j$, then:
$$ \overline{x}_j = \frac{1}{n} \sum_{i = 1}^n x_{ij}, \quad j = 1, \cdots, p, $$

By subtracting the mean from the original matrix, we obtain the centered data matrix, effectively shifting the data centroid to the origin.
$$ \mathbf{X}_c = \mathbf{X} - \overline{\mathbf{X}} = \begin{pmatrix} x_{11} & x_{12} & \cdots & x_{1p} \\ x_{21} & x_{22} & \cdots & x_{2p} \\ \vdots & \vdots & \ddots & \vdots \\ x_{n1} & x_{n2} & \cdots & x_{np} \end{pmatrix} - \begin{pmatrix} \overline{x}_1 & \overline{x}_2 & \cdots & \overline{x}_p \\ \overline{x}_1 & \overline{x}_2 & \cdots & \overline{x}_p \\ \vdots & \vdots & \ddots & \vdots \\ \overline{x}_1 & \overline{x}_2 & \cdots & \overline{x}_p \end{pmatrix} $$

Standardization
Standardization is used to eliminate the impact of differences in scale and other factors across variables, allowing the data to be evaluated on the same scale (mean = 0, standard deviation = 1). The process of standardization is similar to centering, but it also includes dividing by the standard deviation. Like centering, the standardized dataset retains the same ranking and distribution as the original data. Generally, data preprocessing involves centering first, followed by deciding whether standardization is necessary.
Suppose we are analyzing a dataset where we have collected the following information:
| 1 | 2 | 3 | 4 | ⋯ | |
|---|---|---|---|---|---|
| Height (cm) | 180 | 160 | 175 | 170 | ⋯ |
| Age (years) | 20 | 22 | 26 | 18 | ⋯ |
It is known that the data we are analyzing is more related to age than to height. However, since height is nearly 10 times larger than age, the variance of height will be much greater. This may cause PCA to favor height as the principal component, even though the information carried by height is not more significant than that of age.
We can also standardize the data points in Example 1. Let $\sigma^2_j$ represent the variance of $X_j$. From the definition of variance, we can express it as:
$$ \sigma^2_j = \frac{1}{n} \sum_{i = 1}^n (x_{ij} - \overline{x}_j)^2, \quad j = 1, \cdots, p. $$
Therefore, the result of standardizing the dataset is
$$ \mathbf{Z} = \frac{\mathbf{X}_c}{\mathbf{\sigma}} = \frac{\mathbf{X}-\overline{\mathbf{X}}}{\mathbf{\sigma}}, $$
where
$$ \mathbf{\sigma} = \begin{pmatrix} \sigma_1 & \sigma_1 & \cdots & \sigma_1 \\ \sigma_2 & \sigma_2 & \cdots & \sigma_2 \\ \vdots & \vdots & \ddots & \vdots \\ \sigma_p & \sigma_p & \cdots & \sigma_p \end{pmatrix}. $$
Data Point Projection
After applying data preprocessing methods such as centering and standardization, the next step is to project the data points onto new variables.
Suppose we have a data vector $x_i$, and we want to project $x_i$ onto $v$, resulting in $w$. From the projection angle $\theta$, we know that the length of $w$ is given by $\|x_i\| \|v\| \cos(\theta)$, where $\|x_i\|$ represents the length of $x_i$. If $v$ is a unit vector, then the length of $w$ can be rewritten as $\|x_i\| \cos(\theta)$.

The above is the projection formula for a single data point.
Now, let’s consider the projection of multiple data points in the dataset. Suppose we use the data points from Example 1, represented as $\mathbf{X} = (X_1, X_2, \cdots, X_p)^\top$, where $X_j = (x_{1j}, x_{2j}, \cdots, x_{nj})$.
Let $\mathbf{\delta} = (\delta_1, \delta_2, \cdots, \delta_p)^\top$ be the projection direction (principal component vector) of $\mathbf{X}$. Then, the projection of all data points can be written as
$$ \mathbf{\mathcal{P}} = \mathbf{\delta}^\top \mathbf{X} = (\delta_1, \delta_2, \cdots, \delta_p) \begin{pmatrix} X_1 \\ X_2 \\ \vdots \\ X_p \end{pmatrix} = \sum_{j=1}^p \delta_j X_j, $$
$\mathbf{\mathcal{P}} = (\mathcal{P}_1, \mathcal{P}_2, \cdots, \mathcal{P}_p)^\top$
where $\mathbf{\delta}$ must satisfy $\sum_{j=1}^p \delta_j^2 = 1$ to ensure that the projected vector is a unit vector.
Variance Calculation
How can we find a suitable projection direction $\mathcal{P}_i$ such that we achieve maximum separability along that projection vector? Given the following conditions
$$ \max_{\{\delta:\|\delta\| = 1\}} Var(\mathbf{\mathcal{P}}) = \max_{\{\delta:\|\delta\| = 1\}} Var(\mathbf{\delta}^\top \mathbf{X}) = \max_{\{\delta:\|\delta\| = 1\}} \mathbf{\delta}^\top Var(\mathbf{X}) \mathbf{\delta}, $$
To find the maximum variance, we must first determine the appropriate $\mathbf{\delta}$. Before doing so, we need to understand the following theorem:
If $\mathcal{A}$ is a symmetric matrix, then:
$$ \max_x x^\top \mathcal{A} x = \lambda_1 \ge \lambda_2 \ge \cdots \ge \lambda_p = \min_x x^\top \mathcal{A} x, $$
where $\lambda_1, \lambda_2, \cdots, \lambda_p$ are the eigenvalues of $\mathcal{A}$.
According to the theorem above, we can determine that the projection direction $\mathbf{\delta}$ is given by the eigenvector $\gamma_1$ corresponding to the largest eigenvalue $\lambda_1$ of the covariance matrix $\Sigma = Var(\mathbf{X}) \in \mathbb{R}^{p \times p}$.
Principal Component Analysis
First Principal Component
Returning to the initial example, let the dataset be $\mathbf{X}$. Based on the theorem mentioned in Variance Calculation, we can determine that the first principal component (PC1) is
$$ Y_1 = \gamma_1^\top \mathbf{X}, $$
where $Y_1 \in \mathbb{R}^p$ has the largest variance after projection
$$ \argmax_{\{\gamma_1:\|\gamma_1\| = 1\}} \mathbf{\gamma_1}^\top Var(\mathbf{X}) \mathbf{\gamma_1}, $$
which means that $\gamma_1$ satisfies
$$ \Sigma \gamma_1 = \lambda_1 \gamma_1. $$
From the dataset $\mathbf{X}$, we know that $E(\mathbf{X}) = \overline{\mathbf{X}}$ and $Var(\mathbf{X}) = \Sigma$. By diagonalizing the covariance matrix $\Sigma$, we get
$$ \Sigma = \Gamma \Lambda \Gamma^\top, $$
Thus, PC1 can also be written as
$$ Y_1 = \Gamma^\top_1 (\mathbf{X}-\overline{\mathbf{X}}) = \Gamma^\top_1 \mathbf{X}_{c} \in \mathbb{R}^n. $$
Second Principal Component
Now that we have determined PC1 $Y_1$ and its projection vector $\mathcal{P}_1$, we can similarly find the second principal component (PC2). It is important to note that the projection vector of PC2 must be orthogonal to PC1, meaning
$$ \mathcal{P}_2^\top \mathcal{P}_1 = 0, $$
The variance of PC2 is given by
$$ \argmax_{\left\{\gamma_2:\|\gamma_2\| = 1, \gamma_2^\top \gamma_1 = 0 \right\}} \mathbf{\gamma_2}^\top Var(\mathbf{X}) \mathbf{\gamma_2}. $$
If $\gamma_2$ satisfies these conditions, it defines PC2 as
$$ Y_2 = \Gamma^\top_2 (\mathbf{X}-\overline{\mathbf{X}}) = \Gamma^\top_2 \mathbf{X}_{c} \in \mathbb{R}^n. $$
Other Principal Components
To summarize the above, for the $q$-th principal component, we have
$$ Y_q = \Gamma^\top_q (\mathbf{X}-\overline{\mathbf{X}}) = \Gamma^\top_q \mathbf{X}_{c} \in \mathbb{R}^n, $$
and its projection vector $\mathcal{P}_q$ must be orthogonal to $\mathcal{P}_{q-1}$ (i.e., $\mathcal{P}_q^\top \mathcal{P}_{q-1} = 0$). The total number of principal components does not exceed the number of features in the dataset, $p$.
For the principal component $\mathbf{Y} = \Gamma^\top \mathbf{X}_{c}$, the following property holds:
For a given dataset $\mathbf{X} \sim (\overline{\mathbf{X}}, \Sigma)$, let $\mathbf{Y} = \Gamma^\top (\mathbf{X} - \overline{\mathbf{X}})$ represent the principal component transformation (PC transformation). Then, the following holds:
$$ E(Y_j) = 0, \quad j = 1, \cdots, p \\ ~ \\ Var(Y_j) = \lambda_j, \quad j = 1, \cdots, p \\ ~ \\ Cov(Y_i \ne Y_j) = 0, \quad i \ne j \\ ~ \\ Var(Y_1) \ge Var(Y_2) \ge \cdots \ge Var(Y_p) \ge 0 \\ ~ \\ \sum^p_{j=1} Var(Y_j) = tr(\Sigma) \\ ~ \\ \prod^p_{j=1} Var(Y_j) = |\Sigma|. $$
Python Example
Dataset Introduction
The dataset used in this example is the Boston housing data. This dataset contains housing price information from 1978 for the city of Boston, Massachusetts. It includes 506 observations for each census district in the Boston metropolitan area.
Variable Description
According to the book Applied Multivariate Statistical Analysis, this dataset contains 506 observations and 14 variables. The description for each variable is as follows:
| Variable | Description |
|---|---|
| $X_{1}$ | Per capita crime rate |
| $X_{2}$ | Proportion of residential land zoned for large lots |
| $X_{3}$ | Proportion of nonretail business acres |
| $X_{4}$ | Charles River (1 if tract bounds river, 0 otherwise) |
| $X_{5}$ | Nitric oxides concentration |
| $X_{6}$ | Average number of rooms per dwelling |
| $X_{7}$ | Proportion of owner-occupied units built prior to 1940 |
| $X_{8}$ | Weighted distances to five Boston employment centers |
| $X_{9}$ | Index of accessibility to radial highways |
| $X_{10}$ | Full-value property tax rate per $10,000 |
| $X_{11}$ | Pupil/teacher ratio |
| $X_{12}$ | $1000(B - 0.63)^2 \mathbf{I} (B < 0.63)$ where $B$ is the proportion of African American |
| $X_{13}$ | % lower status of the population |
| $X_{14}$ | Median value of owner-occupied homes in $1,000 |
Dataset
Here’s a Python code to load and view the dataset for PCA analysis.
| |
The partial information of the dataset is as follows.
| |
At the same time, use the following code to check the data and whether there are any missing values.
| |
| |
From the above results, it can be seen that there are no missing values in this dataset.
Define Variables and Standardization
Next, we define the feature variables x and the target variable y. By defining the feature and target variables, after performing PCA, the results (PCs) can be used for further analysis with other models, such as Random Forests. If only PCA is needed, all variables can be defined as feature variables.
| |
PCA
Next, we will perform Principal Component Analysis. Here, we will use scikit-learn’s PCA() function, and the n_components parameter of the PCA() function allows us to decide how much variance to retain. By not specifying the n_components parameter, it means we will retain all components (maximum variance).
| |
| |
Here, we can also intuitively observe that the total number of principal components does not exceed the number of features in the dataset.
Next, we will output the PCA component matrix and explained variance, and display them in a DataFrame for easier viewing.
| |
| |
From the above results, we can observe that the explained variance of PC1 is four times that of PC2, highlighting the dominant role of PC1 in explaining the dataset’s variability. Upon further inspection of the cumulative explained variance, we notice that as more principal components are added, the rate of cumulative variance explanation slows down. This allows us to make informed decisions on how many principal components to retain after dimensionality reduction, balancing effective explanation of the dataset while avoiding excessive dimensions that lead to redundant information and computational burden. Therefore, based on these results, we can choose to keep only the first few principal components to efficiently explain the data, without retaining all of them.
Below is a plot of the remaining cumulative variance, allowing us to more intuitively observe the remaining cumulative variance and decide how many principal components to retain.

Use the following code to find all the points after the principal component transformation (PC transformation):
| |
| |
PC1 Violin Plot
We can use a violin plot to visualize the distribution of PC1 data.
| |
If you are unable to view the interactive PC1 violin plot or need a full-screen view, please click here to access it.
PC1 and PC2 Scatter Plot
We can use a scatter plot to visualize the distribution of PC1 and PC2 data.
| |
If you are unable to view the interactive PC1 and PC2 scatter plot or need a full-screen view, please click here to access it.
Conclusion
PCA is a useful dimensionality reduction method that maps a dataset from complex $p$ dimensions to a $q$-dimensional space while retaining as much information as possible. Using PCA helps reduce the dimensionality of data, thereby lowering computation and storage costs, and improving model efficiency and accuracy. By removing unnecessary noise and correlations between features, PCA can improve the generalization ability of machine learning models and make the data more interpretable.
Environment
Operating System: Windows 11 24H2
Programming Language: Python 3.12.9
Further Learning
- The ipynb file used in this article.
See Also
References
Wolfgang Karl Härdle & Léopold Simar. (2015). Applied Multivariate Statistical Analysis (4th Edition). Springer. https://link.springer.com/book/10.1007/978-3-662-45171-7
动画讲编程. (2022, August 2). 机器学习,什么是PCA降维?一个动画告诉你答案 [Video]. YouTube. Retrieved March 25, 2025. https://youtu.be/FI0H_HStNJU
Tommy Huang. (2018, April 20). 機器/統計學習:主成分分析(Principal Component Analysis, PCA). Retrieved March 25, 2025. https://chih-sheng-huang821.medium.com/機器-統計學習-主成分分析-principle-component-analysis-pca-58229cd26e71
Jin-Zhou Li. (2024, January 27). 主成分分析 (Principal Component Analysis, PCA). Retrieved March 25, 2025. https://jinzhou.netlify.app/en/posts/principal-component-analysis/
Quantnet. (2025, January 27). MVA. GitHub. https://github.com/QuantLet/MVA
Violin Plots in Python. (No Date). Plotly | Graphing Libraries. Retrieved April 1, 2025. https://plotly.com/python/violin/
李航. (2022). 機器學習聖經:最完整的統計學習方法. (First Edition). 深智數位股份有限公司.










