Tech PostsTech Posts
실험 설계Experimental Design · 11 / 24
11 실험 설계Experimental Design

무작위 배정을 했는데 왜 통제변수를 넣는가You Randomised. So Why Add Control Variables?

편향을 없애려는 게 아닙니다. 없앨 편향이 없으니까요. 정밀도를 사려는 것이고 그건 공짜로 표본을 두 배 늘리는 것과 같습니다.Not to remove bias — there is none to remove. For precision, which is the same as doubling your sample for free.

무작위 배정만으로 평균 차이가 이미 불편추정량인데, 왜 실험에 통제변수를 넣을까요?

If randomisation already makes the difference in means unbiased, why would you ever add control variables to an experiment?

편향을 없애려는 게 아닙니다. 없앨 편향이 없습니다. 정밀도 때문입니다. 결과를 예측하는 처치 이전 변수는 오차항에 앉아 있었을 분산을 흡수합니다. 오차 분산이 작아지면 같은 추정치 주위의 신뢰구간이 좁아집니다. 실무에서 이건 실험 분석이 내놓을 수 있는 가장 수익률 높은 수에 듭니다. 사전 기간 예측변수가 강한 지표라면 필요 표본을 절반 이하로 줄일 수 있고 비용은 없습니다.

Not to remove bias — there is none to remove. For precision. A pre-treatment covariate that predicts the outcome absorbs variance that would otherwise sit in the error term, and a smaller error variance means a tighter interval around the same estimate. In practice this is one of the highest-return moves available in experimental analysis: on outcomes with a strong pre-period predictor it can cut the required sample by half or more, for free.

정밀도 논증The precision argument

Y = α + τ · D + Xβ + ε
D는 무작위 배정된 처치 지시변수, X는 처치 이전 공변량 벡터입니다.D is the randomised treatment indicator, X a vector of pre-treatment covariates.

D가 무작위 배정되었으므로 X와 독립입니다. X를 넣어도 τ가 추정하는 대상은 바뀌지 않습니다. 직교하는 회귀변수를 빠뜨려도 누락변수 편의가 생기지 않기 때문입니다. 대신 잔차 분산은 바뀝니다. Y 중 X가 설명하는 부분은 더 이상 ε이 흡수하지 않아도 됩니다.

Because D was randomised, it is independent of X. Adding X therefore does not change what τ estimates — omitting an orthogonal regressor causes no omitted-variable bias. But it does change the residual variance: whatever part of Y that X explains no longer has to be absorbed by ε.

τ̂의 표준오차는 잔차 표준편차에 비례하므로 이득이 직접적입니다. X가 Y 분산의 절반을 설명하면 표준오차가 약 √2배 줍니다. 표본을 두 배로 늘린 것과 같습니다.

The standard error of τ̂ is proportional to the residual standard deviation, so the gain is direct. If X explains half the variance in Y, the standard error falls by roughly a factor of √2 — equivalent to having doubled your sample.

가장 좋은 공변량 하나는 거의 항상 결과 변수 자신의 처치 이전 값입니다. 사전 전환율이 사후 전환율을 예측하고 지난달 지출이 이번 달 지출을 예측합니다. 테크 업계에서 CUPED라고 부르는 기법이 이것인데 이름만 새로울 뿐 공변량 조정입니다.

The best single covariate is almost always the pre-treatment value of the outcome itself. Baseline conversion predicts post-period conversion; last month spend predicts this month. This is what the tech industry calls CUPED — the name is new, the technique is covariate adjustment.

python
import numpy as np
import statsmodels.api as sm

rng = np.random.default_rng(5)
TRUE_EFFECT = 1.0

def one_run(n=1_000, rho=0.8):
    baseline = rng.normal(size=n)                       # pre-period outcome
    treated = rng.binomial(1, 0.5, n)                   # randomised
    y = TRUE_EFFECT * treated + rho * baseline + rng.normal(
        scale=np.sqrt(1 - rho**2), size=n)

    naive = sm.OLS(y, sm.add_constant(treated)).fit()
    adjusted = sm.OLS(y, sm.add_constant(
        np.column_stack([treated, baseline]))).fit()
    return naive.params[1], adjusted.params[1]

runs = np.array([one_run() for _ in range(2_000)])
for i, label in enumerate(["unadjusted", "adjusted"]):
    print(f"{label:>11}  mean={runs[:, i].mean():.4f}  sd={runs[:, i].std():.4f}")
print(f"\nprecision gain: {runs[:, 0].std() / runs[:, 1].std():.2f}x"
      f"  -> equivalent to {(runs[:, 0].std()/runs[:, 1].std())**2:.1f}x the sample")
사전 기간 결과가 사후 결과를 0.8의 상관으로 예측하는 경우입니다.The pre-period outcome predicts the post-period outcome with correlation 0.8.
 unadjusted  mean=1.0007  sd=0.0632
   adjusted  mean=1.0003  sd=0.0379

precision gain: 1.67x  -> equivalent to 2.8x the sample

두 추정량 모두 참 효과에 모입니다. 편향이 생기지 않았다는 확인입니다. 다른 건 퍼짐입니다. 여기서는 표준오차가 40% 줄었고 표본을 2.8배 늘린 것과 같은 효과입니다. 공변량을 하나 더한 대가로요.

Both estimators centre on the true effect — confirmation that adding controls introduced no bias. What differs is the spread: the standard error fell 40%, equivalent to running the experiment with 2.8 times the sample. For the cost of one extra column.

얼마나 좁아지는지는 전적으로 공변량이 결과를 얼마나 잘 예측하느냐에 달려 있습니다. 순수한 잡음이면 얻는 게 없고 자유도만 조금 잃습니다. 실험을 설계하기 전에 자기 사전 기간 데이터로 확인해 볼 값어치가 있습니다. 필요한 표본 크기가 여기서 직접 결정되기 때문입니다.

How much tighter depends entirely on how strongly the covariates predict the outcome. If they are pure noise you gain nothing and lose a little (each control costs a degree of freedom). Worth checking against your own pre-period data before designing an experiment, because it directly determines the sample size you need.

유효성을 지키는 규칙The rule that keeps it valid

처치가 영향을 줄 수 있었던 변수를 조건으로 두면 무작위 배정이 없앤 편향이 정확히 되돌아옵니다. 처치가 인게이지먼트를 올리는데 인게이지먼트를 통제하면 재려던 효과의 일부를 제거한 것이고 남은 추정치에는 깨끗한 해석이 없습니다. 더 나쁘게는, 처치와 결과의 공통 결과(충돌부)를 조건으로 두면 존재하지 않던 연관을 만들어 냅니다.

Conditioning on a post-treatment variable — one that treatment could have affected — reintroduces exactly the bias randomisation eliminated. If your treatment increases engagement and you control for engagement, you have removed part of the very effect you set out to measure, and the remaining estimate has no clean interpretation. Worse, conditioning on a common consequence of treatment and outcome (a collider) can manufacture an association where none exists.

안전한 검사는 시간순입니다. 이 단위가 다른 팔에 배정됐다면 이 변수가 달라졌을 수 있는가? 그렇다면 빼십시오.

The safe test is chronological: could this variable have been different if the unit had been assigned to the other arm? If yes, leave it out.

못지않게 중요한 두 번째 규율은 어떤 공변량을 쓸지 미리 정해 두는 것입니다. 여러 조합을 시도하고 p값이 가장 작은 것을 보고하면 유효한 절차가 낚시 원정으로 바뀝니다. 결과를 보기 전에 설정을 적어 두십시오.

A second discipline matters just as much: pre-specify which covariates you will use. Trying several sets and reporting the one with the smallest p-value converts a valid procedure into a fishing expedition. Write the specification down before you look at outcomes.

실무에서In practice

  • 사전 기간 결과를 먼저 쓰십시오. 이국적인 걸 더하기 전에 재려는 지표의 기저값을 넣으십시오. 거의 항상 가장 강한 예측변수이고, 그 하나가 얻을 수 있는 이득의 대부분을 가져갑니다.
  • 조정은 무작위 배정의 대체물이 아닙니다. 실험에서 통제변수는 정밀도를 삽니다. 관측 데이터에서 공변량을 통제하는 것은 식별을 사려는 시도이고 훨씬 까다로우며 모든 교란변수를 통제했을 때만 작동합니다. 뒤따르는 인과추론 편들의 주제이고 그래서 더 어렵습니다.
  • 소표본에서 회귀 조정을 조심하십시오. Freedman은 OLS 조정이 유한표본에서 약간 편향될 수 있고 처치 비율이 불균등하면 정밀도를 오히려 떨어뜨릴 수 있음을 보였습니다. Lin의 상호작용 조정 추정량 — 처치를 중심화한 공변량과 교차 — 이 둘 다 해결하고 N이 작거나 분할이 50/50에서 멀 때 안전한 기본값입니다.
  • 가능하면 설계 시점에 층화하거나 블록화하십시오. 층 안에서 무작위 배정하면 층화 변수의 균형이 기댓값이 아니라 보장으로 확보됩니다. 사후에 불균형을 고치는 것보다 엄격히 낫고 비용도 없습니다. 분석에 층 지시변수를 넣는 것만 잊지 마십시오.
  • 둘 다 보고하십시오. 조정하지 않은 평균 차이와 조정한 추정치를 함께 보이십시오. 크게 벌어지면 그 자체가 정보입니다. 대개 강한 예측변수에서 우연한 불균형이 있었다는 신호이고 묻어 두는 것보다 드러내는 편이 낫습니다.
  • 이질적 효과는 다른 도구가 필요합니다. 공변량을 통제변수로 넣는 것은 하나의 평균 효과를 더 정밀하게 추정합니다. 효과가 집단별로 다른지는 말해 주지 않습니다. 미리 정한 소수의 부분집단이면 상호작용항이 답하고 데이터 주도로 이질성을 찾으려면 인과 숲이 현대적 접근입니다. 둘 다 다중비교에 주의해야 합니다.
  • Use the pre-period outcome first. Before adding anything exotic, add the baseline value of the metric you are measuring. It is nearly always the strongest available predictor, and one covariate captures most of the achievable gain.
  • Adjustment is not a substitute for randomisation. These controls buy precision in an experiment. In observational data, controlling for covariates is an attempt to buy identification, which is far more demanding and only works if you have controlled for every confounder. That is the subject of the causal inference posts, and the reason they are harder.
  • Beware regression adjustment in small samples. Freedman showed OLS adjustment can be slightly biased in finite samples and can even reduce precision when treatment shares are unequal. Lin interaction-adjusted estimator — interacting treatment with demeaned covariates — fixes both and is a safe default when N is small or the split is far from 50/50.
  • Stratify or block at design time if you can. Randomising within strata guarantees balance on the stratifying variables rather than merely achieving it in expectation. This is strictly better than fixing imbalance afterwards and costs nothing. Just remember to include the strata indicators in the analysis.
  • Report both. Show the unadjusted difference in means and the adjusted estimate. If they diverge substantially that is informative — it usually signals chance imbalance on a strong predictor, and it is better surfaced than buried.
  • Heterogeneous effects need a different tool. Adding covariates as controls estimates a single average effect more precisely. It says nothing about whether the effect differs across groups. Interactions answer that for a few pre-specified subgroups; for data-driven discovery, causal forests are the modern approach. Both require care about multiple comparisons.

다음 편은 시뮬레이션에서 이 모든 것의 가장 흔한 실제 응용으로 넘어갑니다. 온라인 A/B 테스트, 그리고 그것을 계속 들여다보는 행위가 통계적 보장을 어떻게 무너뜨리는지입니다.

The next post moves from simulation to the most common real-world application of all this: the online A/B test, and the specific way that continuously monitoring one destroys its statistical guarantees.