무작위 배정은 이 시리즈 전체에서 인과추론 문제를 정면으로 푸는 유일한 기법입니다. 뒤따르는 인과추론 섹션은 전부 무작위 배정을 할 수 없었던 상황의 우회로입니다. 그러니 그것이 정확히 무엇을 사 주는지 알아 둘 값어치가 있고 이 편은 그걸 시뮬레이션으로 합니다. 참값을 아는 세계를 만들고 추정량이 그걸 되찾아 오는지 봅니다.
Randomisation is the only technique in this entire series that solves the causal inference problem outright. Everything in the Causal Inference section that follows is a workaround for situations where you could not randomise. So it is worth understanding precisely what randomisation buys you, and this post does that by simulation: build a world where the true effect is known, then check whether the estimator recovers it.
무작위 배정이 푸는 문제The problem randomisation solves
각 단위에는 잠재적 결과가 둘 있습니다. 처치받았을 때의 Y(1)과 받지 않았을 때의 Y(0)입니다. 그 단위의 인과효과는 Y(1) − Y(0)입니다.
For each unit there are two potential outcomes: Y(1), what happens if treated, and Y(0), what happens if not. The causal effect for that unit is Y(1) − Y(0).
둘을 동시에 관측할 수는 없습니다. 처치하면 Y(0)이 영원히 사라지고 두면 Y(1)이 사라집니다. 이것이 인과추론의 근본 문제, 최악의 형태를 한 결측 데이터 문제입니다. 구성상 언제나 정확히 절반이 없습니다.
You can never observe both. Treat someone and Y(0) is gone forever; leave them alone and Y(1) is. This is the fundamental problem of causal inference, and it is a missing data problem of the worst kind: exactly half the data is missing, always, by construction.
개별 효과를 되찾을 수 없으니 평균처치효과 E[Y(1) − Y(0)]를 노립니다. 순진한 추정량은 처치군과 대조군의 관측 평균 차이입니다. 분해하면 이렇습니다.
Since individual effects are unrecoverable, we aim for the average treatment effect, E[Y(1) − Y(0)]. The naive estimator is the difference in observed means. Decomposed, that difference equals:
ATE + ( E[Y(0) | 처치] − E[Y(0) | 비처치] )아픈 사람이 치료를 찾고, 의욕적인 직원이 교육에 등록하고, 성장하는 기업이 새 소프트웨어를 도입합니다. 관측 데이터에서 이 항은 대체로 크고 부호조차 모르는 경우가 많습니다.
Sick people seek treatment, motivated employees enrol in training, growing firms adopt new software. In observational data this term is generally large and its sign is often unknown.
실무에서 중요한 단서 둘을 붙여 둡니다.
Two clarifications that matter in practice.
- 무작위 배정이 모든 표본에서 모든 공변량을 균형 맞추지는 않습니다. 기댓값에서 맞춥니다. 한 번의 추출이 우연히 더 나이 많거나 더 부유한 처치군을 만들 수 있습니다. 무작위 배정은 그 불균형이 체계적이지 않고 무작위라는 점을 보장합니다. 그래서 반복하면 평균으로 사라지고 표준오차가 그것을 올바르게 반영합니다.
- 불편성은 절차의 성질이지 당신의 실험 하나의 성질이 아닙니다. 시뮬레이션이 이걸 배우는 올바른 방법인 이유가 바로 이것입니다. 실험을 한 번 돌려서는 편향을 알 길이 없습니다. 만 번 돌려서 추정치가 참값에 모이는 걸 보면 전부 알 수 있습니다.
- Randomisation does not balance every covariate in every sample. It balances them in expectation. Any single draw can produce a treatment group that is older or richer by chance. What randomisation guarantees is that this imbalance is random rather than systematic, so it averages out across repetitions and is correctly accounted for by the standard error.
- Unbiasedness is a property of the procedure, not of your one experiment. This is exactly why simulation is the right way to learn it. Running the experiment once tells you nothing about bias. Running it ten thousand times and watching the estimates centre on the truth tells you everything.
몬테카를로가 하는 일What Monte Carlo simulation is for
아래 구조는 이 시리즈 나머지의 작업 패턴입니다.
The structure below is the workhorse pattern for the rest of this series.
- 자료생성과정을 적습니다. 모수를 당신이 고르므로 참 효과를 압니다.
- 거기서 데이터셋을 하나 생성합니다.
- 추정량을 적용하고 추정치를 기록합니다.
- 여러 번 반복하고 추정치의 분포를 봅니다.
- Write down a data generating process. You choose the parameters, so you know the true effect.
- Simulate a dataset from it.
- Apply your estimator and record the estimate.
- Repeat many times and examine the distribution of estimates.
그 분포가 데이터 하나로는 답할 수 없는 질문들에 답합니다. 추정량이 불편인가(추정치 평균이 참 모수와 같은가), 얼마나 정밀한가(추정치의 퍼짐이 곧 참 표준오차이고 이것으로 보고된 표준오차가 정직한지 확인할 수 있습니다), 검정의 크기가 맞는가(명목 5% 검정이 참인 귀무가설을 5%에서 기각하는가), 검정력은 얼마인가.
That distribution answers questions no single dataset can. Is the estimator unbiased — does the mean of the estimates equal the true parameter? How precise is it — the spread of estimates is the true standard error, against which you can check whether your reported standard errors are honest. Does the test have correct size — does a nominal 5% test reject a true null 5% of the time? And what is its power?
실제 데이터에서는 참값을 모르므로 이 중 어느 것도 얻을 수 없습니다. 추정량이 실제로 검증되는 방식이 시뮬레이션인 이유입니다.
You cannot get any of these from real data, because with real data you never know the truth. This is why simulation is how estimators are actually validated.
import numpy as np
rng = np.random.default_rng(42)
TRUE_EFFECT = 2.0
def one_experiment(n, selection_bias=False):
"""Simulate one experiment and return the difference in means."""
ability = rng.normal(size=n) # unobserved driver of outcome
if selection_bias:
# people with higher ability opt in - the observational case
treated = (ability + rng.normal(size=n) > 0).astype(int)
else:
treated = rng.binomial(1, 0.5, n) # coin flip - independent of ability
y = 1.0 + TRUE_EFFECT * treated + 2.0 * ability + rng.normal(size=n)
return y[treated == 1].mean() - y[treated == 0].mean()
for label, biased in [("randomised", False), ("self-selected", True)]:
estimates = np.array([one_experiment(500, biased) for _ in range(5_000)])
print(f"{label:>14} mean={estimates.mean():.3f} "
f"sd={estimates.std():.3f} bias={estimates.mean()-TRUE_EFFECT:+.3f}") randomised mean=2.001 sd=0.199 bias=+0.001
self-selected mean=3.128 sd=0.171 bias=+1.128
자기선택 버전이 더 정밀합니다. 표준편차가 더 작습니다. 그리고 56% 틀렸습니다. 정밀도는 정확성이 아니고 이 구분이 인과추론 섹션 전체를 관통합니다.
The self-selected version is more precise — its standard deviation is smaller. And it is 56% wrong. Precision is not accuracy, and that distinction runs through the entire causal inference section.
시뮬레이션이 보여 주는 두 가지Two things the simulation shows
추정치가 참값에 모입니다. 반복 평균이 참 처치효과에 앉습니다. 개별 반복은 높거나 낮게 흩어지지만 어느 쪽으로도 체계적 당김이 없습니다. 그것이 불편성이고 이제는 들은 게 아니라 본 것입니다.
The estimates centre on the truth. Averaged over replications, the difference in means lands on the true effect. Individual replications scatter high and low, but there is no systematic pull in either direction. That is unbiasedness, and you have now watched it happen rather than been told about it.
퍼짐이 √n으로 줄어듭니다. 표본을 네 배로 하면 추정치의 표준편차가 절반이 됩니다. 첫 편의 중심극한정리 결과가 가장 실무적으로 중요한 형태로 다시 나타난 것입니다. 실험이 커야 하는 이유이자 추가 표본의 한계 가치가 체감하는 이유입니다.
The spread shrinks with √n. Quadruple the sample and the standard deviation of the estimates halves. This is the Central Limit Theorem result from the first post, reappearing in its most practically important form: it is why experiments need to be large, and why the marginal value of extra sample declines.
실무에서In practice
- 분석할 단위에서 무작위 배정하십시오. 처치가 매장 수준에서 배정되었는데 개별 거래를 분석하면 유효 표본은 거래 수가 아니라 매장 수입니다. 거래로 계산한 표준오차는 훨씬 작게 나옵니다. 표준오차는 항상 무작위화 수준에서 클러스터링하십시오.
- 균형은 확인하되 검정하지는 마십시오. 팔별 공변량 평균을 보고하는 건 좋은 습관입니다. 무작위화가 조용히 실패한 구현 버그를 잡아 줍니다. 하지만 그 표에 유의성 검정을 돌리는 건 일관되지 않습니다. 당신이 무작위화했으므로 귀무가설이 참임을 이미 압니다. 공변량 20개면 정의상 하나는 p < 0.05에서 불균형합니다. 중요한 건 불균형의 크기이지 p값이 아닙니다.
- 사람이 이탈한 뒤에는 무작위 배정이 아무것도 보장하지 않습니다. 이탈이 처치와 관련되면 보장이 깨집니다. 처치군이 연구를 떠날 가능성이 더 높으면 남은 두 집단은 더 이상 비교 가능하지 않습니다. 팔별 이탈률을 1순위 진단으로 추적하고 차등 이탈이면 Lee 경계를 고려하십시오.
- 불응은 추정 대상을 바꿉니다. 배정이 실제 처치를 결정하지 않을 때 — 프로그램에 배정됐지만 한 번도 참석하지 않은 사람 — 배정으로 비교하면 의도치료 효과가 나옵니다. 불편이지만 처치 자체의 효과와는 다른 질문에 답합니다. 후자를 되찾으려면 배정을 도구변수로 쓰는 IV가 필요합니다. 이 시리즈 뒤편의 주제입니다.
- 간섭은 핵심 가정을 깹니다. SUTVA는 한 단위의 처치가 다른 단위의 결과에 영향을 주지 않을 것을 요구합니다. 마켓플레이스(한 구매자의 할인이 다른 구매자가 마주하는 가격에 영향), 소셜 네트워크, 공유 자원 제약이 있는 곳에서 깨집니다. 클러스터나 스위치백 설계가 정확히 이 경우를 위해 있습니다.
- 검정력 계산은 실험 전에 하는 것이지 후에 하는 게 아닙니다. 검출할 값어치가 있는 최소 효과를 정하고 그것을 검출하는 데 필요한 표본을 계산하십시오. 검정력이 부족한 실험은 없느니만 못합니다. 진짜 효과를 놓칠 뿐 아니라 검출해 낸 효과는 체계적으로 과장됩니다. 유난히 큰 표집 추출만이 유의 문턱을 넘기 때문입니다. 관측된 효과로 사후 계산한 검정력은 정보가 없으므로 보고하지 마십시오.
- Randomise the unit you will analyse. If treatment is assigned at the store level but you analyse individual transactions, your effective sample is the number of stores, not transactions. Standard errors computed on transactions will be far too small. Always cluster at the level of randomisation.
- Check balance, but do not test it. Reporting covariate means by arm is good practice — it catches implementation bugs such as a randomisation that silently failed. But running significance tests on that table is incoherent: you know the null is true, because you randomised. With twenty covariates you expect one imbalance at p < 0.05 by definition. What matters is the magnitude, not the p-value.
- Randomisation guarantees nothing after people drop out. Attrition breaks the guarantee if it is related to treatment. If the treated group is more likely to leave, the remaining groups are no longer comparable. Track attrition by arm as a first-order diagnostic, and consider Lee bounds when it is differential.
- Non-compliance changes what you estimate. When assignment does not determine actual treatment — people assigned to a programme who never attend — comparing by assignment gives the intention-to-treat effect. That is unbiased but answers a different question than the effect of the treatment itself. Recovering the latter requires instrumental variables, using assignment as the instrument, which is a later post.
- Interference violates the core assumption. SUTVA requires that one unit treatment does not affect another outcome. This fails in marketplaces (a discount for one buyer affects the price another faces), social networks, and anywhere with a shared resource constraint. Cluster or switchback designs exist for exactly this case.
- Power calculations come before the experiment, not after. Decide the minimum effect worth detecting, then compute the sample needed. An underpowered experiment is worse than none: it not only misses real effects, but the effects it does detect are systematically overstated, because only unusually large sampling draws clear the significance threshold. Post-hoc power computed from the observed effect is not informative and should not be reported.
다음 편은 이 틀에 공변량을 더합니다. 처치 이전 변수를 조건으로 두면 편향 없이 정밀도가 올라간다는 이야기입니다.
The next post extends this framework with covariates, showing how conditioning on pre-treatment variables improves precision without introducing bias.