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

Unsupervised Learning – Dimensionality Reduction

Unsupervised Learning - Dimensionality Reduction

Imagine you are a photographer organizing a gallery containing millions of high-resolution photos. Each photo consists of millions of pixels (features). If you want to quickly find all the photos of seaside sunsets, directly comparing every pixel of every photo is nearly impossible, because the data volume is too large and too "fat."

In machine learning, we often face a similar dilemma: a dataset has hundreds or thousands of features (dimensions). This not only leads to extremely slow computation (the curse of dimensionality), but may also, because many features are redundant or irrelevant, interfere with our ability to find the true patterns in the data.

Dimensionality reductionis a core technique in unsupervised learning; it is like a data fitness coach that helps us "slim down" high-dimensional data into a low-dimensional space while preserving the most important information as much as possible. Today, we will learn about dimensionality reduction in an accessible yet thorough way.


Basic Concepts of Dimensionality Reduction

What Is Dimensionality Reduction?

Simply put,Dimensionality reduction is the process of reducing the number of features in a dataset. Through some mathematical transformation, it maps data points from the original high-dimensional space into a new, lower-dimensional space.

Why Reduce Dimensionality?

Dimensionality reduction is by no means simply discarding data; its core value lies in:

  1. Visualization: Humans can intuitively understand at most three-dimensional space. By reducing to 2D or 3D, we can plot high-dimensional data and intuitively observe its structure, groupings, and outliers.
  2. Improve efficiency: Fewer data dimensions mean less storage space, faster training, and lower computational costs.
  3. Removing Noise and Redundancy: Many algorithms (especially distance-based ones such as KNN) suffer performance degradation in high-dimensional spaces due to irrelevant or duplicate features. Dimensionality reduction can distill the essence of the data.
  4. Mitigating the Curse of Dimensionality: In high-dimensional spaces, data becomes extremely sparse, making it difficult for many machine learning models to find effective patterns.

Core Idea: Information Preservation

The key challenge of dimensionality reduction is:How can we preserve as much valuable information (such as variance and data structure) as possible in the original data while reducing the dimensionality? Different dimensionality reduction algorithms have different answers to this.


Detailed Explanation of Mainstream Dimensionality Reduction Algorithms

Dimensionality reduction algorithms are mainly divided into two major categories:Linear Dimensionality Reduction and Nonlinear Dimensionality Reduction。

Linear Dimensionality Reduction: Principal Component Analysis

Principal Component Analysis (PCA) is the most classic and most commonly used linear dimensionality reduction method. Its goal is to find a new set of coordinate axes (called "principal components") for the data, such that the variance of the data projected onto these new axes is maximized.

How PCA Works (Four Steps):

  1. Centering: Subtract the mean from each feature so that the center of the data distribution moves to the origin of the coordinate system.
  2. Compute the covariance matrix: This matrix describes the correlations among the various features of the data.
  3. Eigendecomposition: Compute the eigenvalues and eigenvectors of the covariance matrix.Eigenvectors indicate the directions of the new coordinate axes (principal components),Eigenvalues represent the amount of variance of the data in those directions. The larger the eigenvalue, the more information that direction contains.
  4. Select Principal Components: Sort the eigenvalues in descending order, and select the top k k eigenvectors corresponding to the largest eigenvalues, forming a projection matrix.
  5. Data Transformation: Multiply the original data by this projection matrix to obtain new data reduced to k d dimensions.

Example

Import the necessary libraries

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

decomposition

import

PCA

from

sklearn.

datasets

import

load_iris

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

1. Load the classic Iris dataset (4 features)

iris

=

load_iris

(

)

X

=

iris.

data

 

Original data: 150 samples, 4 features

y

=

iris.

target

Labels, used for coloring in visualization

print

(

f

"Original data shape: {X.shape}"

)

 

Output: (150, 4)

2. Create a PCA model, specifying reduction to 2 dimensions

pca

=

PCA

(

n_components

=

2

)

3. Fit the model (compute the principal components) and transform the data

X_pca

=

pca.

fit_transform

(

X

)

print

(

f

"Reduced data shape: {X_pca.shape}"

)

Output: (150, 2)

print

(

f

"Variance ratio explained by each principal component: {pca.explained_variance_ratio_}"

)

The output might look like: [0.9246, 0.0530], indicating that the first principal component preserves 92.5% of the information and the second preserves 5.3%

4. Visualize the dimensionality reduction result

plt.

figure

(

figsize

=

(

8

,

6

)

)

scatter

=

plt.

scatter

(

X_pca

[

:

,

0

]

,

X_pca

[

:

,

1

]

,

c

=

y

,

edgecolor

=

'k'

,

alpha

=

0.7

)

plt.

xlabel

(

'First Principal Component (PC1)'

)

plt.

ylabel

(

'Second Principal Component (PC2)'

)

plt.

title

(

'PCA: Dimensionality Reduction Visualization of the Iris Dataset'

)

plt.

colorbar

(

scatter

,

label

=

'Iris Species'

)

plt.

grid

(

True

,

linestyle

=

'--'

,

alpha

=

0.5

)

plt.

show

(

)

Code Explanation:

Advantages and Disadvantages of PCA

Nonlinear Dimensionality Reduction: t-SNE

When data has a complex nonlinear structure, we need nonlinear dimensionality reduction methods.t-Distributed Stochastic Neighbor Embedding (t-SNE) is currently the most popular visualization-oriented nonlinear dimensionality reduction algorithm.

The Core Idea of t-SNE

t-SNE focuses onpreserving the local structure of the data. It tries to make points that are "similar" (close in distance) in the high-dimensional space also "similar" in the low-dimensional mapping, while points that are "dissimilar" in high dimensions are far apart in low dimensions.

Example

Import the necessary libraries

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

decomposition

import

PCA

from

sklearn.

manifold

import

TSNE

from

sklearn.

datasets

import

make_swiss_roll

Generate Swiss Roll Data

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

1. Generate a nonlinear dataset: the Swiss roll

X_swiss

,

color

=

make_swiss_roll

(

n_samples

=

1000

,

noise

=

0.1

)

print

(

f

"Swiss roll data shape: {X_swiss.shape}"

)

(1000, 3)

2. Attempt dimensionality reduction using PCA (a linear method)

pca

=

PCA

(

n_components

=

2

)

X_swiss_pca

=

pca.

fit_transform

(

X_swiss

)

3. Reduce dimensionality using t-SNE (a nonlinear method)

perplexity is a key parameter of t-SNE, typically ranging between 5 and 50, representing a balanced focus on local/global structure

tsne

=

TSNE

(

n_components

=

2

,

perplexity

=

30

,

random_state

=

42

)

X_swiss_tsne

=

tsne.

fit_transform

(

X_swiss

)

4. Comparative Visualization

fig

,

axes

=

plt.

subplots

(

1

,

2

,

figsize

=

(

15

,

6

)

)

PCA Result

axes

[

0

]

.

scatter

(

X_swiss_pca

[

:

,

0

]

,

X_swiss_pca

[

:

,

1

]

,

c

=

color

,

cmap

=

'viridis'

)

axes

[

0

]

.

set_title

(

'PCA Dimensionality Reduction Result'

)

axes

[

0

]

.

set_xlabel

(

'PC1'

)

axes

[

0

]

.

set_ylabel

(

'PC2'

)

t-SNE Result

sc

=

axes

[

1

]

.

scatter

(

X_swiss_tsne

[

:

,

0

]

,

X_swiss_tsne

[

:

,

1

]

,

c

=

color

,

cmap

=

'viridis'

)

axes

[

1

]

.

set_title

(

't-SNE Dimensionality Reduction Result (perplexity=30)'

)

axes

[

1

]

.

set_xlabel

(

't-SNE 1'

)

axes

[

1

]

.

set_ylabel

(

't-SNE 2'

)

plt.

colorbar

(

sc

,

ax

=

axes

[

1

]

,

label

=

'The "Height" of the Swiss Roll'

)

plt.

tight_layout

(

)

plt.

show

(

)

Code Explanation:

Advantages and Disadvantages of t-SNE

Advantages: Excellent visualization results for complex nonlinear data, clearly revealing cluster structures.

Disadvantages:

  1. Slow Computation Speed; not suitable for large datasets.
  2. Results haverandomness; each run may differ slightly.
  3. Sensitive to hyperparameters,perplexity Requires tuning.
  4. PrimaryFor visualization(2D/3D); the reduced features are usually not used for subsequent machine learning tasks, because the meaning of distances in the low-dimensional space has changed.

How to Choose a Dimensionality Reduction Method and Key Parameters

Algorithm Selection Flowchart

Key Parameter Guidelines

PCA: n_components

Example

Preserve 95% of the Variance Information

pca

=

PCA

(

n_components

=

0.95

)

pca.

fit

(

X

)

print

(

f

"To preserve 95% of the variance, {pca.n_components_} principal components are needed"

)

t-SNE: perplexity


Practical exercises and summary

Hands-On Exercise: Applying Dimensionality Reduction to the MNIST Handwritten Digits Dataset

Example

from

sklearn.

datasets

import

fetch_openml

from

sklearn.

preprocessing

import

StandardScaler

1. Load the MNIST dataset (use only a subset of samples to speed things up)

mnist

=

fetch_openml

(

'mnist_784'

,

version

=

1

,

as_frame

=

False

)

X_mnist

,

y_mnist

=

mnist.

data

[

:

3000

]

/

255.0

,

mnist.

target

[

:

3000

]

Normalize and take the first 3000 samples

print

(

f

"MNIST data shape: {X_mnist.shape}"

)

(3000, 784) -> 784 dimensions!

2. First, use PCA to quickly reduce to 50 dimensions to remove a large amount of noise

pca

=

PCA

(

n_components

=

50

)

X_mnist_pca

=

pca.

fit_transform

(

X_mnist

)

print

(

f

"Shape after PCA: {X_mnist_pca.shape}"

)

3. Then use t-SNE to reduce the 50-dimensional data to 2 dimensions for visualization

tsne

=

TSNE

(

n_components

=

2

,

perplexity

=

40

,

n_iter

=

300

,

random_state

=

42

)

X_mnist_tsne

=

tsne.

fit_transform

(

X_mnist_pca

)

4. Visualization

plt.

figure

(

figsize

=

(

10

,

8

)

)

scatter

=

plt.

scatter

(

X_mnist_tsne

[

:

,

0

]

,

X_mnist_tsne

[

:

,

1

]

,

                      c

=

y_mnist.

astype

(

int

)

,

cmap

=

'tab10'

,

alpha

=

0.6

,

s

=

5

)

plt.

colorbar

(

scatter

,

ticks

=

range

(

10

)

,

label

=

'Handwritten Digits'

)

plt.

title

(

't-SNE Visualization of the MNIST Handwritten Digits Dataset After PCA Preprocessing'

)

plt.

xlabel

(

't-SNE 1'

)

plt.

ylabel

(

't-SNE 2'

)

plt.

grid

(

True

,

linestyle

=

'--'

,

alpha

=

0.3

)

plt.

show

(

)

Exercise Objectives: Observe whether different digits (0-9) form clear clusters on the two-dimensional plane. Try modifying the perplexity parameter (e.g., change it to 10 or 50) to see how the visualization result changes.

Summary and Key Takeaways

The Essence of Dimensionality Reduction: It is information compression and distillation, not simply discarding data. The goal is toexpress as much of the original information as possible using fewer dimensions。

PCA (The King of Linear Methods): Finds the most important linear directions of the data by maximizing variance. Efficient and stable, suitable for preprocessing and removing linear correlations.

t-SNE (A Powerful Visualization Tool): Reveals nonlinear structure by preserving local similarities between data points. The results are striking, but computation is slow and results are random; it is mainly used for exploratory data analysis.

Workflow:

Dimensionality reduction is a key to opening the black box of high-dimensional data.

By mastering PCA and t-SNE, when facing complex data, you will be able to both overlook the overall structure and prepare streamlined, refined features for subsequent machine learning models, greatly improving the efficiency and depth of your data analysis.