Machine Learning - PCA Visualization Case
Imagine you are tidying up a cluttered room filled with all kinds of items. To understand the layout more clearly, you might take several photos of it from different angles (such as front, side, and overhead).
Principal Component Analysis (abbreviated as PCA) does something similar in machine learning.
PCA is a powerfuldata dimensionality reductionandVisualizationtool. When our data contains hundreds or thousands of features (dimensions), it is as if the data resides in an ultra-high-dimensional space that humans cannot intuitively comprehend.
PCA can help us find the most important perspectives in the data (i.e., principal components) and project the data onto the two or three most important dimensions, allowing us to observe the structure and distribution of high-dimensional data with 2D or 3D scatter plots.
In short, the goals of PCA are:
- Dimensionality reduction: Use fewer features to represent the original data, reducing computation and storage while removing noise.
- Visualization: Reduce high-dimensional data to 2D or 3D so that we can intuitively observe the relationships between data points (such as clustering and separation).
PCA Core Principles and Workflow
The core idea of PCA is to find the directions with the largest variance in the data.
The larger the variance, the more dispersed the projected points are in that direction, and the more information it contains.
The first direction found is thefirst principal component (PC1), and the second direction, orthogonal to PC1 with the next largest variance, is thesecond principal component (PC2), and so on.
PCA Workflow Diagram

Description of the key steps in the workflow:
Standardization: Make each feature have a mean of 0 and a standard deviation of 1, ensuring all features have equal importance in the calculation.
Covariance matrix: Compute the correlations between features. PCA analyzes this matrix to find the main directions of variation in the data.
Eigenvalues and Eigenvectors:
- Eigenvectors: are the principal component directions we are looking for.
- Eigenvalues: the amount of data variance in the direction of the corresponding eigenvector. The larger the eigenvalue, the more important the principal component.
Select Principal Components: Sort the eigenvalues from largest to smallest and select the eigenvectors corresponding to the top K largest eigenvalues. K is the target dimension we want to reduce to (for example, for visualization, K=2 or 3).
Data Transformation: Use the selected K eigenvectors to form a projection matrix, multiply the original data points by this matrix, and obtain the coordinates on the K new principal components, i.e., the reduced data.
Practical Case: Visualization of the Iris Dataset
We will use the classicIris datasetto demonstrate PCA. This dataset contains 150 samples, each with 4 features (sepal length, sepal width, petal length, petal width), belonging to 3 different species.
Our goal is to use PCA to reduce this 4-dimensional data to 2 dimensions, plot it on a 2D plane, and observe whether flowers of different species can be distinguished.
Environment Setup and Data Loading
First, make sure you have installed the necessary Python libraries:scikit-learn, matplotlib, numpy,pandas。
Example
Import the necessary libraries
import
numpy
as
np
import
pandas
as
pd
import
matplotlib.
pyplot
as
plt
from
sklearn
import
datasets
from
sklearn.
decomposition
import
PCA
from
sklearn.
preprocessing
import
StandardScaler
Set Chinese font and chart style (optional)
plt.
rcParams
[
'font.sans-serif'
]
=
[
'SimHei'
]
For proper display of Chinese labels
plt.
rcParams
[
'axes.unicode_minus'
]
=
False
For proper display of minus signs
Load the Iris dataset
iris
=
datasets.
load_iris
(
)
X
=
iris.
data
Feature data, with shape (150, 4)
y
=
iris.
target
Target labels (species), with shape (150,)
target_names
=
iris.
target_names
Species names: ['setosa', 'versicolor', 'virginica']
(
f
"Dataset shape: {X.shape}"
)
(
f
"Feature names: {iris.feature_names}"
)
(
f
"Target classes: {target_names}"
)
Output:
数据集形状: (150, 4)
特征名称: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
目标类别: ['setosa' 'versicolor' 'virginica']
Data standardization
Before applying PCA, standardizing the data iscrucialstep.
Because PCA is very sensitive to feature scale, if one feature has a numeric range (e.g., petal length in centimeters, values between 1-10) much larger than another feature (e.g., sepal width in millimeters, values between 0.1-1), the feature with the larger range will dominate the direction of the principal components, which is usually not what we want.
Example
Data standardization (centering and scaling to unit variance)
scaler
=
StandardScaler
(
)
X_scaled
=
scaler.
fit_transform
(
X
)
(
"After standardization, the data of the first 5 samples:"
)
(
X_scaled
[
:
5
]
)
Apply PCA for dimensionality reduction
We use scikit-learn 's PCA class, which can easily handle all the mathematical computations.
Example
Create a PCA object, specifying reduction to 2 dimensions
pca
=
PCA
(
n_components
=
2
)
Fit the PCA model on the standardized data and transform the data
X_pca
=
pca.
fit_transform
(
X_scaled
)
(
f
"Reduced data shape: {X_pca.shape}"
)
(
f
"Coordinates of the first 5 samples on PC1 and PC2:\n{X_pca[:5]}"
)
View the variance explained ratio of each principal component
(
f
"Principal component variance explained ratio: {pca.explained_variance_ratio_}"
)
(
f
"Cumulative variance explained ratio of the first two principal components: {sum(pca.explained_variance_ratio_):.4f}"
)
Code analysis:
n_components=2: Specify that we want to reduce the data to 2 dimensions.
fit_transform(X_scaled): This method does two things at once:
fit: Based on the input dataX_scaledcompute the parameters needed by PCA (such as principal component directions).transform: Using the computed parameters, transform the dataX_scaledinto the new 2D space.
explained_variance_ratio_: This is a very important attribute. It tells us the proportion ofof the original data variance captured by each principal component. For example, if the output is [0.73, 0.23], it means PC1 retains 73% of the original data's information, PC2 retains 23%, and together they retain 96%. This helps us evaluate the information loss after dimensionality reduction.
Visualize the result
Now that we have the 2D data X_pca, we can easily visualize it with a scatter plot.
Example
Create the visualization chart
plt.
figure
(
figsize
=
(
8
,
6
)
)
Set different colors and markers for each species
colors
=
[
'navy'
,
'turquoise'
,
'darkorange'
]
lw
=
2
Line width
Loop over the three species and plot separately
for
color
,
i
,
target_name
in
zip
(
colors
,
[
0
,
1
,
2
]
,
target_names
)
:
plt.
scatter
(
X_pca
[
y
==
i
,
0
]
,
Select the PC1 coordinates of samples belonging to the current species i
X_pca
[
y
==
i
,
1
]
,
Select the PC2 coordinates of samples belonging to the current species i
color
=
color
,
alpha
=
0.8
,
lw
=
lw
,
label
=
target_name
)
Add chart title and axis labels
plt.
title
(
'2D PCA Visualization of the Iris Dataset'
)
plt.
xlabel
(
f
'First Principal Component (PC1) - Variance Explained Ratio: {pca.explained_variance_ratio_[0]:.2%}'
)
plt.
ylabel
(
f
'Second Principal Component (PC2) - Variance Explained Ratio: {pca.explained_variance_ratio_[1]:.2%}'
)
plt.
legend
(
loc
=
'best'
,
shadow
=
False
,
scatterpoints
=
1
)
plt.
grid
(
True
,
linestyle
=
'--'
,
alpha
=
0.6
)
Display the chart
plt.
tight_layout
(
)
plt.
show
(
)
Interpretation of the visualization results: After running the above code, you will get a 2D scatter plot.
- X-axis (PC1): represents the direction with the largest variance among the original 4 features, and is the most important dimension for distinguishing the data. As can be seen from the figure, it well separates Setosa (Iris setosa) species from the other two species.
- Y-axis (PC2): represents the direction orthogonal to PC1 with the next largest variance, providing additional discriminative information. It helps further distinguish Versicolor (Iris versicolor) and Virginica (Iris virginica), although the two overlap somewhat.
- Conclusion: Through PCA, we successfully projected the 4D data onto a 2D plane and clearly observed the clustering of the three species. Setosa is completely separated, while Versicolor and Virginica partially overlap in the 2D projection, indicating that the first two principal components alone (retaining about 95% of the information) are not enough to perfectly distinguish the latter two species, but their main distribution trends are already very clear.
Further Exploration and Reflection
How to choose the number of principal components (the value of K)?
In real projects, we may not know how many dimensions to reduce to. A common method is to draw a scree plot, which shows the variance explained ratio of each principal component.
Example
First, fit PCA with all principal components
pca_full
=
PCA
(
)
pca_full.
fit
(
X_scaled
)
Draw the scree plot
plt.
figure
(
figsize
=
(
8
,
5
)
)
plt.
plot
(
range
(
1
,
len
(
pca_full.
explained_variance_ratio_
)
1
)
,
pca_full.
explained_variance_ratio_
,
'o-'
,
linewidth
=
2
)
plt.
title
(
'PCA Variance Explained Ratio Scree Plot'
)
plt.
xlabel
(
'Principal Component Number'
)
plt.
ylabel
(
'Variance Explained Ratio'
)
plt.
grid
(
True
,
linestyle
=
'--'
,
alpha
=
0.6
)
plt.
xticks
(
range
(
1
,
len
(
pca_full.
explained_variance_ratio_
)
1
)
)
plt.
tight_layout
(
)
plt.
show
(
)
Draw the cumulative variance explained ratio plot
plt.
figure
(
figsize
=
(
8
,
5
)
)
plt.
plot
(
range
(
1
,
len
(
pca_full.
explained_variance_ratio_
)
1
)
,
np.
cumsum
(
pca_full.
explained_variance_ratio_
)
,
's-'
,
linewidth
=
2
,
color
=
'red'
)
plt.
title
(
'PCA Cumulative Variance Explained Ratio'
)
plt.
xlabel
(
'Number of Principal Components'
)
plt.
ylabel
(
'Cumulative Variance Explained Ratio'
)
plt.
axhline
(
y
=
0.95
,
color
=
'gray'
,
linestyle
=
'--'
,
label
=
'95% Threshold'
)
Common thresholds
plt.
legend
(
)
plt.
grid
(
True
,
linestyle
=
'--'
,
alpha
=
0.6
)
plt.
xticks
(
range
(
1
,
len
(
pca_full.
explained_variance_ratio_
)
1
)
)
plt.
tight_layout
(
)
plt.
show
(
)
How to choose the value of K?
- Look for the elbow point: In the scree plot, look for the point where the declining trend of the variance explained ratio suddenly flattens (the "elbow"); the principal components after it contribute less.
- Set a threshold: In the cumulative variance plot, choose the smallest K value that makes the cumulative explained ratio reach a satisfactory threshold (such as 95% or 99%). From the cumulative plot of the iris data, the first two principal components already explain more than 95% of the variance, so K=2 is a good choice.
Understanding the Meaning of Principal Components
We can also examine theloadings, i.e., the contribution weight of each original feature to the principal component, which helps explain the practical meaning of the principal component.
Example
Get the loading matrix (eigenvectors) of the first two principal components
pca_components
=
pca.
components_
with shape (2, 4)
Display with a DataFrame for clarity
df_components
=
pd.
DataFrame
(
pca_components
,
columns
=
iris.
feature_names
,
index
=
[
'PC1'
,
'PC2'
]
)
(
"Principal Component Loading Matrix (Eigenvectors):"
)
(
df_components
)
Can be visualized with a heatmap
import
seaborn
as
sns
plt.
figure
(
figsize
=
(
8
,
4
)
)
sns.
heatmap
(
df_components
,
annot
=
True
,
cmap
=
'RdBu_r'
,
center
=
0
)
plt.
title
(
'Principal Component Loading Heatmap'
)
plt.
tight_layout
(
)
plt.
show
(
)
Interpreting the loading matrix:
- For PC1, if petal length and petal width have largepositiveweights, while sepal width has largenegativeweights, then PC1 may mainly represent the composite feature of the contrast between petal size and sepal width.
- For PC2, with a different weight pattern, it may represent another combination of features. By analyzing these weights, we can assign some practical biological or business meaning to the abstract principal components.
Summary and Practice Exercises
Summary of Key Points
- What PCA Is: An unsupervised linear dimensionality reduction method that reformulates the data by finding the orthogonal directions (principal components) with the largest variance.
- Core Steps: Standardization -> Compute the covariance matrix -> Compute eigenvalues and eigenvectors -> Select principal components -> Data projection.
- Important Concepts:
- Principal Component: New, uncorrelated feature axes.
- Variance Explained Ratio: A metric that measures the importance of each principal component.
- Loading: A bridge connecting original features and principal components, used to explain the meaning of principal components.
- Main applications: Data visualization, removing noise and redundancy, and serving as a preprocessing step for other models (such as classification and regression) to speed up training.
Hands-on Exercises
To consolidate your knowledge, try the following exercises:
Exercise 1: Explore Different Datasets Try performing PCA visualization on scikit-learn other datasets in (such as digits the handwritten digits dataset or wine the wine dataset). Observe whether the reduced images still preserve the distinction between different classes.
Example
Hint: Load the wine dataset
from
sklearn.
datasets
import
load_wine
wine
=
load_wine
(
)
... Repeat the PCA process
Exercise 2: 3D Visualization Reduce the iris data to 3 dimensions and use the mpl_toolkits.mplot3d library to draw a 3D scatter plot. See whether adding one dimension reduces the overlap between Versicolor and Virginica.
Example
from
mpl_toolkits.
mplot3d
import
Axes3D
pca3
=
PCA
(
n_components
=
3
)
X_pca3
=
pca3.
fit_transform
(
X_scaled
)