Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Machine Learning – PCA Visualization Case

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:


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:

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']

print

(

f

"Dataset shape: {X.shape}"

)

print

(

f

"Feature names: {iris.feature_names}"

)

print

(

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

)

print

(

"After standardization, the data of the first 5 samples:"

)

print

(

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

)

print

(

f

"Reduced data shape: {X_pca.shape}"

)

print

(

f

"Coordinates of the first 5 samples on PC1 and PC2:\n{X_pca[:5]}"

)

View the variance explained ratio of each principal component

print

(

f

"Principal component variance explained ratio: {pca.explained_variance_ratio_}"

)

print

(

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:

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.


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?

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'

]

)

print

(

"Principal Component Loading Matrix (Eigenvectors):"

)

print

(

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:


Summary and Practice Exercises

Summary of Key Points

- **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.

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

)

... Create a 3D figure for plotting