1. Dimensionality Reduction: Basic concept of dimensionality reduction
Suppose there is a data set containing 1000 samples and 100 features:
The goal of dimensionality reduction is to transform it into:
Among them:
- : raw data.
- : Data after dimensionality reduction.
- : target dimension.
For example, a 100-dimensional feature can be converted to 2 dimensions in order to plot a scatter plot.
Why is dimensionality reduction needed?
- Visualization: Map high-dimensional data to two-dimensional or three-dimensional space.
- Feature Compression: Reduce the number of features and storage costs.
- Noise Reduction: Reduce the impact of some noise and redundant information.
- Computational Efficiency: Reduce the computational cost of subsequent algorithms.
- Feature Extraction: Discover potential combinations and structures of original features.
It should be noted that dimensionality reduction usually results in the loss of some information, and there is no guarantee that the machine learning model will perform better after dimensionality reduction.
Feature Selection and Feature Extraction
These two concepts need to be distinguished.
Feature Selection (feature selection)
Select a subset from existing features:
[Age, Salary, Height, Weight]
↓
[Age, Salary]
Feature Extraction (feature extraction)
Construct new features through mathematical transformations:
[X1, X2, X3, X4]
↓
[PC1, PC2]
PCA, SVD, t-SNE and UMAP mainly belong to feature extraction or low-dimensional embedding methods.
2. Classification of dimensionality reduction algorithms
| method | Type | main goal |
|---|---|---|
| PCA | linear dimensionality reduction | Keep maximum variance |
| SVD / TruncatedSVD | linear matrix factorization | Low rank approximation, feature compression |
| t-SNE | Nonlinear dimensionality reduction | Preserve local proximity relationships, mainly used for visualization |
| UMAP | Nonlinear manifold learning | Preserve local structure and part of larger-scale structure |
It can be simply understood as:
Dimensionality Reduction
├── Linear Methods
│ ├── PCA
│ └── SVD / TruncatedSVD
│
└── Nonlinear Methods
├── t-SNE
└── UMAP
PCA and SVD are more suitable for general feature dimensionality reduction; t-SNE and UMAP are more commonly used to explore the structure of high-dimensional data.
3. PCA:Principal Component Analysis
PCA (principal component analysis) is the most common linear dimensionality reduction algorithm.
Its core idea is:
looks for the orthogonal directions that explain the greatest variance in the data and projects the data onto these directions.
These directions are called Principal Components (principal components).
Principal Components
Suppose the original data has two highly correlated features:
X1:height
X2:weight
Two features may contain some degree of duplicate information.
PCA can find two new orthogonal directions:
- PC1: The direction that explains the most variance.
- PC2: Orthogonal to PC1 and explains the direction with the most remaining variance.
If PC1 has explained most of the variance, you can consider retaining only PC1.
Mathematical principles of PCA
PCA usually first centralizes the data:
Compute the covariance matrix:
Then find the main directions via eigenvalue decomposition or SVD.
The eigenvalues of the covariance matrix represent the variance explained by the corresponding principal components.
The principal components are ordered from large to small explained variance.
scikit-learn implementation
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X_scaled)
View the results:
X_reduced.shape
pca.components_
pca.explained_variance_
pca.explained_variance_ratio_
pca.singular_values_
Key parameters
| parameters | function |
|---|---|
n_components | Number of principal components retained |
whiten | Whether to scale the whitened principal components |
svd_solver | SVD solution method |
random_state | Controlling part of the stochastic solution process |
For example:
PCA(n_components=5)
Indicates that the first 5 principal components are retained.
Dimensions can also be determined based on the cumulative explained variance:
PCA(n_components=0.95, svd_solver="full")
Indicates the retention of principal components sufficient to explain at least 95% of the total variance.
PCA Is standardization required?
PCA itself will center the features, but will not automatically normalize each feature to the same scale.
For example:
Age: 20~60
Income: 3000~30000
Without normalization, Income may dominate the principal component direction.
When different features have different units and numerical scales, it is usually recommended to use StandardScaler first.
However, if the variance of the original features itself has practical significance, only centralization can be performed.
Limitations of PCA
- Only linear projections can be learned.
- A large explained variance does not necessarily mean it contains the most predictive information.
- Sensitive to outliers.
- Principal components are usually a combination of multiple original features and may be less interpretable.
4. Explained Variance: explained variance
Explained variance is one of the most important metrics for understanding PCA.
Explained Variance Ratio
Definition:
Among them, represents the variance corresponding to the th principal component.
For example:
PC1: 60%
PC2: 25%
PC3: 10%
PC4: 5%
PC1 and PC2 are reserved:
Indicates that the 2D PCA retains 85% of the total variance of the original data.
Calculate explained variance
pca = PCA()
pca.fit(X_scaled)
ratios = pca.explained_variance_ratio_
cumulative = ratios.cumsum()
Scree Plot
Scree Plot displays the proportion of explained variance for each principal component.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(
range(1, len(ratios) + 1),
ratios,
marker="o",
)
ax.set(
xlabel="Principal Component",
ylabel="Explained Variance Ratio",
title="Scree Plot",
)
plt.show()
Cumulative Explained Variance
The cumulative explained variance is used to determine how many principal components need to be retained.
import numpy as np
fig, ax = plt.subplots()
ax.plot(
range(1, len(cumulative) + 1),
cumulative,
marker="o",
)
ax.axhline(0.95, linestyle="--", color="red")
ax.set(
xlabel="Number of Components",
ylabel="Cumulative Explained Variance",
)
plt.show()
Consider when choosing dimensions:
- Preserve 90% or 95% of the variance.
- The inflection point of Scree Plot.
- Validation set performance of subsequent models.
- Actual calculated costs.
95% is just a common empirical threshold, not a universal optimal standard.
If the purpose is visualization, it is usually straightforward to select 2 or 3 principal components and report the corresponding proportion of explained variance explicitly.
5. SVD:Singular Value Decomposition
SVD (singular value decomposition) is a basic matrix decomposition method and an important mathematical basis for PCA.
For matrices:
can be broken down into:
Among them:
- : left singular vector matrix.
- : Singular value diagonal matrix.
- : transpose of the right singular vector matrix.
Singular values are usually sorted from largest to smallest.
SVD and dimensionality reduction
If only the largest K singular values and corresponding vectors are retained:
An approximate representation of the original matrix with rank K is obtained.
This is called Low-rank Approximation (low rank approximation).
NumPy / SciPy implementation
import numpy as np
U, S, Vt = np.linalg.svd(
X,
full_matrices=False,
)
Keep the first two singular values:
k = 2
X_approx = (
U[:, :k]
@ np.diag(S[:k])
@ Vt[:k, :]
)
X_approx is a low-rank approximation to the original matrix, not an eigenmatrix of dimensions K.
If you need a low-dimensional representation, you can use:
X_reduced = U[:, :k] * S[:k]
TruncatedSVD
scikit-learn provides TruncatedSVD:
from sklearn.decomposition import TruncatedSVD
svd = TruncatedSVD(
n_components=50,
random_state=42,
)
X_reduced = svd.fit_transform(X)
The difference between PCA and TruncatedSVD
| Contrast | PCA | TruncatedSVD |
|---|---|---|
| Whether to centralize data | Yes | No |
| Whether linear dimensionality reduction | Yes | Yes |
| Is it suitable for sparse matrices? | Supported by some solvers, but may be subject to centralization constraints | usually more suitable |
| Common uses | Numerical feature dimensionality reduction | High-dimensional sparse data compression |
| main goal | Preserve data variance | low rank matrix approximation |
PCA can usually be achieved by doing SVD on centralized data.
TruncatedSVD does not require centralization, so it is particularly suitable for sparse data such as TF-IDF and word frequency matrices.
Latent Semantic Analysis(LSA)
In text processing, common combinations are:
Text
↓
TF-IDF
↓
TruncatedSVD
↓
Low-dimensional Features
For example:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(
TfidfVectorizer(),
TruncatedSVD(
n_components=50,
random_state=42,
),
)
X_reduced = pipeline.fit_transform(documents)
This type of method is often called Latent Semantic Analysis.
6. t-SNE:t-distributed Stochastic Neighbor Embedding
t-SNE is a nonlinear dimensionality reduction method mainly used to map high-dimensional data to two-dimensional or three-dimensional space.
It focuses particularly on:
Samples that are similar in high-dimensional space should also be as close as possible in low-dimensional space.
core idea
t-SNE first establishes a similarity probability distribution based on the distance between high-dimensional samples.
Then the corresponding similarity distribution is established in the low-dimensional space, and the difference between the two is reduced through optimization.
The target usually uses KL Divergence:
Among them:
- : Sample similarity distribution in high-dimensional space.
- : Sample similarity distribution in low-dimensional space.
t-SNE mainly preserves local neighborhood structure rather than all global distances.
scikit-learn implementation
from sklearn.manifold import TSNE
tsne = TSNE(
n_components=2,
perplexity=30,
learning_rate="auto",
random_state=42,
)
X_2d = tsne.fit_transform(X_scaled)
Key hyperparameters
| parameters | function |
|---|---|
n_components | target dimension |
perplexity | Control the effective size of local neighborhoods |
learning_rate | Learning rate for optimization process |
early_exaggeration | Initial degree of separation between clusters |
max_iter | Maximum number of optimization iterations |
random_state | Controlling randomness |
Perplexity
This is one of the most important parameters of t-SNE.
- Smaller: pay more attention to local proximity relationships.
- Larger: Consider a larger range of neighborhood structures.
Often multiple values are tried, for example:
perplexity = 5
perplexity = 30
perplexity = 50
perplexity must be less than the sample size.
Limitations of t-SNE
- Mainly suitable for visualization, not first choice for general feature compression.
- Computational costs may be higher.
- Different random initialization or parameters may produce different results.
- The distance between clusters in a two-dimensional graph cannot directly represent the distance in the original high-dimensional space.
- The size and density of clusters in the plot do not necessarily reflect the actual scale of the original data.
- scikit-learn's
TSNEdoes not provide the regulartransform()method for new samples.
PCA + t-SNE
If the original feature dimension is very high, it is usually recommended to use PCA to reduce it to a lower dimension, and then perform t-SNE.
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
X_pca = PCA(
n_components=50,
random_state=42,
).fit_transform(X_scaled)
X_tsne = TSNE(
n_components=2,
perplexity=30,
random_state=42,
).fit_transform(X_pca)
It is required that the number of original features and samples is sufficient to support 50 principal components.
Executing PCA first can reduce the computational cost and reduce the impact of some high-dimensional noise.
7. UMAP:Uniform Manifold Approximation and Projection
UMAP is a nonlinear dimensionality reduction method based on manifold learning (Manifold Learning).
Like t-SNE, it can be used for high-dimensional data visualization, but can also be used for more general low-dimensional feature representation.
core idea
The basic process of UMAP:
- Find the nearest neighbors of each sample in high-dimensional space.
- Build a weighted graph structure based on neighborhood relationships.
- Convert these neighborhood relationships into low-dimensional embeddings.
- Optimize low-dimensional positions to preserve the original neighborhood structure as much as possible.
UMAP will comprehensively consider the local neighborhood structure and the overall structure within a certain range, but does not guarantee that all global distances will be strictly preserved.
Installation
UMAP does not belong to the scikit-learn core library and needs to be installed separately:
pip install umap-learn
Basic usage
import umap
reducer = umap.UMAP(
n_components=2,
n_neighbors=15,
min_dist=0.1,
metric="euclidean",
random_state=42,
)
X_2d = reducer.fit_transform(X_scaled)
Key hyperparameters
| parameters | function |
|---|---|
n_components | Output dimensions |
n_neighbors | local neighborhood size |
min_dist | The closeness of points in low-dimensional space |
metric | Distance measure of original space |
random_state | Controlling randomness |
n_neighbors
Control the balance between local and overall structures.
- Smaller: pays more attention to local structure.
- Larger: Pay more attention to larger-scale data structures.
min_dist
Controls how tightly points can be clustered in a low-dimensional representation.
- Smaller: Low-dimensional clusters are generally more compact.
- Larger: The distribution is generally more spread out.
But the real number of clusters cannot be judged solely by the visual separation produced by min_dist.
Transform of new data
Unlike t-SNE of scikit-learn, UMAP generally supports mapping new samples to existing low-dimensional spaces:
reducer = umap.UMAP(
n_components=10,
random_state=42,
)
X_train_reduced = reducer.fit_transform(X_train)
X_test_reduced = reducer.transform(X_test)
This enables UMAP to be used for feature transformation for some subsequent machine learning tasks in addition to visualization.
Note: The low-dimensional mapping of UMAP is approximate and will be affected by training data, parameters and randomness.
8. Comparison of PCA, SVD, t-SNE and UMAP
| Features | PCA | TruncatedSVD | t-SNE | UMAP |
|---|---|---|---|---|
| Type | Linear | Linear | nonlinear | nonlinear |
| main goal | Maximize retained variance | low rank approximation | Preserve local neighborhood | Preserve neighborhood topology |
| Suitable for visualization | Yes | Yes | very suitable | very suitable |
| Suitable for general feature compression | Yes | Yes | Usually not recommended | can try |
| Whether to support new data transform | Yes | Yes | sklearn implementation does not support | Usually supported |
| explained variance | Yes | There are relevant indicators | No direct corresponding indicator | No direct corresponding indicator |
| Core parameters | n_components | n_components | perplexity | n_neighbors、min_dist |
Select suggestions
PCA
Suitable for:
- Feature compression of general numerical data.
- Remove some linear redundancy.
- Variance needs to be explained.
- Use dimensionality reduction features in subsequent models.
TruncatedSVD
Suitable for:
- High-dimensional sparse matrix.
- TF-IDF and text features.
- Matrix low-rank approximation.
t-SNE
Suitable for:
- Two-dimensional visualization of high-dimensional data.
- Exploring local sample structure.
- Make auxiliary observations of cluster structures.
UMAP
Suitable for:
- High-dimensional data visualization.
- Nonlinear low-dimensional feature representation.
- Want to apply the learned dimensionality reduction map to new samples.
9. Dimensionality reduction visualization
The most common use of dimensionality reduction is to convert high-dimensional data into two-dimensional data and then display it using Scatter Plot.
PCA Visualization
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
pca = PCA(n_components=2)
X_2d = pca.fit_transform(X_scaled)
fig, ax = plt.subplots()
scatter = ax.scatter(
X_2d[:, 0],
X_2d[:, 1],
c=y,
cmap="tab10",
alpha=0.7,
)
ax.set(
xlabel="PC1",
ylabel="PC2",
title="PCA Visualization",
)
plt.show()
If the data does not have real labels, you can use a uniform color, or use existing cluster labels for coloring.
t-SNE Visualization
from sklearn.manifold import TSNE
X_2d = TSNE(
n_components=2,
random_state=42,
).fit_transform(X_scaled)
plt.scatter(
X_2d[:, 0],
X_2d[:, 1],
c=y,
cmap="tab10",
s=15,
)
plt.title("t-SNE Visualization")
plt.show()
UMAP Visualization
import umap
X_2d = umap.UMAP(
n_components=2,
random_state=42,
).fit_transform(X_scaled)
plt.scatter(
X_2d[:, 0],
X_2d[:, 1],
c=y,
cmap="tab10",
s=15,
)
plt.title("UMAP Visualization")
plt.show()
Interpretation of visualization results
Different dimensionality reduction algorithms may produce significantly different two-dimensional structures for the same data.
Especially t-SNE and UMAP:
- Local proximity between points is usually more interesting than absolute coordinates.
- The presence of clearly separated point groups in the graph does not necessarily mean that equally clear clusters exist in the original space.
- Different visualization results may be produced under different parameters.
- The predictive power of a classification model cannot be judged solely on the basis of two-dimensional projections.
10. The relationship between dimensionality reduction and clustering
Dimensionality reduction is often used with clustering:
High-dimensional Data
↓
Preprocessing
↓
PCA / UMAP
↓
K-Means / DBSCAN
↓
Cluster Analysis
For example:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
pipeline = make_pipeline(
StandardScaler(),
PCA(n_components=10),
KMeans(
n_clusters=3,
n_init=10,
random_state=42,
),
)
labels = pipeline.fit_predict(X)
This approach may reduce the computational cost of clustering and reduce the impact of some redundant features.
But please note:
The cluster seen on a 2D UMAP or t-SNE plot does not necessarily represent a reliable clustering structure in the original data.
If the main purpose is clustering, you should usually compare:
- Clustering results on original standardized features.
- PCA clustering result after dimensionality reduction.
- UMAP clustering result after dimensionality reduction.
And evaluate it based on stability, business significance and appropriate clustering indicators.
11. Dimensionality reduction and supervised learning
Dimensionality reduction can also be used as a machine learning preprocessing step.
For example:
Features
↓
StandardScaler
↓
PCA
↓
LogisticRegression / SVM
By Pipeline:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([
("scaler", StandardScaler()),
("pca", PCA(n_components=10)),
("model", LogisticRegression(max_iter=1000)),
])
pipeline.fit(X_train, y_train)
y_pred = pipeline.predict(X_test)
Avoid Data Leakage
Wrong approach:
# Error: Fit PCA using complete data first
X_reduced = PCA(n_components=10).fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_reduced,
y,
)
Correct approach:
- First split the training set and test set.
- Fit StandardScaler, PCA only on the training set.
- Apply the trained transformations to the test set.
- Use the training set to train a predictive model.
- Evaluate on the test set.
Pipeline can automatically manage this type of conversion sequence.
Will PCA definitely improve the model effect?
uncertain.
PCA determines which feature directions to retain based on the variance rather than the target variable.
A principal component with a small variance may be important for classification or regression.
Therefore, cross-validation should be used to compare model performance before and after dimensionality reduction, rather than deciding whether to adopt PCA based solely on Explained Variance Ratio.
12. Complete example: Compare PCA, t-SNE and UMAP
High-dimensional visualization using the Digits dataset of scikit-learn.
The dataset contains images of handwritten digits, each with 64 pixel features.
import matplotlib.pyplot as plt
import umap
from sklearn.datasets import load_digits
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
# 1. Load data
digits = load_digits()
X = digits.data
y = digits.target
# 2. Standardization
X_scaled = StandardScaler().fit_transform(X)
# 3. PCA
X_pca = PCA(
n_components=2,
).fit_transform(X_scaled)
# 4. t-SNE
X_tsne = TSNE(
n_components=2,
perplexity=30,
random_state=42,
).fit_transform(X_scaled)
# 5. UMAP
X_umap = umap.UMAP(
n_components=2,
n_neighbors=15,
min_dist=0.1,
random_state=42,
).fit_transform(X_scaled)
# 6. Visual comparison
fig, axes = plt.subplots(
1,
3,
figsize=(15, 4),
)
results = {
"PCA": X_pca,
"t-SNE": X_tsne,
"UMAP": X_umap,
}
for ax, (name, values) in zip(axes, results.items()):
ax.scatter(
values[:, 0],
values[:, 1],
c=y,
cmap="tab10",
s=8,
alpha=0.7,
)
ax.set_title(name)
plt.tight_layout()
plt.show()
This example allows for visual comparison:
- Linear projection of PCA.
- t-SNE represents the local neighborhood.
- UMAP represents the neighborhood structure.
But you cannot conclude that a certain dimensionality reduction algorithm is better in all machine learning tasks just based on the degree of separation of different numbers in a two-dimensional graph.
13. FAQ
1. Are PCA and SVD two completely different algorithms?
no.
SVD is a general matrix factorization method, while PCA is a dimensionality reduction method with explicit statistical goals.
PCA can usually be achieved by executing SVD on centralized data.
Therefore, the two are very closely related mathematically, but their application goals are not exactly the same.
2. Is the more principal components of PCA the better?
no.
Retaining more principal components generally retains more variance information, but also increases the number of features and subsequent computational cost.
Explained Variance should be selected in conjunction with model performance and business goals.
3. Which is better, t-SNE or UMAP?
There are no absolute answers.
- t-SNE is generally suitable for exploring local neighborhood structures.
- UMAP is suitable for visualization and can also be used for certain nonlinear feature transformations.
- PCA is better suited for tasks that require explained variance and stable linear mapping.
Different data sets and parameters may yield different results.
4. Why are the inter-cluster distances in the t-SNE / UMAP graph untrustworthy?
Because the algorithm mainly optimizes the neighborhood structure, it does not require that the low-dimensional space completely retains all geometric distances of the high-dimensional data.
Therefore the absolute distances, cluster sizes and densities of the 2D graph cannot be interpreted directly in terms of the original space.
5. Is dimensionality reduction equivalent to denoising?
Not equal to.
In some data sets, the smaller principal components may contain mainly noise; in other data sets, they may also contain meaningful information.
Dimensionality reduction may reduce noise, but may also lose valid signals.
Summary
| Knowledge points | importance |
|---|---|
| Dimensionality Reduction | core |
| Feature Selection vs Feature Extraction | important |
| PCA / Principal Components | core |
| Explained Variance Ratio | core |
| Scree Plot / Cumulative Variance | core |
| SVD / Low-rank Approximation | core |
| TruncatedSVD / Sparse Data | important |
| t-SNE / Perplexity | important |
| UMAP / n_neighbors / min_dist | important |
| Visualization / Interpretation | core |
| Feature Scaling | core |
| Data Leakage / Pipeline | core |
| Dimensionality Reduction + Clustering | important |
The five most important concepts of dimensionality reduction:
- PCA: Find the orthogonal principal components that maximize the explained data variance to achieve linear dimensionality reduction.
- SVD: Feature compression is achieved through matrix decomposition and low-rank approximation, which is an important mathematical basis for PCA.
- Explained Variance: Measures how much variance information PCA retains in the original data, but it does not equal how much prediction information is retained.
- t-SNE/UMAP: Preserve part of the neighborhood structure of high-dimensional data through nonlinear mapping, especially suitable for visualization.
- Generalization & Interpretation: Dimensionality reduction should be fitted on the training data, and the results should be interpreted carefully in combination with the model performance and the original data structure.