Runoob Tutorial ArchiveEnglish

PCA for data dimensionality reduction and visualization

PCA for data dimensionality reduction and visualization

Implement PCA (Principal Component Analysis) yourself without using sklearn. Intuitively see the role of eigenvalues and eigenvectors in "compressing information and retaining major differences."

After learning this case study, you will understand: PCA is about finding the direction where data is most "spread out," using fewer dimensions to retain as much information as possible.


Real-life introduction

**Describe the shape of a fish to a friend

You don't need to precisely describe the three-dimensional coordinates of every point on the fish. You just need to say: "It's roughly this long, this wide, and this shape." You captured the most critical differences with the fewest pieces of data.

PCA does exactly this: it finds the most important directions from high-dimensional data, discards unimportant details, and describes the same data with fewer numbers.


Intuitive understanding

Suppose we have 300 three-dimensional data points. They are not uniformly distributed—most points lie along a certain diagonal line, and only a few points deviate from this line.

What does this mean? It means we actually don't need three-dimensional coordinates. Two dimensions are enough—one along the diagonal line and one perpendicular to the diagonal line. The third dimension's data in the perpendicular direction hardly changes and can be discarded.

**

Centering

**

Covariance matrix

**

Eigenvalue Decomposition

**

Projection Dimensionality Reduction

The larger the eigenvalue, the more "spread out" the data is in that direction—meaning that direction is more important.


Mathematical Definition

PCA Algorithm Steps

[ \begin{aligned} \text{1. Centering:}&\quad X_c = X - \bar{X} \ \text{2. Covariance Matrix:}&\quad \Sigma = \frac{1}{n-1}X_c^T X_c \ \text{3. Eigenvalue Decomposition:}&\quad \Sigma = V \Lambda V^T \ \text{4. Select the first k eigenvectors:}&\quad V_k = [v_1, v_2, ..., v_k] \ \text{5. Projection:}&\quad X_{\text{reduced}} = X_c \cdot V_k \end{aligned} ]

Explain the variance ratio

[ Explain the ratioi = \frac{\lambda_i}{\sum{j=1}^{d} \lambda_j} ]

Where (\lambda_i) is the i-th largest eigenvalue. This ratio tells you: how much of the total variance the i-th principal component "contributes".


Python hands-on practice

Construct a 3D dataset that is actually distributed along a certain direction, and manually reduce it to 2D using PCA.

Example

import

numpy

as

np

np.

random

.

seed

(

42

)

1. Construct 3D data, the data is mainly distributed along a certain direction

n

=

300

base

=

np.

random

.

randn

(

n

,

1

)

X

=

np.

hstack

(

[

base *

3

random

.

randn

(

n

,

1

)

0.3

,

 

x1 column

base *

1.5

random

.

randn

(

n

,

1

)

0.3

,

 

x2 columns

np.

random

.

randn

(

n

,

1

)

0.2

,

             

3 columns (noise)

]

)

print

(

"RUNOOB original data shape:"

,

X.

shape

,

     

"(300 samples, 3 dimensions per sample)"

)

2. Handwritten PCA (Four Steps)

def

pca

(

X

,

n_components

=

2

)

:

   

Step 1: Centering - shift the mean of the data to 0

X_centered

=

X - X.mean

mean

(

axis

=

0

)

   

Step two: Covariance matrix—find the relationship between all pairs of variables

cov

=

np.

cov

(

X_centered

,

rowvar

=

False

)

   

Step 3: Feature decomposition—eigh is more stable for symmetric matrices

eigvals

,

eigvecs

=

np.

linalg

.

eigh

(

cov

)

   

Sort by eigenvalues from largest to smallest

order

=

np.

argsort

(

eigvals

)

[

::-

1

]

eigvals

=

eigvals

[

order

]

eigvecs

=

eigvecs

[

:

,

order

]

   

Step four: take the first k feature vectors and project

components

=

eigvecs

[

:

,

:n_components

]

    X_reduced

=

X_centered

@

components

   

Calculate the proportion of variance explained by each principal component

explained_ratio

=

eigvals

[

:n_components

]

/ eigvals.

sum

(

)

   

return

X_reduced

,

eigvals

,

explained_ratio

X_reduced

,

eigvals

,

explained_ratio

=

pca

(

X

,

n_components

=

2

)

print

(

"\nRUNOOB three eigenvalues (variance size):"

,

np.

round

(

eigvals

,

3

)

)

print

(

"Proportion of variance explained by the first 2 principal components:"

,

      np.

round

(

explained_ratio

,

3

)

)

print

(

"Cumulative retained information:"

,

     

round

(

explained_ratio.

sum

(

)

100

,

1

)

,

"%"

)

print

(

"Data shape after dimensionality reduction:"

,

X_reduced.

shape

,

     

"(Reduced from 3D to 2D)"

)

3. Key observation: The third eigenvalue is very small

print

(

f

"\nRUNOOB's third eigenvalue is only {eigvals[2]:.4f},"

      f

"much smaller than the first two ({eigvals[0]:.2f}, {eigvals[1]:.2f})"

)

print

(

"Indicate that the third dimension has almost no information content—it can be safely discarded!"

)

Original prompt (Chinese, left untranslated)



RUNOOB 原始数据形状: (300, 3) (300 个样本,每个样本 3 维)



RUNOOB 三个特征值 (方差大小): [9.569 2.267 0.04 ]

前 2 个主成分解释的方差比例: [0.806 0.191]

累计保留信息: 99.7 %

降维后数据形状: (300, 2) (从 3 维降到了 2 维)



RUNOOB 第三个特征值只有 0.0404,远小于前两个 (9.57, 2.27)

说明第三维几乎没有信息量——可以安全丢掉!


Application scenarios in AI

AI scenarios How to use PCA
Data visualization Reduce high-dimensional data (such as 768-dimensional word vectors) to 2 dimensions and visually observe the data distribution using a scatter plot
Feature dimensionality reduction Before training the model, remove redundant features to reduce computation while lowering the risk of overfitting
Noise filtering Retain only the principal components with large variance and discard those with small variance (which are often noise)
Image compression Approximate facial images using a combination of a few "eigenfaces"
Recommendation system Decompose the user-item rating matrix using SVD (the matrix version of PCA) to discover hidden user preference patterns