1 정의
Mediation (매개): \(X\) 가 \(M\) 을 통해 \(Y\) 에 영향:
X → M → Y
\(M\) 이 mediator. \(X\) 의 효과가 \(M\) 을 거쳐 \(Y\) 에 도달.
IV (Instrumental Variable, 도구변수): 알려진 mediation 관계를 활용해 confounding bias 줄이는 도구.
Z → X → Y
↑ ↑
└──── 공통 confounder
\(Z\) 가 \(X\) 의 cause 이지만 \(Y\) 에 직접 영향 없음 (Z 가 instrument). \(Z\) 의 randomization 으로 \(X\) → \(Y\) 인과 추정.
비즈니스 사례:
- Mediation: PlayArea → VisitDuration → GroceryPurchases
- IV: 무작위 SOP → CSAT → M6Spend (CSAT 의 인과 효과 추정)
분석가의 자연스러운 의문: “왜 둘이 한 챕터?”
답: 같은 Chain 구조의 다른 활용.
| 도구 | 목적 | 활용 |
|---|---|---|
| Mediation | 메커니즘 이해 | \(X\) → \(M\) → \(Y\) chain 의 각 단계 측정 |
| IV | Confounding 제거 | \(Z\) → \(X\) 의 randomization 으로 \(X\) → \(Y\) 식별 |
같은 chain 구조 (3 변수, 2 화살표). 그러나:
- Mediation: chain 중간을 측정 (mechanism)
- IV: chain 위쪽 (Z) 의 randomness 를 활용 (causal identification)
→ 두 도구가 같은 chain 의 다른 응용.
2 Mediation 의 비즈니스 가치
2.1 1. 인과 메커니즘 이해
분석 질문: “PlayArea 가 GroceryPurchases 에 미치는 효과는?”
단순 회귀:
GroceryPurchases ~ PlayArea
beta = 27.6 (PA 있으면 +$27.6 평균 grocery)
이 추정의 한계:
- “왜 효과가 있나?” 모름
- 다른 매장의 외삽 어려움
- Personalization 어려움
Mediation 분석:
PlayArea → VisitDuration → GroceryPurchases
12.6 분 추가 2.2 $/분 추가
→ 12.6 × 2.2 = 27.5 $
해석:
- PA 의 효과 99.5% 가 visit duration 통한 mediation
- Grocery purchase 의 진짜 driver 는 visit time
PA → VisitDuration → GroceryPurchases 의 의미:
- “PA 가 단순히 매장 분위기 좋게 하는 게 아니라 시간을 늘림”
- 다른 비즈니스 결정의 단서:
- PA 대신 lounge area? (다른 시간 늘리는 메커니즘)
- PA 의 closing time 효과? (시간 제한 시 효과 약함)
- 시간 늘리는 다른 정책 (mini-cinema, snack station)
이 통찰이 단순 평균 효과로는 안 보임.
→ Mediation 이 비즈니스 ideation 의 도구.
2.2 2. Causal Bias 방지
분석가의 흔한 실수:
# 잘못 — total effect 측정에 mediator 포함
m = smf.ols("GroceryPurchases ~ PlayArea + VisitDuration", data=df).fit()문제:
- VisitDuration 이 mediator
- 통제 시 mediation chain 차단
- PlayArea 계수 = direct effect 만 (= 0.16)
- Total effect (= 27.6) 측정 못 함
올바른 분석:
# Total effect
m_total = smf.ols("GroceryPurchases ~ PlayArea", data=df).fit()
# beta = 27.6 (정확)
# Direct effect (mediator 통제)
m_direct = smf.ols("GroceryPurchases ~ PlayArea + VisitDuration", data=df).fit()
# beta_PA = 0.16, beta_VD = 2.2 (mediation 분리)두 분석 모두 의미 있음. 단순한 회귀로 둘을 혼동하면 위험.
| 분석 질문 | Mediator 통제 |
|---|---|
| “PlayArea 의 총 효과?” | No (mediation chain 보존) |
| “PlayArea 의 직접 효과 (vd 무관)?” | Yes (mediator 통제) |
| “Mediation 자세히 측정?” | 두 회귀 모두 (total + direct) |
분석가의 default:
- 비즈니스 의사결정용 보고: total effect (mediator 통제 X)
- 메커니즘 분석용: mediation analysis (별도 처리)
이 분리가 분석의 명확성.
2.3 3. 다른 Mediator 와의 confounding
C-Mart 매장 단위 분석:
Average duration ─→ Grocery sales (total)
↑ ↑
PlayArea ───→ Number of customers ─→
↑
Store customer base (confounder)
Number of customers 가 mediator 이면서 confounder.
분석가의 결정:
- Number of customers 통제 시 mediation 차단
- 통제 안 하면 confounding bias
해결: Customer base (proxy) 를 confounder 통제 변수로:
Customer base = 1년 전 customers 수 (proxy, treatment 효과 미포함).
이 처리가 confounding 제거 + mediator 보존 동시에.
3 Mediation 측정의 3 단계
3.1 Total Effect
3.2 Indirect Effect (Mediated)
Indirect effect = \(X \to M\) 의 효과 × \(M \to Y\) 의 효과.
# X → M
m_xm = smf.ols("VisitDuration ~ PlayArea", data=df).fit()
beta_xm = m_xm.params["PlayArea"] # 12.6
# M → Y (X 통제)
m_my = smf.ols("GroceryPurchases ~ PlayArea + VisitDuration", data=df).fit()
beta_my = m_my.params["VisitDuration"] # 2.2
# Indirect effect
indirect = beta_xm * beta_my # 12.6 × 2.2 = 27.5수식:
\[ \beta_{\text{indirect}} = \beta_{XM} \cdot \beta_{MY} \]
Product 의 직관:
- \(X\) 1 증가 → \(M\) 이 \(\beta_{XM}\) 증가
- \(M\) 이 \(\beta_{XM}\) 증가 → \(Y\) 가 \(\beta_{XM} \cdot \beta_{MY}\) 증가
비유: 톱니바퀴.
- 작은 톱니 (X) 가 1 회전 → 중간 톱니 (M) 가 12 회전 → 큰 톱니 (Y) 가 27 회전
- 12 × 2.25 = 27
각 화살표의 강도가 곱해져 final effect.
3.3 Direct Effect (Unmediated)
3.4 Percentage Mediated
\[ \text{Percentage Mediated} = \frac{\beta_{\text{indirect}}}{\beta_{\text{total}}} \]
C-Mart 사례:
\[ \text{PM} = \frac{27.5}{27.6} \approx 99.5\% \]
해석:
- 99.5% 의 total effect 가 VisitDuration 을 통한 mediation
- 0.5% 만 direct (다른 메커니즘)
- → “Full mediation” 가까움
PM = 99.5% 의 의사결정 함의:
- PA 의 진짜 driver = visit duration
- Visit duration 늘리는 다른 정책 (lounge, snack 등) 도 같은 효과 가능
- PA 자체보다 시간 늘리는 메커니즘이 핵심
만약 PM = 50% 였다면:
- 절반은 visit duration 통해
- 절반은 다른 메커니즘 (분석 추가 필요)
→ PM 이 비즈니스 strategy 결정.
3.5 Bootstrap CI
PM 은 두 추정의 ratio → 분포 비선형 → Bootstrap.
import numpy as np
def bootstrap_pm(df, B=1000):
pms = []
for _ in range(B):
sample = df.sample(len(df), replace=True)
m_total = smf.ols("GroceryPurchases ~ PlayArea", data=sample).fit()
m_xm = smf.ols("VisitDuration ~ PlayArea", data=sample).fit()
m_my = smf.ols("GroceryPurchases ~ PlayArea + VisitDuration", data=sample).fit()
b_total = m_total.params["PlayArea"]
b_xm = m_xm.params["PlayArea"]
b_my = m_my.params["VisitDuration"]
b_indirect = b_xm * b_my
pm = b_indirect / b_total
pms.append(pm)
return np.percentile(pms, [5, 95])
ci = bootstrap_pm(df)
print(f"Percentage Mediated 90% CI: {ci}")가상 결과: [0.9933, 0.9975].
→ Full mediation 의 robust 확인.
4 Full vs Partial Mediation
4.1 두 시나리오
Full Mediation:
X ──→ M ──→ Y
X 의 효과가 모두 M 을 통해. Direct effect = 0.
Partial Mediation:
X ──→ M ──→ Y
└────────→
X 가 M 통해서도, 직접도 Y 에 영향. Direct effect ≠ 0.
수학적으로:
- Full: \(\beta_{\text{direct}} = 0\), \(\beta_{\text{total}} = \beta_{\text{indirect}}\)
- Partial: \(\beta_{\text{direct}} > 0\), \(\beta_{\text{total}} = \beta_{\text{indirect}} + \beta_{\text{direct}}\)
Full mediation:
- 메커니즘 1 가지
- M 을 modify 하면 효과 변경 가능
- 다른 메커니즘 검색 불필요
Partial mediation:
- 메커니즘 여러 가지
- M 외에도 다른 path 가 있음
- 추가 mediator 검색 가치
분석가의 결정:
- Full → 분석 종결
- Partial → 추가 mediator 식별 시도
→ Mediation 의 percentage 가 다음 단계 결정.
4.2 Multicollinearity 함정
Full mediation 의 경우 X 와 M 이 매우 상관:
- X = 1 일 때 M 의 평균이 매우 다름
- X 의 분산이 M 의 분산으로 거의 흡수
- 회귀에 둘 다 포함 시 multicollinearity
증상:
- 큰 standard errors
- 반대 부호 계수 (X와 M 이 cancel)
- p-value 매우 큼
해결:
- X 를 회귀에서 제거 (M 만)
- Mediation = total effect (가정)
Buisson:
“Including the primary cause makes the mediator coefficient go haywire? Don’t include the primary cause.”
Multicollinearity 시:
- X 만 회귀: total effect 측정
- M 만 회귀: M 의 효과 추정 (X 통제 없이)
- 둘 다 시도: 결과 비교
만약 X 만 vs X+M 의 X 계수 큰 차이:
- Full mediation 가능성 높음
- 통계 도구의 한계 인정
→ 분석가의 default: 다양한 모형 비교 + 도메인 직관.
5 Instrumental Variables (IV)
5.1 정의
문제: \(X\) 의 \(Y\) 에 대한 인과 효과 추정. 그러나 \(X\) 와 \(Y\) 의 confounder 존재.
U (confounder)
↓ ↓
X ──→ Y
회귀 \(Y \sim X\) 가 confounded.
해결: Instrumental Variable (IV) \(Z\).
Z ──→ X ──→ Y
↑ ↑
U (confounder)
조건:
- Relevance: \(Z\) 가 \(X\) 에 영향 (\(Z\) → \(X\))
- Exclusion: \(Z\) 가 \(Y\) 에 직접 영향 X (오직 \(X\) 통해서만)
- No common cause: \(Z\) 와 \(U\) 가 독립
IV 의 기능: \(Z\) 의 변동을 활용해 \(X\) → \(Y\) 를 confounding 없이 추정.
비유: 약물 효과 측정.
- 약 \(X\) 가 증상 \(Y\) 에 효과 (가설)
- 그러나 환자 특성 (severity) 이 둘 다 영향 (confounder)
- 단순 비교 (\(X = 1\) vs \(X = 0\)) 시 confounding bias
해결: 무작위 처방 (instrument \(Z\)).
- \(Z\) 가 약 처방 결정 (relevance)
- \(Z\) 자체가 환자 health 에 직접 영향 X (exclusion)
- \(Z\) 가 환자 severity 와 독립 (randomization)
\(Z\) 의 무작위성이 confounding 우회. \(X\) → \(Y\) 효과 = “\(Z\) 가 처방을 1 증가시킬 때 \(Y\) 변화” / “\(Z\) 가 \(X\) 변화시킬 정도”.
수식:
\[ \beta_{XY} = \frac{\text{Cov}(Z, Y)}{\text{Cov}(Z, X)} \]
5.2 AirCnC CSAT 사례
분석 질문: “CSAT 가 M6Spend 에 미치는 인과 효과?”
CD:
?? (confounders)
↓ ↓
CSAT ──→ M6Spend
가능한 confounders:
- Customer wealth (rich → high CSAT + high M6Spend)
- Customer loyalty (loyal → high CSAT + high M6Spend)
- Product quality experience (good experience → high CSAT + high M6Spend)
회귀 \(\text{M6Spend} \sim \text{CSAT}\) 가 confounded.
해결: Ch.10 의 SOP 실험 의 무작위 배정을 instrument 로.
SOP 무작위 배정 (Z) ──→ CSAT (X) ──→ M6Spend (Y)
↑ ↑
└─── confounders
조건 점검:
- Relevance: SOP 가 CSAT 에 영향 (Ch.10 실험에서 확인됨)
- Exclusion: SOP 자체가 M6Spend 에 직접 영향 X (CSAT 통해서만)
- No common cause: SOP 가 무작위 → confounders 와 독립
→ 3 조건 모두 만족. IV 적용 가능.
Exclusion: “\(Z\) 가 \(Y\) 에 직접 영향 안 줘야”.
SOP 사례 의문:
- 새 SOP 가 customer experience 자체 향상 → CSAT 변화 외 다른 path 로도 M6Spend 영향?
답:
- SOP 의 효과가 customer 의 satisfaction 변화로 channel
- 다른 메커니즘 (직접 spending 자극) 없음 → Exclusion 가정 합리적
만약 exclusion 의심:
- SOP 가 reps 의 cross-sell 능력 향상 → customer 추가 구매
- 그러면 SOP → M6Spend 직접 path 존재 → IV 가정 깨짐
- IV 추정 부정확
→ Exclusion 가정의 도메인 검토 필수.
5.3 2SLS (Two-Stage Least Squares)
2-stage least squares:
Stage 1: X = α_0 + α_Z * Z + ε → X̂ (predicted X)
Stage 2: Y = β_0 + β_X * X̂ + ε → β_X (causal effect)
해석:
- Stage 1: Z 의 변동으로 X 의 일부분 (X̂) 추출
- Stage 2: X̂ (= Z-driven X) 의 Y 에 대한 효과 추정
핵심: X̂ 가 confounder U 와 독립 (Z 의 무작위성 덕분) → 정확한 추정.
5.4 IV 의 결과 해석
Coefficient Std.Error
CSAT 45.0 12.0
age -1.5 0.5
reason_property -50.0 15.0
해석:
- CSAT 1 점 증가 → M6Spend +$45 (인과 효과)
- 만약 단순 회귀였다면 confounding 으로 다른 추정 (예: $80, 과대)
- IV 가 confounding 없는 깨끗한 추정
비즈니스 함의:
- CSAT 1 점 향상 → M6Spend $45 추가
- CSAT 향상 정책의 ROI 계산 가능
- “1 점 향상에 $20 비용 → ROI = $25/customer”
5.5 IV vs Mediation
같은 chain 의 다른 응용:
| 도구 | 가정 | 목적 | 결과 |
|---|---|---|---|
| Mediation | X → M → Y, X 가 random or unconfounded | 메커니즘 측정 | M 의 비율 |
| IV | Z → X → Y, Z random | Causal X→Y 추정 | \(\beta_{XY}\) unbiased |
핵심 차이:
- Mediation: X 자체가 독립적 (실험 또는 unconfounded)
- IV: X 가 confounded but Z 가 random
비즈니스 분석:
- 실험 가능 + 메커니즘 궁금: Mediation
- 실험 불가능 + 다른 random instrument 있음: IV
5.6 IV 의 함정
Relevance 가 약함 (Z 가 X 에 작은 영향):
F-statistic for instrument < 10
문제:
- Stage 1 의 X̂ 가 noise 많음
- Stage 2 의 추정 unstable
- Standard error 폭증
해결:
- 더 강한 instrument 찾기
- 또는 IV 안 사용 (다른 도구)
Z 가 Y 에 직접 영향:
SOP → reps 의 cross-sell skill → M6Spend
이 path 가 있으면 IV 가정 깨짐.
해결:
- 도메인 점검 (실험 디자인 시)
- 다른 instrument 시도
- Sensitivity analysis
IV 분석의 가장 어려운 부분 = 가정 검증 (수학으로 검증 불가).
6 코드 예시 — Mediation + IV 통합
6.1 Mediation 구현
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
# 가상 C-Mart 데이터
np.random.seed(42)
n = 5000
df = pd.DataFrame({
"play_area": np.random.binomial(1, 0.5, n),
})
# True coefficients
beta_xm = 12.6 # PA → VD
beta_my = 2.2 # VD → GP
beta_direct = 0.16 # PA → GP direct
df["visit_duration"] = (
23 + beta_xm * df["play_area"] + np.random.normal(0, 5, n)
)
df["grocery_purchases"] = (
50
+ beta_direct * df["play_area"]
+ beta_my * df["visit_duration"]
+ np.random.normal(0, 10, n)
)
# Mediation 분석
m_total = smf.ols("grocery_purchases ~ play_area", data=df).fit()
m_xm = smf.ols("visit_duration ~ play_area", data=df).fit()
m_my = smf.ols("grocery_purchases ~ play_area + visit_duration", data=df).fit()
beta_total_est = m_total.params["play_area"]
beta_xm_est = m_xm.params["play_area"]
beta_my_est = m_my.params["visit_duration"]
beta_direct_est = m_my.params["play_area"]
beta_indirect_est = beta_xm_est * beta_my_est
pm = beta_indirect_est / beta_total_est
print(f"=== Mediation 분석 ===")
print(f"Total Effect: {beta_total_est:.2f}")
print(f"Indirect Effect (mediated): {beta_indirect_est:.2f}")
print(f"Direct Effect: {beta_direct_est:.2f}")
print(f"Percentage Mediated: {pm:.2%}")예상:
- Total: ~27.9 (12.6 × 2.2 + 0.16 = 27.88)
- Indirect: ~27.7
- Direct: ~0.16
- PM: ~99%
진짜 값과 가까움 → 추정 정확.
비즈니스 보고:
“PA 효과 99% 가 visit duration 통한 mediation. PA 자체의 직접 효과 미미. Visit duration 늘리는 다른 정책도 같은 효과 가능.”
6.2 Bootstrap CI
def bootstrap_mediation(df, B=1000):
"""Mediation 통계량의 Bootstrap CI."""
results = {"total": [], "indirect": [], "direct": [], "pm": []}
for _ in range(B):
sample = df.sample(len(df), replace=True)
mt = smf.ols("grocery_purchases ~ play_area", data=sample).fit()
mxm = smf.ols("visit_duration ~ play_area", data=sample).fit()
mmy = smf.ols("grocery_purchases ~ play_area + visit_duration", data=sample).fit()
bt = mt.params["play_area"]
bxm = mxm.params["play_area"]
bmy = mmy.params["visit_duration"]
bd = mmy.params["play_area"]
results["total"].append(bt)
results["indirect"].append(bxm * bmy)
results["direct"].append(bd)
results["pm"].append((bxm * bmy) / bt)
print("\n=== Bootstrap 90% CI ===")
for key, values in results.items():
ci = np.percentile(values, [5, 95])
print(f" {key}: [{ci[0]:.3f}, {ci[1]:.3f}]")
bootstrap_mediation(df)각 추정의 robustness:
- Total CI 좁음 → 신뢰
- Indirect CI 좁음 → mediation 강함
- Direct CI 가 0 포함 → direct effect 무관
- PM CI 가 95~100% → near full mediation
분석가의 결론:
- “Mediation 강하고 robust”
- 비즈니스 의사결정 진행
6.3 IV 시뮬레이션
# IV 사례 — CSAT → M6Spend with confounding
np.random.seed(42)
n = 5000
# Confounder
unobserved_loyalty = np.random.normal(0, 1, n)
# Instrument (random)
sop = np.random.binomial(1, 0.5, n)
# X (CSAT) — affected by both Z and U
csat = (
7
+ 0.5 * sop # SOP → CSAT
+ 0.8 * unobserved_loyalty # U → CSAT
+ np.random.normal(0, 0.5, n)
)
# Y (M6Spend) — affected by X and U
true_beta_csat = 45
m6spend = (
100
+ true_beta_csat * csat
+ 50 * unobserved_loyalty # U → M6Spend (confounding)
+ np.random.normal(0, 30, n)
)
df_iv = pd.DataFrame({
"csat": csat,
"m6spend": m6spend,
"sop": sop,
})
# Naive OLS (confounded)
m_ols = smf.ols("m6spend ~ csat", data=df_iv).fit()
print(f"=== Naive OLS ===")
print(f" CSAT coef: {m_ols.params['csat']:.2f} (true = {true_beta_csat})")
print(f" Bias: {m_ols.params['csat'] - true_beta_csat:.2f}")
# IV (2SLS)
from linearmodels.iv import IV2SLS
# linearmodels 가 import 되어 있다고 가정
try:
iv_result = IV2SLS(
dependent=df_iv["m6spend"],
exog=None,
endog=df_iv[["csat"]],
instruments=df_iv[["sop"]],
).fit()
print(f"\n=== IV (2SLS) ===")
print(f" CSAT coef: {iv_result.params['csat']:.2f} (true = {true_beta_csat})")
print(f" Bias: {iv_result.params['csat'] - true_beta_csat:.2f}")
except ImportError:
# linearmodels 없는 경우 manual 2SLS
# Stage 1
s1 = smf.ols("csat ~ sop", data=df_iv).fit()
df_iv["csat_hat"] = s1.predict()
# Stage 2
s2 = smf.ols("m6spend ~ csat_hat", data=df_iv).fit()
print(f"\n=== Manual 2SLS ===")
print(f" CSAT coef: {s2.params['csat_hat']:.2f} (true = {true_beta_csat})")예상 결과:
- Naive OLS: \(\beta \approx 70\) (overestimate 가짜 상관)
- IV: \(\beta \approx 45\) (정확)
OLS bias = 25 (큰 편향).
이유:
- U (loyalty) 가 양쪽에 영향 → confounding
- Naive 가 그 영향을 CSAT 의 효과로 흡수
- IV 가 SOP 의 random variation 만 활용 → confounding 없음
비즈니스 함의:
- 단순 회귀로는 CSAT 의 효과 과대 추정
- IV 로 진짜 ROI 측정 가능
- “CSAT +1 점 → M6Spend +$45” 정확
→ IV 의 가치는 진짜 인과 효과 추정.
7 종합 — 분석가의 결정 트리
1. 분석 질문?
"X 의 Y 에 대한 메커니즘?" → Mediation
"X 의 Y 에 대한 인과 효과?" → IV (confounding 의심 시)
"X 의 Y 에 대한 평균 효과?" → 단순 회귀 (가능 시)
2. Mediation:
a. Mediator 후보 식별 (도메인 직관)
b. Total / Indirect / Direct 추정
c. PM 계산
d. Bootstrap CI
e. Multicollinearity 점검
f. Full vs Partial 결정
3. IV:
a. Instrument 후보 식별
b. 3 조건 점검 (Relevance, Exclusion, No common cause)
c. 2SLS 실행
d. F-statistic 점검 (weak instrument 위험)
e. OLS 와 비교 (bias 의 크기)
4. 보고서:
- 메커니즘 (mediation 의 PM)
- 인과 효과 (IV 의 β)
- 한계 (Exclusion 가정 등)
이 워크플로가 mediation/IV 의 표준.
8 관련 주제
8.1 Ch.12 의 형제 글
- E-BUI12-1 매개 효과 3 단계 회귀 — Mediation 자세히
- E-BUI12-2 매개 비율과 이항 매개 — 이항 mediator
- E-BUI12-3 매개 × 조절 결합 — 결합 분석
- E-BUI12-4 도구변수와 2SLS — IV 자세히
8.2 이전 챕터
- E-BUI3-2 체인과 포크 구조 — Mediator 정의
- E-BUI11-0 Moderation overview — Mediator vs Moderator
8.3 Hernan 정통 cross-link
- Causal_Inference/14 (예정) IV — IV 의 학술적 처리
- Causal_Inference/12 (예정) Mediation Analysis — Mediation 의 학술
8.4 카테고리 진입점
- Experimentation 학습 로드맵 — 11 Phase × 7 교재 매핑