CertNote/ Commute Study Notes
Roadmap
KOEN
CLF-C02 · FoundationalCloud Practitioner - Foundational
DVA-C02 · AssociateDeveloper - Associate
SAA-C03 · AssociateSolutions Architect - Associate
SOA-C02 · AssociateCloudOps Engineer - Associate
SAP-C02 · ProfessionalSolutions Architect - Professional
DOP-C02 · ProfessionalDevOps Engineer - Professional
Linux Master 2 · 2급KAIT Linux Master - Level 2
SCS-C03 · SpecialtySecurity - Specialty
Linux Master 1 · 1급KAIT Linux Master - Level 1
MLA-C01 · AssociateMachine Learning Engineer - Associate
AIF-C01 · FoundationalAI Practitioner - Foundational
DEA-C01 · AssociateData Engineer - Associate
MLS-C01 · SpecialtyMachine Learning - Specialty
  • Week 1
    • 1.The ML Lifecycle (from a Specialty Perspective)
    • 2.Data Storage for ML: S3, EFS, FSx for Lustre, and Data Formats
    • 3.Data Ingestion: Kinesis, Glue, Batch vs. Streaming
    • 4.Data Labeling: SageMaker Ground Truth, Active Learning, Label Quality
    • 5.Week 1 Comprehensive Review: ML Overview & Data Engineering 1
  • Week 2
  • Week 3
  • Week 4
    • 1.Dimensionality Reduction: PCA, t-SNE, and the Curse of Dimensionality
    • 2.Feature Selection: Filter, Wrapper and Embedded Methods, Importance, and Multicollinearity
    • 3.Data Visualization: Distributions, Correlations, QuickSight, and Drawing Insights
    • 4.Handling Class Imbalance: Oversampling, Undersampling, SMOTE, Class Weights, Evaluation
    • 5.Week 4 Comprehensive Review: Dimensionality, Feature Selection, Visualization, Imbalance
  • Week 5
  • Week 6
  • Week 7
  • Week 8
  • Week 9
  • Week 10
  • Week 11
  • Week 12
SQLD · 개발자SQL Developer (SQLD)

© CertNote · 주간랩스

  • About
  • Changelog
  • Contact
  • Terms
  • Privacy
← MLS-C01/Week 4/Day 1

Based on the MLS-C01 exam guide·Report an error

MLS-C01· AssociateWeek 4 · Day 1~31 min read

Day 1 - Dimensionality Reduction: PCA, t-SNE, and the Curse of Dimensionality

📌 Key Takeaways

  • Curse of dimensionality: as dimensions grow, data becomes sparse and the distances between points become homogeneous, so distance-based algorithms such as KNN and K-means break down.
  • PCA is a linear, unsupervised technique that finds orthogonal axes preserving as much variance as possible. Standardization before applying it is mandatory.
  • Choose the number of principal components k by cumulative explained variance (e.g., n_components=0.95) or the elbow of the scree plot.
  • t-SNE is a nonlinear technique that preserves local structure and is for visualization only. It cannot transform new data, and distances between clusters are meaningless.
  • For large datasets use SageMaker's built-in PCA, and when the number of features is very large choose algorithm_mode=randomized.

The Curse of Dimensionality

Week 4 moves into the second pillar of exploratory data analysis (EDA): handling high-dimensional data. As features multiply, a model seems to have more information, but as dimensions grow, the volume of space that the same number of samples must fill grows exponentially. As a result, data points drift apart from one another and distance-based measures lose their discriminating power.

SymptomDescription
Data sparsityAs dimensions grow, the number of samples needed for the same density grows exponentially
Distance homogenizationThe distances of all point pairs become similar, so telling nearest from farthest becomes meaningless
Overfitting riskWhen the number of features approaches the number of samples, the model memorizes noise
Computational costTraining and inference costs grow in proportion to (or with the square of) the dimension
[Low dimension (2D)]             [High dimension (d ≫ 1)]
    ●                              ●    ●    ●
       ● ← close                     ●    ●    ●
              ● ← far              ●    ●    ●
                                   All pairwise distances are similar
  Nearest / farthest distinguishable   d_max / d_min → 1
  → KNN·K-means work normally        → the notion of a neighbor collapses

Vulnerability to High Dimensions, by Algorithm

AlgorithmVulnerabilityReason
KNNVery highDecides neighbors by Euclidean distance
K-meansVery highAssigns clusters by distance to the centroid
SVM (RBF kernel)HighKernel values depend on distances between samples
Linear/logistic regressionMediumWhen the number of features approaches the number of samples, coefficients become unstable and the model overfits
Decision Tree / Random ForestMedium to lowLooks at one feature at a time, but many irrelevant features degrade split quality
Naive BayesLowMultiplies per-feature conditional probabilities, so it does not use a notion of distance

Algorithms that depend on Euclidean distance, such as KNN and K-means, are especially vulnerable in high dimensions.

The mathematical core of the curse of dimensionality is that, in a high-dimensional unit hypercube, the ratio of the maximum to the minimum distance between two random points converges to 1. In other words, the "nearest neighbor" and the "farthest neighbor" become effectively the same. For this reason, dimensionality reduction does not merely cut computation; it also restores the space in which distance-based learning works.

PCA: Principal Component Analysis

PCA is a linear dimensionality-reduction technique that finds orthogonal axes (principal components) that preserve as much variance as possible and projects the data onto those axes.

  • The first principal component (PC1) is the direction of greatest variance
  • The second principal component (PC2) is orthogonal to PC1 and has the greatest remaining variance
  • Keep only the top k principal components to reduce dimensions from d → k

Key precondition: always standardize before PCA. Because it is variance-based, variables with large scales dominate the principal components.

Preprocessing Requirements Before PCA

ItemRequirementReason
ScaleStandardization requiredIt is variance-based, so large-scale variables monopolize the principal components
Missing valuesImpute beforehandMissing values cannot enter the covariance computation
CategoricalEncoding required (one-hot, etc.)It accepts only numeric input
TargetNot usedPCA is an unsupervised transform
Fit scopeFit on the training set onlyFitting with test statistics causes leakage
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
 
X_scaled = StandardScaler().fit_transform(X_train)
 
pca = PCA(n_components=0.95)   # minimum number of components explaining 95% of the variance
X_reduced = pca.fit_transform(X_scaled)
 
print("Selected number of components:", pca.n_components_)
print("Explained variance ratio:", pca.explained_variance_ratio_.cumsum())

If you pass a 0–1 ratio to n_components instead of an integer, it automatically selects "the minimum number of principal components whose cumulative explained variance exceeds that ratio."

How to Choose the Number of Components k

MethodWhat it doesCriterion
Target explained varianceMinimum k whose cumulative explained variance exceeds the targetSpecify the ratio directly, as in n_components=0.95
Scree plot elbowThe point where the eigenvalue (explained variance) drops sharplyThe elbow where the curve bends
Downstream model performanceCompare cross-validation scores while varying kCostly, but the most practical

Choose an appropriate k from the scree plot or the elbow of the cumulative explained variance curve.

PCA is equivalent to an eigendecomposition of the data's covariance matrix. The eigenvectors are the principal component directions, and the eigenvalues are the variance in those directions. So the "explained variance ratio" is simply each eigenvalue divided by the sum of all eigenvalues. Singular value decomposition (SVD) yields the same result, and scikit-learn and SageMaker use randomized SVD on large data to improve efficiency.

⚠️ Pitfall: PCA is an unsupervised transform that never looks at the target. "The direction of large variance" is not always "the direction useful for prediction." If a decisive signal hides in a low-variance axis, PCA may throw it away.

⚠️ Pitfall: Principal components are linear combinations of the original features, so physical meaning is lost. If a question says "you must explain which variables were used for prediction," the answer is feature selection, not PCA.

SageMaker Built-in PCA Algorithm

Large datasets cannot be loaded into memory entirely, so use SageMaker's built-in PCA algorithm.

ModeWhen to use
regularMedium-sized number of features and observations
randomizedWhen the number of features is very large (approximate SVD provides scalability)
  • Input is recordIO-protobuf or CSV, and training supports distributed processing
  • Use the resulting principal components to reduce the input dimension of downstream models (XGBoost, etc.)
HyperparameterRole
feature_dimNumber of input features
num_componentsNumber of principal components to keep
algorithm_moderegular / randomized
subtract_meanWhether to subtract the mean
from sagemaker import image_uris
 
container = image_uris.retrieve("pca", region="ap-northeast-2")
# Example Estimator hyperparameters
hyperparameters = {
    "feature_dim": 784,
    "num_components": 50,
    "algorithm_mode": "randomized",
    "subtract_mean": "true",
}

AWS Service Mapping

SituationService / featureReason
Extract principal components from a large matrix that exceeds memorySageMaker built-in PCADistributed training, supports recordIO-protobuf/CSV input
Very many features and scalability is the priorityBuilt-in PCA + algorithm_mode=randomizedApproximate SVD saves memory and time
Exploratory reduction of small data in a notebookSageMaker notebook + scikit-learn PCAFree experimentation such as scree plots
Downstream classification or regression on the reduced featuresBuilt-in algorithms such as SageMaker XGBoostUse the PCA output directly as training input

t-SNE: A Nonlinear Technique for Visualization Only

t-SNE (t-distributed Stochastic Neighbor Embedding) is a nonlinear technique that maps data so that neighbor relationships (local structure) in high dimensions are preserved in 2–3 dimensions.

ItemPCAt-SNE
Linear/nonlinearLinearNonlinear
PurposeVariance preservation, dimensionality reductionCluster visualization
Distance interpretationPreserves global structureTrust only local structure
Transforming new datatransform possibleNot possible (retrain each time)
DeterminismDeterministicRandom (depends on seed)

t-SNE is excellent for seeing clusters with the eye, but it is not used as preprocessing for model input. Distances between clusters and cluster sizes have no physical meaning, and new samples cannot be projected into the same space.

from sklearn.manifold import TSNE
 
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
X_embedded = tsne.fit_transform(X_scaled)   # 2D coordinates for visualization

perplexity balances how many neighbors to consider and is typically tuned in the range 5–50.

t-SNE converts high-dimensional distances into conditional probability distributions and minimizes the KL divergence so that a heavy-tailed t-distribution in low dimensions reproduces the same relationships. The heavy tails of the t-distribution relieve the "crowding problem," letting clusters spread out instead of clumping. Because of this process, however, the size of the empty space between clusters is meaningless — on the exam, an option that says "judge similarity by the distance between t-SNE clusters" is a trap.

t-SNE has only fit_transform; it has no transform that stores the learned mapping and applies it to new samples. An option that says "put new data arriving in production into the same embedding space" is wrong.

Dimensionality Reduction Technique Selection Table

TechniqueLinear/nonlinearNew-data transformMain useWhen not to use
PCALinearPossible (transform)Model preprocessing, noise removal, mitigating multicollinearityWhen interpretation of the original variables is needed, or when relationships are strongly nonlinear
t-SNENonlinearNot possible (retrain)2–3D cluster visualizationModel input, projecting new data, interpreting distances between clusters
AutoencoderNonlinearPossible (reuse the encoder)Nonlinear compression, anomaly detectionWhen you cannot afford the data and tuning cost, or when axis interpretation is needed
Feature selection (Day 2)—Possible (original columns kept)Reduction where interpretability is requiredWhen interactions between features are the key to performance (filter methods only)

Reduce or Select?

You need to reduce dimensions
├─ Must the result be explained variable by variable? (regulated industry, audit response)
│    ├─ Yes → Feature selection (keep the original columns as they are)
│    └─ No ↓
├─ Is the goal "check by eye whether clusters exist"?
│    ├─ Yes → t-SNE (2–3D, visualization only. Never as model input)
│    └─ No ↓
├─ Are relationships mostly linear?
│    ├─ Yes → PCA (standardize → choose k by cumulative explained variance)
│    └─ No  → Nonlinear compression such as an autoencoder
└─ Does the data exceed single-instance memory?
     └─ Yes → SageMaker built-in PCA (randomized if there are many features)

Summary of Preprocessing Techniques for High Dimensions

Dimensionality reduction is only one solution to the high-dimensional problem. The exam asks not "reduce the dimensions" but "what fits this situation."

TechniqueEffectWhen to useCaution
Standardization (Z-score)Puts all features on the same scaleBefore PCA, KNN, SVM, neural networksFit on the training set only
PCACompresses correlated axes into orthogonal axesMany features that are correlated with each otherNot interpretable; standardize first
Feature selectionRemoves irrelevant or redundant columnsInterpretation needed, manageable number of featuresMay miss interactions
Remove constant / quasi-constant columnsRemoves axes with no informationThe first step in any situationBeware of columns whose values appear only in a minority class
Regularization terms (L1/L2)Shrinks coefficients or sets them to 0Number of features ≳ number of samplesScaling must come first
EmbeddingsTurns high-cardinality categories into dense vectorsDeep learning, ultra-high cardinalityNeeds training data and a network
[High-dimensional raw data]
        │
   ① Split (train / test)  ← from here on, every fit uses the training set only
        │
   ② Missing-value imputation · encoding
        │
   ③ Standardization (StandardScaler)
        │
   ④ ┌─ Interpretation needed ─→ Feature selection (keep original columns)
     └─ Not needed ─→ PCA (n_components=0.95)
        │
   ⑤ Model training (XGBoost / linear / neural network …)
        │
   ⑥ On the test set, apply only transform with what was learned in ②–④

Question Clue → Answer Mapping

Clue in the questionAnswer to chooseReason
"There are 784 features and scalability matters"SageMaker built-in PCA, algorithm_mode=randomizedApproximate SVD gives scalability in high dimensions
"What do you do before applying PCA?"Standardization (scaling)It is variance-based, so scale dominates the result
"I want to see by eye whether clusters exist"t-SNE 2D embeddingReveals local neighbor structure visually
"Use t-SNE coordinates as classifier input"Wrong optionNew data cannot be transformed, and distances are meaningless
"You must explain which variables were used for prediction"Feature selectionKeeps the original features, so it is interpretable
"KNN accuracy drops as dimensions increase"Curse of dimensionality → dimensionality reductionDistance homogenization makes neighbor decisions meaningless
"You must decide how many principal components to keep"Cumulative explained variance / scree plot elbowA standard method based on the variance structure

The next post covers feature selection, which reduces dimensions while keeping the original features, and multicollinearity.

📖 Glossary

  • Curse of dimensionality: The phenomenon in which, as dimensions grow, data becomes sparse and distance discrimination disappears, making learning harder.
  • Sparsity: Data becoming thin because the same number of samples must fill a much larger space.
  • Principal component: A new coordinate axis taken, in order, along the directions of greatest variance in the data. They are mutually orthogonal.
  • Projection: Moving the original data onto new axes, "casting a shadow," and re-assigning coordinates.
  • Explained variance ratio: The share of the total variance that each principal component holds.
  • Scree plot: A graph with the principal component number on the x-axis and explained variance on the y-axis. Pick k at the bend (elbow).
  • Eigendecomposition / SVD: Linear-algebra operations that extract principal component directions (eigenvectors) and their variances (eigenvalues) from the covariance matrix. SVD is a way to get the same result more stably.
  • Local structure / global structure: Relationships among nearby neighbors / the overall large-scale layout of the data. t-SNE preserves the former well, PCA the latter.
  • perplexity: A value in t-SNE that controls "how many neighbors to look at." Usually set between 5 and 50.
  • recordIO-protobuf: A binary input format preferred by SageMaker built-in algorithms. More efficient than CSV for large volumes.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

You want to reduce the dimensionality of 784-dimensional image data with SageMaker and use it as input to a downstream classification model. The number of features is large, so scalability is important. What is the MOST appropriate choice?

Question 2

What preprocessing must be done before applying PCA?

Question 3

Which statement about t-SNE is NOT correct?

Question 4

What is the most appropriate way to choose an appropriate number of principal components k in PCA?

Question 5

Which type of algorithm does the curse of dimensionality worsen MOST directly?

PreviousWeek 3 Comprehensive Review: Cleaning and Feature EngineeringWeek 3 · Day 5Next Feature Selection: Filter, Wrapper and Embedded Methods, Importance, and MulticollinearityWeek 4 · Day 2

Official references

  • MLS-C01 official exam page(opens in a new tab)
  • Amazon SageMaker AI documentation(opens in a new tab)

On this page

  • Key Takeaways
  • The Curse of Dimensionality
  • Vulnerability to High Dimensions, by Algorithm
  • PCA: Principal Component Analysis
  • Preprocessing Requirements Before PCA
  • How to Choose the Number of Components k
  • SageMaker Built-in PCA Algorithm
  • AWS Service Mapping
  • t-SNE: A Nonlinear Technique for Visualization Only
  • Dimensionality Reduction Technique Selection Table
  • Reduce or Select?
  • Summary of Preprocessing Techniques for High Dimensions
  • Question Clue → Answer Mapping
  • Glossary
  • Practice Questions