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:
- 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.
- Improve efficiency: Fewer data dimensions mean less storage space, faster training, and lower computational costs.
- 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.
- 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):
- Centering: Subtract the mean from each feature so that the center of the data distribution moves to the origin of the coordinate system.
- Compute the covariance matrix: This matrix describes the correlations among the various features of the data.
- 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.
- Select Principal Components: Sort the eigenvalues in descending order, and select the top
kk eigenvectors corresponding to the largest eigenvalues, forming a projection matrix. - Data Transformation: Multiply the original data by this projection matrix to obtain new data reduced to
kd 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
(
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
)
(
f
"Reduced data shape: {X_pca.shape}"
)
Output: (150, 2)
(
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:
PCA(n_components=2): Initializes the model,n_componentswith the parameter specifying the number of principal components to retain (i.e., the dimensionality after reduction).fit_transform(X): This is a combined method that first computes the mean and principal component directions of the data (fit), and then immediately transforms the data into the new space (transform)。explained_variance_ratio_: This is a very important attribute of PCA; it tells us how much variance (information) of the original data each new feature (principal component) retains. This helps us decide how many principal components it is appropriate to select.

Advantages and Disadvantages of PCA
- Advantages: Computationally efficient, with clear principles, and effectively removes linear correlations.
- Disadvantages: It is a linear method that assumes the principal components of the data are linear. For nonlinear manifold data such as the "Swiss roll," PCA does not perform well.
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
)
(
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:
perplexityParameter: It can be understood as how many neighbors are considered for each point. A small value focuses more on local structure, while a large value focuses more on global structure. It is the most important parameter to tune in t-SNE.random_state: Ensures reproducible results, because the optimization process of t-SNE is stochastic.- From the visualization results, we can clearly see that PCA "flattened" the Swiss roll, losing its nonlinear curled structure; while t-SNE better unfolded the roll on the two-dimensional plane, preserving the local adjacency relationships of the data.

Advantages and Disadvantages of t-SNE
Advantages: Excellent visualization results for complex nonlinear data, clearly revealing cluster structures.
Disadvantages:
- Slow Computation Speed; not suitable for large datasets.
- Results haverandomness; each run may differ slightly.
- Sensitive to hyperparameters,
perplexityRequires tuning. - 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
- Can be set to an integer (such as 2) to specify a specific dimension.
- Can be set to
0 < n < 1a decimal (such as 0.95), indicating that thecumulative variance contribution ratereaches that threshold with the fewest principal components.
Example
Preserve 95% of the Variance Information
pca
=
PCA
(
n_components
=
0.95
)
pca.
fit
(
X
)
(
f
"To preserve 95% of the variance, {pca.n_components_} principal components are needed"
)
t-SNE: perplexity
- Typical values range from 5 to 50.
- For small datasets (<<100 samples), a smaller value is recommended.
- The optimal value is usually close to the number of "neighbors" of each point in the data. It needs to be selected by observing the visualization results through experimentation.
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
(
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
)
(
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:
- Clarify the Goal: Is it for visualization, or for feeding more refined features into a downstream model?
- Data exploration: First visualize a portion of the data to get an initial sense of whether it is linear or nonlinear.
- Method Experimentation: Choose an algorithm based on the goal and data structure, and adjust the key parameters.
- Evaluate the Results: Evaluate the dimensionality reduction results through visualization, information retention rate, or downstream task performance.
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.