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 5

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

MLS-C01· AssociateWeek 4 · Day 5~28 min read

Day 5 - Week 4 Comprehensive Review: Dimensionality, Feature Selection, Visualization, Imbalance

📌 Key Takeaways

  • One sentence that runs through all of Week 4: "Split first, and fit everything only on the training set." Standardization, PCA, feature selection, and SMOTE all fall under it.
  • PCA vs feature selection splits on "do you need interpretability?" If you have an obligation to explain, select; if not, reduce.
  • PCA vs t-SNE splits on "do you need to transform new data?" t-SNE is for visualization only.
  • The 3 big imbalance traps: using a t-SNE embedding as model input, trusting accuracy under imbalance, and applying SMOTE before the split.
  • Multicollinearity is fatal to linear models and harmless to trees. Diagnose it with the correlation matrix and VIF (> 5 caution, > 10 severe).

Week 4 on One Page

Week 4 was the second cluster of EDA — techniques for handling high dimensions and class imbalance. Today we knit the four days into one workflow, compare the commonly confused pairs, and sum up the exam traps.

DayTopicKey pointOne-line discriminator
1Dimensionality reductionCurse of dimensionality, PCA (preserves variance, standardization required), t-SNE (visualization only)If you must transform new data, PCA
2Feature selectionFilter, wrapper, embedded; feature importance; multicollinearity (VIF)If you must explain the variables, select
3Data visualizationDistribution and correlation charts, QuickSight, the lesson of AnscombeA dashboard without code means QuickSight
4Class imbalanceAccuracy paradox, SMOTE and undersampling, class weights, PR-AUCIf positives are rare, PR-AUC

The Integrated Workflow

This is the typical EDA and preprocessing order for high-dimensional, imbalanced data.

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
 
# 1) Split first — fit everything only on the training set (prevents leakage)
X_tr, X_te, y_tr, y_te = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
 
# 2) Visualize distributions, correlations, and imbalance (on the training set)
#    histograms/box plots, correlation heatmap, class distribution bars
 
# 3) Standardize → reduce dimensions (or select features)
# 4) Resample on the training set only, inside a Pipeline
pipe = Pipeline([
    ("scaler", StandardScaler()),
    ("pca", PCA(n_components=0.95)),
    ("smote", SMOTE(random_state=42)),
])
X_tr_proc, y_tr_proc = pipe.fit_resample(X_tr, y_tr)
[Raw data]
     │
 ① Split (stratify=y)  ────────────────→ [Test set] sealed
     │                                        │
 ② Visualize (Day 3)                          │
     ├ distributions → skew and outliers      │
     ├ correlation heatmap → multicollinearity candidates │
     └ class bars → confirm imbalance         │
     │                                        │
 ③ Standardize (fit: training set)            │
     │                                        │
 ④ Dimension handling                         │
     ├ interpretability needed → feature selection (Day 2) │
     └ not needed → PCA (Day 1)               │
     │                                        │
 ⑤ Imbalance handling (Day 4)                 │
     ├ resampling → only in each fold's training portion │
     └ or class weights (data unchanged)      │
     │                                        │
 ⑥ Train → set the threshold on the validation set │
     │                                        │
 ⑦ Final evaluation ←──── apply only transform of what was learned in ③ and ④
        (PR-AUC / F1 — not accuracy)

The principle that ties this workflow together is "split first, fit only on the training set." Standardization, PCA, SMOTE, feature selection, missing-value imputation — every transform that depends on the data must learn its statistics or rules on the training set and only be applied to the test set. This single principle runs from Week 3 (cleaning and encoding) through Week 4 (dimensionality and imbalance).

Why This Order

OrderWhy it comes firstIf reversed
Split → preprocessingTest information must not leak into the transformAll performance estimates are inflated optimistically
Standardize → PCAPCA is variance-based, so it is dominated by scaleVariables with large units monopolize the principal components
Visualize → preprocessing decisionsYou must know what to fix before fixing itTransforms are applied indiscriminately without a basis
Dimension handling → resamplingSynthesizing in the reduced space is consistentSynthetic samples are generated including the axes you would discard
Resampling → training (within the same fold)The validation portion must keep the original distributionSynthetic positives flow into the validation set
Training → threshold decision (validation set)The threshold is also a learned valueSetting it by looking at the test set leaks

⚠️ Pitfall: The misconception that "I did dimensionality reduction, so feature selection is unnecessary." The two have different purposes. PCA merges correlated axes to tidy up computation and multicollinearity, but it also mixes the noise from irrelevant features into the principal components. Columns that are useless to begin with are better filtered out before PCA.

⚠️ Pitfall: If the stem contains words like "must be explainable," "regulatory compliance," or "audit," the PCA, t-SNE, and autoencoder families are all dropped from the candidates. What remains is feature selection, which keeps the original features, and SHAP/Clarify, which explain contributions.

Comparing Commonly Confused Pairs

PCA vs Feature Selection

AspectPCAFeature selection
Resulting featuresSynthetic axes (meaning lost)A subset of the originals (interpretability preserved)
TypeUnsupervisedBoth supervised and unsupervised exist
MulticollinearityResolved with orthogonal axesResolved by removing correlated features
Regulated industriesHard to explainExplainable, preferred
New dataSame transform via transformJust pick and use the same columns
Information lossAs much as the discarded principal componentsAs much as the discarded features

PCA vs t-SNE

  • PCA: Linear, preserves global variance, can transform new data, suitable for model preprocessing
  • t-SNE: Nonlinear, preserves local structure, must be refit every time, visualization only
Question to askPCAt-SNE
Is the result used as model input?YesNo
Can new samples be placed into the same space in production?PossibleNot possible
Does it give the same result on every run?YesNo (depends on the seed)
Can you interpret distances between clusters?Relatively reliableMeaningless

Oversampling vs Class Weights

AspectOversampling (SMOTE)Class weights
DataGrows (synthetic samples are generated)Unchanged
Where appliedPreprocessing stage, training set onlyModel hyperparameter
Leakage riskYes (split and fold management needed)None
Model constraintsNone (any model)The model must support weights
Categorical featuresBasic SMOTE cannot be applied directlyNo effect
High dimensionsInterpolation loses meaningNo effect
Reproducibility and auditBurden of managing synthetic dataAdvantageous since the original stays as is

ROC-AUC vs PR-AUC

AspectROC-AUCPR-AUC
AxesTPR vs FPRPrecision vs recall
Effect of negativesAll negatives in the FPR denominator → dilutedNot directly driven by the number of negatives
WhenClasses are relatively balancedWhen positives are rare
PitfallLooks optimistic under imbalanceCannot be compared across datasets with different class ratios

Filter vs Wrapper vs Embedded

AspectFilterWrapperEmbedded
Model trainingNoneRepeatedlyOnce (built into training)
SpeedFastestSlowestMedium
Captures interactionsNoYesPartially
Representative techniquesCorrelation, chi-square, mutual informationForward selection, backward elimination, RFELasso, tree importance

The Decision Flow on One Page

Too many dimensions / performance is poor
   │
   ├─ Do you need variable-level explanations?
   │     Yes → feature selection (narrow down in the order filter → embedded → RFE)
   │     No ↓
   ├─ Is the goal "to see by eye whether clusters exist"?
   │     Yes → t-SNE (visualization only. Never as model input)
   │     No ↓
   ├─ Is the scale beyond memory?
   │     Yes → SageMaker built-in PCA (randomized if there are many features)
   │     No → scikit-learn PCA (after standardizing, n_components=0.95)
   │
The target is heavily skewed
   │
   ├─ Is it acceptable to change the data?
   │     No → class weights / threshold moving
   │     Yes ↓
   ├─ Is the data very large?
   │     Yes → random undersampling (to gain speed)
   │     No → SMOTE (only inside the fold)
   │
   └─ Always evaluate with PR-AUC · F1 · recall (never accuracy)

Three easy-to-confuse traps. (1) "Use the t-SNE embedding as classifier input" → wrong (visualization only). (2) "99% accuracy on imbalanced data is good" → accuracy paradox. (3) "Apply SMOTE or scaling before the split" → data leakage. Nailing just these three stabilizes your score in the EDA domain.

Even when a question looks like it asks about imbalance handling and metric choice separately, many stems require answering them as a set. An option that picks only "apply SMOTE" and then leaves evaluation to accuracy is wrong. Whether you use resampling, weights, or thresholds, evaluation goes by PR-AUC, F1, and recall.

AWS Service Mapping Review

TaskService/tool
Large-scale PCASageMaker built-in PCA (randomized mode)
Visual data preparation and distribution reportsSageMaker Data Wrangler
Code-based EDA visualizationSageMaker notebooks (seaborn/matplotlib)
BI dashboards and ML InsightsAmazon QuickSight
Serverless SQL analysis on S3Amazon Athena (+ QuickSight)
Pre-training bias and distribution checkSageMaker Clarify
User in the stemTool to chooseWhy
Data scientist, free-form explorationSageMaker notebooksAnything is possible with code
Analyst preprocessing without codeData WranglerVisual preparation + reports
Business user without codeQuickSight (ML Insights, Q)Dashboards and natural-language queries
Regulatory compliance ownerClarify + feature selectionBias checks and explainability

Stem Clue → Answer Mapping

Stem clueAnswer to chooseWhat to recall together
"Must explain which variables were used for prediction"Feature selectionPCA is wrong
"There are very many features and scalability matters"SageMaker built-in PCA + randomizedStandardization first
"Confirm by eye whether clusters exist"t-SNEForbidden as model input
"Positives are 0.2%"PR-AUC and recall + class weights/SMOTEAccuracy is a trap
"Accuracy is 99% but the minority class is not caught"Accuracy paradoxCheck the confusion matrix first
"Use SMOTE in cross-validation"imblearn Pipeline, inside the foldApplying before the split leaks
"VIF is 12"Severe multicollinearity → remove, PCA, RidgeCan be ignored for tree models
"Correlation is 0 but the scatter plot is a curve"Pearson measures only linearSpearman, mutual information
"Anomaly detection dashboard without code"QuickSight ML InsightsQ is natural-language querying
"Check class distribution and bias before training"SageMaker ClarifyPre-training bias

Wrong-Answer Notebook

Easy-to-confuse statementVerdictWhy
"Feed the coordinates made by t-SNE directly into a classifier"✗Cannot transform new data, and distances have no physical meaning
"PCA gives the same result without standardization"✗It is variance-based, so large-scale variables monopolize the principal components
"PCA considers the target and picks useful axes"✗An unsupervised transform. High-variance axes ≠ axes useful for prediction
"99% accuracy on imbalanced data means a good model"✗Accuracy paradox. TN dominates the metric
"Apply SMOTE to the entire data before the split"✗Synthetic positives flow into the validation set, causing leakage
"SMOTE duplicates minority samples"✗Not duplication but interpolation between neighbors (duplication is random oversampling)
"Multicollinearity is fatal to every model"✗Fatal to linear models, tree families are insensitive
"Impurity-based importance is the most trustworthy"✗High-cardinality bias. Permutation importance and SHAP are more trustworthy
"If the correlation coefficient is 0, the two variables are independent"✗Pearson measures only linear relationships. A nonlinear relationship may exist
"Feature selection keeps the original features, so it is explainable"✓Why it is preferred over PCA in regulated industries
"Undersampling speeds up training when the data is very large"✓Shrinks the majority class, solving both volume and imbalance
"Threshold moving raises recall without retraining"✓Can be adjusted after training and even in production

📖 Glossary

  • Data leakage: An accident in which information that cannot be known at prediction time gets mixed into training, making performance look better than it really is.
  • stratify: An option that keeps the class ratio the same in the training and test sets when splitting. It is especially important on imbalanced data.
  • Pipeline: A mechanism that bundles preprocessing and the model into one unit and reproduces it in the same order for each fold. It is the standard tool for preventing leakage.
  • Synthetic axes vs original features: The nameless axes that PCA produces / the original columns whose names and units remain intact.
  • Local structure preservation: The property that points that were close remain close after reduction. It is the goal t-SNE aims for.
  • Accuracy paradox: The illusion that a model looks good because accuracy comes out high even when it just predicts the majority class.
  • PR-AUC: The area under the precision-recall curve. When positives are rare, it reveals differences better than ROC-AUC.
  • VIF (variance inflation factor): A value that measures multicollinearity by how well one feature can be predicted from the other features. 5 is caution, 10 is severe.
  • SageMaker Clarify: A feature that checks data bias and class distribution before training and computes feature attributions for predictions.
  • SPICE: QuickSight's in-memory calculation engine. It makes dashboard aggregation fast.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

Which leakage-prevention principle, common to standardization, PCA, SMOTE, and missing-value imputation and running through Weeks 3 and 4, applies?

Question 2

In a regulated industry, you must explain which variables were used for prediction and also handle multicollinearity. Which approach is more appropriate than PCA?

Question 3

Which of the following statements is correct?

Question 4

A business user who does not write code wants automatic anomaly detection and forecasting on a dashboard of S3 data. Which tool is MOST appropriate?

Question 5

You have data with a very large majority class and a rare minority class, and you want to reduce the data volume itself for training speed while also mitigating the imbalance. Which method is MOST appropriate?

PreviousHandling Class Imbalance: Oversampling, Undersampling, SMOTE, Class Weights, EvaluationWeek 4 · Day 4Next Statistics Basics: Distributions, Central Tendency, Spread, Transformations, and Sample vs PopulationWeek 5 · Day 1

Official references

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

On this page

  • Key Takeaways
  • Week 4 on One Page
  • The Integrated Workflow
  • Why This Order
  • Comparing Commonly Confused Pairs
  • PCA vs Feature Selection
  • PCA vs t-SNE
  • Oversampling vs Class Weights
  • ROC-AUC vs PR-AUC
  • Filter vs Wrapper vs Embedded
  • The Decision Flow on One Page
  • AWS Service Mapping Review
  • Stem Clue → Answer Mapping
  • Wrong-Answer Notebook
  • Glossary
  • Practice Questions