Estimating Personalization Impact via AB Test Covariate Adjustment
Statistics & ExperimentsModel answerLast updated
Analyze an A/B test on content recommendation by calculating the ATE, deriving robust 95% confidence intervals, and evaluating covariate adjustment techniques like Lin's regression.
You are analyzing data from an A/B experiment designed to test a novel personalized recommendation system against the standard non-personalized baseline.
The dataset is formatted with one record per user and contains the following fields:
user_id: Unique identifier for each participanttreat: Binary indicator (1 if assigned to the personalized experience, 0 if control)minutes_streamed: Continuous numeric outcome representing cumulative watch time (in minutes) over a 7-day post-assignment evaluation period- Pre-experiment features (pre-treatment covariates): e.g.,
prior_7d_minutes,tenure_days,is_premium,device_type,country(some variables may be non-informative or noisy)
Your Objectives:
- Detail how to compute the Average Treatment Effect (ATE) of personalization on total streaming time.
- Formulate a 95% confidence interval for your ATE point estimate and explain the statistical underpinnings of your chosen variance calculation method.
- Discuss the theoretical and practical implications of incorporating pre-experiment covariates into your estimation model. Address why including uninformative covariates typically does or does not introduce estimation bias or inflate error bounds.
Assumptions & Operational Rules:
- Randomization is performed independently at the user level with no interference between subjects (SUTVA holds).
- All reported confidence intervals should be two-sided at $\alpha = 0.05$.
- Post-treatment mediators are excluded from the covariate set; all auxiliary attributes reflect user state strictly prior to assignment.
Hints
Hint 1
Recall how the Neyman variance estimator accounts for potential heteroskedasticity (differing variances between control and treatment groups) without relying on equal-variance assumptions.
Hint 2
Consider how covariate adjustment via OLS can introduce bias in small samples if treatment effects interact with pre-treatment features, and how Lin's (2013) interacted model resolves this issue.
Hint 3
Distinguish between pre-treatment covariates and post-treatment variables; why does conditioning on post-treatment data corrupt the ATE estimate?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Estimand Definition & Pre-Analysis Checks
Under the Rubin Causal Model, each user $i$ has potential outcomes $Y_i(1)$ (streaming minutes under personalization) and $Y_i(0)$ (streaming minutes under control). The Average Treatment Effect (ATE) is defined as:
$$\tau = \mathbb{E}[Y(1) - Y(0)]$$
Because randomization is assigned at the individual user level and the Stable Unit Treatment Value Assumption (SUTVA) holds: $$\mathbb{E}[Y | W=1] = \mathbb{E}[Y(1)] \quad \text{and} \quad \mathbb{E}[Y | W=0] = \mathbb{E}[Y(0)]$$
Pre-Analysis Diagnostics
Before running any estimator, perform two sanity checks:
- Sample Ratio Mismatch (SRM) Test: Conduct a Pearson chi-square goodness-of-fit test on the observed sample counts against the nominal allocation ratio (e.g., 50/50). An SRM indicates systemic assignment or logging pipeline failures.
- Covariate Balance Check: Compute the Standardized Mean Difference (SMD) across treatment arms for key baseline covariates (e.g.,
prior_7d_minutes). SMD values above $0.1$ signal baseline imbalance.
2. Unadjusted Estimation (Difference-in-Means)
The unbiased point estimator for the ATE is the difference in sample means:
$$\hat{\tau}_{\text{raw}} = \bar{Y}_1 - \bar{Y}_0$$
Variance & 95% Confidence Interval
Because personalization often changes the variance of user behavior (e.g., heavy streamers watch even more, shifting variance in the treatment arm), we avoid assuming homoskedasticity. We use Neyman's variance estimator (Welch's $t$-test setting):
$$\widehat{\text{Var}}(\hat{\tau}_{\text{raw}}) = \frac{s_1^2}{n_1} + \frac{s_0^2}{n_0}$$
Where $s_1^2$ and $s_0^2$ are the sample variances within the treatment and control arms, and $n_1, n_0$ are their respective sample sizes.
The two-sided 95% Confidence Interval is given by:
$$\hat{\tau}_{\text{raw}} \pm 1.96 \cdot \sqrt{\frac{s_1^2}{n_1} + \frac{s_0^2}{n_0}}$$
Note: Running an ordinary least squares (OLS) regression $Y = \alpha + \tau W + \epsilon$ with HC2 heteroskedasticity-robust standard errors yields an estimate identical to Neyman's variance in large samples.
3. Covariate-Adjusted Estimation (Lin's Interacted Regression)
While the unadjusted estimator is unbiased, user watch time has high baseline variance. Pre-treatment engagement metrics (such as prior_7d_minutes) often exhibit high correlation ($r \approx 0.6 - 0.8$) with post-period watch time. Using pre-treatment covariates allows us to filter out pre-existing variation, shrinking error bounds and boosting statistical power without altering the underlying estimand.
Simple ANCOVA vs. Lin (2013) Interacted Model
Standard ANCOVA fits $Y = \alpha + \tau W + \boldsymbol{\beta}^T \mathbf{X}$. However, Freedman (2008) showed that under heterogeneous treatment effects and unequal sample sizes, standard ANCOVA can lead to standard error estimates that are worse than the unadjusted difference-in-means.
To guarantee that covariate adjustment never decreases asymptotic efficiency, we use Lin's (2013) Interacted Regression:
- Mean-center all pre-treatment covariates across the combined sample: $\mathbf{X}^* = \mathbf{X} - \bar{\mathbf{X}}$.
- Fit the fully interacted OLS specification:
$$Y_i = \alpha + \tau W_i + \boldsymbol{\beta}^T \mathbf{X}_i^* + \boldsymbol{\gamma}^T (W_i \cdot \mathbf{X}_i^*) + \epsilon_i$$
- Estimate standard errors using HC2 or HC3 robust standard errors.
Why Lin's Model Works:
- Unbiased Point Estimate: Mean-centering ensures that the main coefficient $\hat{\tau}$ directly represents the ATE at the population mean of $\mathbf{X}$.
- Efficiency Guarantee: The interaction term allows treatment effects to vary across covariate sub-groups. Asymptotically, Lin's estimator is guaranteed to have variance less than or equal to the unadjusted difference-in-means.
Alternative Variance Estimation Methods
- CUPED (Controlled Experiment Using Pre-Experiment Data): Equivalent to single-covariate ANCOVA where $Y_{\text{adj}} = Y - \theta (X - \bar{X})$ with $\theta = \frac{\text{Cov}(Y, X)}{\text{Var}(X)}$.
- Non-parametric Bootstrap: Resample users with replacement within each arm ($n_1$ from treatment, $n_0$ from control), re-evaluate the full Lin regression pipeline on each draw, and compute the 2.5th and 97.5th percentiles of the resulting $\hat{\tau}$ distribution. This approach is particularly effective when dealing with skewed streaming distributions.
4. Inclusion of Covariates: Risks and Guidelines
| Scenario | Impact on Estimation | Operational Recommendation |
|---|---|---|
Informative Pre-Treatment Covariates (prior_7d_minutes) | Dramatically reduces residual variance ($1 - R^2$), increasing effective power. | Pre-specify inclusion in the experiment design protocol. |
| Irrelevant / Noisy Pre-Treatment Covariates | Under complete randomization, uninformative covariates are orthogonal to $W$. They do not introduce asymptotic bias. They consume 1 degree of freedom per term, inflating variance by $\approx k/n$. | Safe at large scale ($n > 10^5$), but eliminate high-cardinality noise features in small samples ($n < 10^3$). |
| Post-Treatment Variables (e.g., clicks during test) | Causes conditioning on a mediator / collider, inducing post-treatment selection bias and invalidating causal inference. | Strictly exclude any feature logged after assignment. |
| High-Dimensional Covariates ($k \approx n$) | Leads to severe OLS overfitting and underestimation of standard errors. | Use Lasso/Ridge for covariate selection, or cross-fit via Double/Debiased Machine Learning (DML). |
5. Skewness and Distributional Considerations
Streaming data typically exhibits a heavy right tail (power users) and a structural zero mass (inactive users).
- Winsorization (Capping): Extreme outliers can skew both $\hat{\tau}$ and its variance. Capping values at a high threshold (e.g., the 99.9th percentile computed across the baseline period) stabilizes variance. Note that this changes the target estimand to the ATE of winsorized minutes.
- Log Transformation: Transforming the outcome to $\log(\text{minutes} + 1)$ stabilizes variance but shifts the estimand from absolute change in average minutes to relative geometric shifts. For business reporting, compute the raw total ATE as the primary metric, while evaluating log-scaled models as secondary sensitivity checks.
6. Python Implementation
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from scipy import stats
def analyze_ab_test(
df: pd.DataFrame,
outcome: str = "minutes_streamed",
treatment: str = "treat",
covariates: list[str] = None
) -> dict:
"""
Computes unadjusted and Lin-adjusted ATE along with HC2 95% Confidence Intervals.
"""
if covariates is None:
covariates = []
# 1. SRM Check (Assuming equal 50/50 split target)
n_treat = df[treatment].sum()
n_control = len(df) - n_treat
srm_pvalue = stats.chisquare([n_control, n_treat]).pvalue
if srm_pvalue < 0.001:
print(f"WARNING: Potential Sample Ratio Mismatch detected! p = {srm_pvalue:.4f}")
# 2. Unadjusted Difference in Means (Welch's t-test / Neyman SE)
y_t = df.loc[df[treatment] == 1, outcome]
y_c = df.loc[df[treatment] == 0, outcome]
ate_raw = y_t.mean() - y_c.mean()
se_raw = np.sqrt(y_t.var(ddof=1) / len(y_t) + y_c.var(ddof=1) / len(y_c))
ci_raw = (ate_raw - 1.96 * se_raw, ate_raw + 1.96 * se_raw)
results = {
"srm_pvalue": srm_pvalue,
"unadjusted": {"ate": ate_raw, "se": se_raw, "ci": ci_raw}
}
# 3. Lin (2013) Interacted Regression Adjustment
if covariates:
df_lin = df.copy()
interact_terms = []
for col in covariates:
# Mean center numerical features
if np.issubdtype(df_lin[col].dtype, np.number):
df_lin[f"{col}_centered"] = df_lin[col] - df_lin[col].mean()
c_name = f"{col}_centered"
else:
c_name = col
interact_terms.append(c_name)
interact_terms.append(f"{treatment}:{c_name}")
formula = f"{outcome} ~ {treatment} + " + " + ".join(interact_terms)
model = smf.ols(formula=formula, data=df_lin).fit(cov_type="HC2")
ate_lin = model.params[treatment]
se_lin = model.bse[treatment]
ci_lin = (ate_lin - 1.96 * se_lin, ate_lin + 1.96 * se_lin)
results["lin_adjusted"] = {"ate": ate_lin, "se": se_lin, "ci": ci_lin}
return results