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
  • Week 5
    • 1.Statistics Basics: Distributions, Central Tendency, Spread, Transformations, and Sample vs Population
    • 2.Correlation and Relationships: Correlation Coefficients, Causation vs. Correlation, Multivariate Relationships
    • 3.Data Leakage: Causes, Detection, Prevention, and Time-Series and Target Leakage
    • 4.Validation Design: Train/Validation/Test Splits, Cross-Validation, Time-Series Splits, Stratified Sampling
    • 5.Week 5 Comprehensive Review: Statistics and Validation Design
  • 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 5/Day 2

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

MLS-C01· AssociateWeek 5 · Day 2~34 min read

Day 2 - Correlation and Relationships: Correlation Coefficients, Causation vs. Correlation, Multivariate Relationships

📌 Key Takeaways

  • Pearson looks at linear relationships, Spearman at monotonic ones. Whatever the correlation coefficient, always interpret it together with a scatter plot.
  • Correlation is not causation. First suspect reverse causation, confounders, chance, and selection bias. Causal claims require an experimental design (A/B test).
  • When explanatory variables correlate strongly with each other, you have multicollinearity. The coefficients of linear and logistic regression become unstable (VIF > 5–10 is the warning line).
  • Tree-based models are insensitive to multicollinearity, but correlated variables split the importance between them, so each one's individual importance is underestimated.
  • For categorical-vs-categorical, use the chi-square test and Cramér's V rather than a correlation coefficient; for numeric-vs-categorical, use group mean comparison (ANOVA) and boxplots.

Correlation Coefficients: Degree of Joint Movement

Yesterday we examined the distribution of a single variable. Today we look at relationships between variables. Do two variables move together? If so, how strongly and in which direction? And the most dangerous question of all: just because they move together, is one the cause of the other?

MLS-C01 Domain 2 treats correlation analysis as a core EDA tool. Correlation drives feature selection, multicollinearity diagnosis, and the judgment "should I include this feature?" But confusing correlation with causation is the costliest mistake in data science.

A correlation coefficient quantifies how much two variables change together. Each type differs in what it measures and what it assumes.

CoefficientMeasuresAssumptions / propertiesRange
PearsonLinear relationshipContinuous, normality preferred, sensitive to outliers−1 to +1
SpearmanMonotonic relationshipRank-based, robust to nonlinearity and outliers−1 to +1
Kendall's τRank concordanceRank-based, robust when the sample is small or there are many ties−1 to +1
  • +1: perfect positive relationship (when one goes up, the other goes up)
  • 0: no linear (or monotonic) relationship
  • −1: perfect negative relationship

Pearson captures linear relationships only. For a strongly nonlinear curve such as a U shape, the Pearson r can be near 0 even though the variables are in fact strongly associated. In that case, rank-based Spearman is more useful.

 Strong positive linear     Strong U shape (nonlinear)   Fake correlation created by one outlier
    ·                        ·         ·              ·
      ·                       ·       ·                       ·   ← this single point
        ·                       ·   ·                ····         pulls r upward
          ·                       ···                ····
  r ≈ +0.95 (Pearson OK)   r ≈ 0 (Pearson fails)    r is high but nothing real behind it
                            → Spearman, scatter plot → must confirm with a scatter plot
import pandas as pd
 
df = pd.read_csv("data/marketing.csv")
 
# Pearson: linear relationship
print(df[["ad_spend", "revenue"]].corr(method="pearson"))
 
# Spearman: monotonic relationship (robust to nonlinearity and outliers)
print(df[["ad_spend", "revenue"]].corr(method="spearman"))
 
# Full correlation matrix (feature selection, multicollinearity check)
corr_matrix = df.corr(numeric_only=True)

Pearson r is the covariance of the two variables after standardizing them, and it connects directly to regression's R² (in simple linear regression, R² = r²). If r = 0.7, then R² = 0.49, meaning one variable explains about 49% of the other's variance. What matters is that r measures linearity only. Anscombe's quartet shows that the scatter plots can look completely different even when r is the same. A correlation coefficient must always be interpreted together with a scatter plot.

Correlation Coefficient Selection Table — by Variable Type

Variable combinationNature of relationshipRecommended methodCaution
Continuous ↔ continuousLinearPearsonA single outlier can shake the value greatly
Continuous ↔ continuousNonlinear but monotonicSpearmanDoes not tell you the "shape" of the curve
Ordinal ↔ ordinalRank agreementSpearman / Kendall's τKendall is more stable when there are many ties
Categorical ↔ categoricalWhether independentChi-square test of independenceThe test is inaccurate if expected frequencies are too small
Categorical ↔ categoricalStrength of associationCramér's V (0–1)Has no notion of direction (positive/negative)
Categorical ↔ continuousDifference between groupsANOVA, boxplot, group mean comparisonWatch for imbalanced group sizes
Any combinationCheck the actual shapeScatter plot / heatmap visualizationLooking only at the coefficient will always mislead you

Correlation ≠ Causation

The costliest mistake in data science is mistaking correlation for causation. There are several explanations for why things move together.

PatternExplanationExample
True causationA actually causes BExercise → improved fitness
Reverse causationIn fact B causes A"Hospital visits ↔ illness": people visit the hospital because they are sick
ConfounderA hidden variable Z causes bothIce cream sales ↔ drowning accidents: temperature (Z) raises both
SpuriousCoincidental alignment in a sample or time seriesTwo unrelated time series both trend upward
Selection biasThe way the sample was drawn creates a false relationshipA relationship that appears from observing only those who were admitted
  • To claim causation from correlation, observational data alone is not enough. You need a randomized controlled trial (A/B test) or causal inference techniques.
  • If an experiment is impossible, you must at least control for confounders (stratification, regression adjustment).

⚠️ Pitfall: "Ice cream sales correlate with drowning accidents" is the textbook case, and it results from ignoring the confounder (temperature). On the exam, an answer choice like "A strong correlation was observed, so increasing A will increase B" is wrong. An observed correlation alone cannot justify a policy or intervention.

⚠️ Pitfall: Do not conclude "there is no relationship" just because the correlation coefficient is 0. A Pearson of 0 only means there is no linear relationship; a strong nonlinear relationship such as a U shape or a periodic pattern may be hiding.

Multivariate Relationships and Multicollinearity

With three or more variables, relationships become complex. The most important problem in modeling is multicollinearity: the situation in which explanatory variables are strongly correlated with each other.

The problems with multicollinearity:

  • In linear and logistic regression, coefficient estimates become unstable and interpretation breaks down (signs can even flip).
  • It is hard to separate out which variable is truly important.
  • Standard errors grow, which blurs statistical significance.

Multicollinearity Diagnosis and Remedy Table

ToolMethodDecision criterionRemedy
Correlation matrix heatmapVisually scan the correlations of variable pairsWatch pairs with |r| of 0.8–0.9 or higherRemove one of the two, or merge them
VIF (Variance Inflation Factor)Computed from the R² of regressing one variable on all the othersVIF > 5 is a caution; > 10 is strong multicollinearityRemove or combine variables
Dimensionality reduction (PCA)Compress correlated variables into orthogonal componentsChoose the number of components by explained variance ratioCost: you lose interpretability
Regularization (Ridge)Stabilize by applying an L2 penalty to the coefficientsChoose α by cross-validationKeeps the variables while stabilizing the coefficients
Domain judgmentClean up variables with redundant meaning (impressions, clicks, etc.)—Reconstruct them as ratio features
import seaborn as sns
import matplotlib.pyplot as plt
from statsmodels.stats.outliers_influence import variance_inflation_factor
 
# Correlation heatmap: first-pass multicollinearity scan
corr = df.corr(numeric_only=True)
sns.heatmap(corr, annot=True, cmap="coolwarm", center=0)
plt.show()
 
# Quantitative diagnosis: VIF
X = df[["ad_spend", "impressions", "clicks"]]
vif = pd.DataFrame({
    "feature": X.columns,
    "VIF": [variance_inflation_factor(X.values, i) for i in range(X.shape[1])],
})
print(vif)  # VIF > 10 indicates strong multicollinearity

Tree-based models (Random Forest, XGBoost) are relatively insensitive to multicollinearity. When splitting, they only need to pick one of the correlated variables, so predictive performance does not drop much. However, correlated variables share the importance between them, so individual importance can be underestimated. Linear and logistic regression, by contrast, suffer unstable coefficient estimation itself. The exam point is that sensitivity to multicollinearity depends on the algorithm.

Correlation and Multicollinearity Sensitivity by Algorithm

Algorithm typeEffect of multicollinearityPredictive performanceInterpretation / importanceResponse
Linear / logistic regressionVery sensitiveNot much worse, but unstableCoefficients become practically uninterpretableRemove variables, Ridge/Lasso, PCA
Ridge / LassoMitigatedStableLasso tends to keep only one of the correlated variablesCross-validate the regularization strength
KNN / SVM (distance-based)ModerateCorrelated variables count twice in the distance—Scaling + clean up redundant variables
PCAActually a precondition—Components are hard to interpretIts purpose is to compress the correlation structure
Decision Tree / RF / XGBoostInsensitiveAlmost no effectImportance is split and underestimatedGroup correlated features when interpreting importance

Relationships Between Categorical Variables

Correlation coefficients are for numeric variables. Categorical relationships use different tools.

  • Chi-square test: tests whether two categorical variables are independent (based on a contingency table).
  • Cramér's V: an association-strength measure that normalizes chi-square to 0–1.
  • Numeric vs. categorical: compare group means (ANOVA) and look at distribution differences with boxplots.
import pandas as pd
from scipy.stats import chi2_contingency
 
# Test independence of two categorical variables
table = pd.crosstab(df["region"], df["churned"])
chi2, p, dof, expected = chi2_contingency(table)
print(f"chi2={chi2:.2f}, p-value={p:.4f}")  # p < 0.05 means there is an association

Using Correlation for Feature Selection

The practical use of correlation analysis ultimately comes down to "which features do we keep?" You have to distinguish two directions.

What you look atMeaningUsePitfall
Feature ↔ target correlationHow well that feature explains the targetDrop features with near-zero correlation from the candidatesNonlinear relationships come out low. Discarding a feature just because its correlation is 0 can cost you
Feature ↔ feature correlationWhether features carry overlapping informationClean up redundant features to reduce multicollinearityWhen keeping only one, choose the one with the better domain meaning
A single feature with |r| ≥ 0.95 against the targetSuspiciously perfect explanation—The number-one sign of target leakage (Day 3)

Feature selection methods also fall into three groups.

MethodHowProsCons
FilterPre-screen with correlation coefficients, variance, chi-squareFast and applicable independent of the modelCannot see the combined effects of features
WrapperForward selection / backward elimination, choosing by actual performanceReflects combined effectsHigh computational cost
EmbeddedAutomatic selection during training (Lasso, tree importance)Practical, directly tied to performanceTied to the model type

If you see a feature with an abnormally high correlation with the target (|r| ≈ 1) and celebrate "I found a great feature," you are making a mistake. It is far more likely that outcome information that is unknowable at prediction time has been mixed in. First ask: "Can I really know this value at the moment of prediction?"

MLS Perspective: Where Does Correlation Analysis Lead?

AWS Service Mapping Table

SituationAWS service / featureReason
Explore relationships with correlations, scatter plots, and histograms without codeSageMaker Data WranglerBuilt-in analysis and visualization let you quickly scan relationships between features and chain on transformations
Filter out low-correlation features to cut training costSageMaker processing flow + feature selectionUnneeded features raise both training time and overfitting risk
Compress correlated high-dimensional numeric data into orthogonal componentsSageMaker built-in PCA algorithmRemoves multicollinearity while reducing dimensionality
Check whether a particular attribute (gender, region) is entangled with the targetSageMaker ClarifyBias metrics before training check the association between sensitive attributes and labels
Check cross-tabulations and aggregate relationships with SQL on large dataAmazon AthenaQuery the S3 source directly to extract cross-frequencies between categories
Explain after training which features contributed to predictionsSageMaker Clarify (feature attribution)Correlation and model contribution differ, so post-hoc explanation is needed

Question Clue → Answer Mapping Table

Phrase in the questionSignal to readAnswer to pick
"It is U-shaped but the correlation coefficient is near 0"Pearson sees only linearSpearman + confirm with a scatter plot
"Relationship between two continuous variables with many outliers"Pearson is sensitive to outliersSpearman (rank-based)
"Is region related to churn?"Categorical ↔ categoricalChi-square test of independence / Cramér's V
"VIF came out at 15"Strong multicollinearityRemove variables, PCA, or Ridge
"The sign of a regression coefficient is opposite to common sense"Sign of multicollinearityCheck the correlation matrix and VIF
"The correlation is high, so increasing A will increase B"Causal leapWrong. Suspect confounders and reverse causation; an A/B test is needed
"Many correlated variables but a tree model is used"Trees are insensitivePredictive performance holds up, but be careful interpreting importance
"Impressions, clicks, and ad spend are strongly correlated with each other"Redundant informationReconstruct as ratio features or keep only one

In the next article we cover the deadliest enemy of EDA and validation: data leakage.

📖 Glossary

  • Correlation coefficient: A value summarizing, on a scale of −1 to +1, how much two variables move together.
  • Pearson correlation: A correlation coefficient that measures the strength of a straight-line relationship. Weak against outliers.
  • Spearman correlation: A correlation coefficient that uses ranks instead of values to measure a monotonic relationship. Robust to nonlinearity and outliers.
  • Monotonic relationship: A relationship in which, as one variable increases, the other keeps increasing or keeps decreasing. It need not be a straight line.
  • Confounder: A hidden variable that influences both variables and creates a spurious correlation.
  • Reverse causation: The error of interpreting the direction of cause and effect the wrong way around.
  • Multicollinearity: The phenomenon in which explanatory variables are strongly correlated with each other, making regression coefficient estimates unstable.
  • VIF (Variance Inflation Factor): A multicollinearity measure showing how well one variable is explained by the remaining variables. Warning above 5–10.
  • Chi-square test of independence: A method that tests, using a contingency table, whether two categorical variables are independent of each other.
  • Cramér's V: A value that normalizes the chi-square statistic to 0–1 to express the strength of association between categorical variables.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

There is a strong U-shaped (nonlinear) relationship between two variables, yet the Pearson correlation coefficient came out near 0. Which method better captures the strength of the relationship?

Question 2

In data showing that "ice cream sales and drowning incidents are strongly positively correlated," what is the correct interpretation?

Question 3

In a linear regression model, which problem occurs when the explanatory variables are strongly correlated with each other (very high VIF)?

Question 4

You want to test whether two categorical variables (region and churn status) are independent. Which method is MOST appropriate?

Question 5

When building a model on data with many correlated features, which algorithm is relatively insensitive to multicollinearity?

PreviousStatistics Basics: Distributions, Central Tendency, Spread, Transformations, and Sample vs PopulationWeek 5 · Day 1Next Data Leakage: Causes, Detection, Prevention, and Time-Series and Target LeakageWeek 5 · Day 3

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
  • Correlation Coefficients: Degree of Joint Movement
  • Correlation Coefficient Selection Table — by Variable Type
  • Correlation ≠ Causation
  • Multivariate Relationships and Multicollinearity
  • Multicollinearity Diagnosis and Remedy Table
  • Correlation and Multicollinearity Sensitivity by Algorithm
  • Relationships Between Categorical Variables
  • Using Correlation for Feature Selection
  • MLS Perspective: Where Does Correlation Analysis Lead?
  • AWS Service Mapping Table
  • Question Clue → Answer Mapping Table
  • Glossary
  • Practice Questions