Propensity Score Matching for Non-Randomized Feature Opt-Ins
Statistics & ExperimentsModel answerLast updated
Learn how to apply propensity score matching to non-randomized feature opt-in data, covering causal assumptions, propensity score estimation, balance diagnostics, and alternative estimators.
You want to evaluate the causal impact of a new opt-in feature on 7-day retention (retained_7d).
Because users manually opt in after seeing a prompt, treatment is non-randomized: highly active or engaged users choose to adopt the feature at significantly higher rates. You are provided with an observational dataset containing:
user_id: Unique user identifieropt_in: Binary indicator (1 = opted in, 0 = exposed to prompt but did not opt in)- Pre-period covariates (e.g., historical session count, watch time, device type, region, account tenure)
retained_7d: Binary outcome indicator (1 = active 7 days post-exposure, 0 = churned)
Explain how you would structure an analysis using Propensity Score Matching (PSM) to isolate the feature's true causal effect. In your answer, address:
- Identification Assumptions: The formal causal assumptions required and real-world mechanisms that break them.
- Propensity Score Estimation & Feature Selection: How to select pre-period covariates, fit the model, and key traps to avoid.
- Matching Strategy & Support Constraints: Choosing distance metrics, setting calipers, and enforcing overlap.
- Balance Diagnostics: How to confirm covariate balance without looking at the outcome variable.
- Estimand Choice & Variance Quantification: Calculating ATT vs. ATE and properly computing standard errors.
- Sensitivity & Alternative Approaches: Methods to check for hidden bias, and alternative observational estimators if PSM performs poorly.
Hints
Hint 1
Restrict the study population strictly to users who were shown the prompt to prevent positivity violations.
Hint 2
Focus covariate selection on confounders and strong outcome predictors, while strictly excluding post-treatment variables.
Hint 3
Do not rely on t-test p-values for balance verification; rely on Standardized Mean Difference (SMD) and variance ratios.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Methodology Overview
Evaluating non-randomized feature adoption using a naive comparison between opt-in ($T=1$) and non-opt-in ($T=0$) users yields heavily biased estimates due to selection bias. Power users naturally opt in at higher rates and naturally exhibit higher baseline retention regardless of the feature.
Propensity score matching (PSM) treats the evaluation as a two-stage observational study:
- Design Stage: Model the selection process and create matched groups with balanced pre-treatment covariates without looking at the outcome variable.
- Analysis Stage: Estimate the treatment effect and uncertainty on the balanced matched sample.
1. Identification Assumptions
To give a causal interpretation to the matched outcome difference, four core identification assumptions must hold:
| Assumption | Definition | Failure Mode in This Context |
|---|---|---|
| Unconfoundedness (Conditional Ignorability) | $(Y(1), Y(0)) \perp T \mid X$<br>All variables jointly affecting opt-in choice and retention are captured in $X$. | Unobserved user motivation or intent (e.g., a user logged in specifically to binge a newly released show). |
| Positivity (Common Support) | $0 < P(T=1 \mid X) < 1$ for all valid $X$.<br>Every user profile has a non-zero probability of both opting in and opting out. | Extreme power users who always opt in, or legacy client devices where the prompt UI fails to display. |
| SUTVA (No Interference) | Unit $i$'s outcome depends only on $i$'s treatment state, with no varying treatment versions. | Social network interactions, shared household accounts, or backend infrastructure throttling. |
| No Post-Treatment Adjustment | $X$ contains only features established prior to prompt exposure. | Including activity logged after the prompt introduces mediator conditioning or collider bias. |
Handling Temporal Spikes: Users who opt in frequently do so during a temporary surge in engagement. If pre-period covariates are measured over too short a window, regression to the mean will corrupt the estimate. Include multiple historical lookback windows (e.g., 7-day, 14-day, 28-day totals) alongside pre-period growth trends to capture trajectory.
2. Propensity Score Estimation & Feature Selection
Covariate Selection Rules
- Include Confounders: Variables driving both $T$ (opt-in) and $Y$ (retention), such as historical active days, watch time, subscription status, region, and platform.
- Include Outcome Predictors: Features predicting $Y$ strongly (even if weakly correlated with $T$) reduce estimator variance.
- Exclude Pure Instruments: Features affecting only $T$ (e.g., experimental variations in prompt banner design) increase estimator variance and amplify bias from unobserved confounders.
- Exclude Post-Treatment Features: Exclude any metric recorded after the prompt exposure timestamp.
Modeling Strategy
Fit a parametric or non-parametric model to estimate $e(X) = P(T=1 \mid X)$:
- Model Options: Logistic regression with splines/interaction terms or a calibrated Gradient Boosted Decision Tree (GBDT).
- Matching Scale: Perform distance matching on the logit scale: $$\text{logit}(\hat{e}(X)) = \ln\left(\frac{\hat{e}(X)}{1 - \hat{e}(X)}\right)$$ Matching on the linear propensity score avoids compression artifacts near 0 and 1.
- Objective: The goal of $e(X)$ estimation is covariate balance, not high classification accuracy. An AUC near or above $0.90$ indicates extreme non-overlap rather than a superior causal model.
3. Matching Implementation & Common Support
Choosing the Target Estimand
- ATT (Average Treatment Effect on the Treated): $E[Y(1) - Y(0) \mid T=1]$. Measures the impact on users who chose to opt in. This is usually the primary product target when deciding whether an opt-in feature creates value for its adopters.
- ATE (Average Treatment Effect): $E[Y(1) - Y(0)]$. Measures the impact if the feature were forcibly rolled out to all users. Requires strong two-sided overlap.
Matching Configuration (Targeting ATT)
- Algorithm: $1:k$ Nearest-Neighbor matching on the logit propensity score (typically $1:1$ or $1:2$).
- Caliper: Enforce a maximum distance bound of $0.2 \times \sigma_{\text{logit}}$ ($0.2$ standard deviations of the logit propensity score). Treated units without a control within the caliper are trimmed.
- Exact Matching: Enforce exact matches on coarse categorical variables such as platform/OS or geography.
- Replacement Strategy: Match with replacement if control units with high propensity scores are scarce. This reduces bias at the cost of higher estimator variance.
Enforcing Common Support
Drop treated units that fall outside the common support region. Always document and report the fraction and profile of dropped units, as trimming alters the effective target population.
4. Balance Verification Diagnostics
Never evaluate retention differences until covariate balance is confirmed using scale-invariant metrics:
- Standardized Mean Difference (SMD):
$$\text{SMD} = \frac{\bar{X}{\text{treated}} - \bar{X}{\text{control}}}{\sqrt{\frac{s_{\text{treated}}^2 + s_{\text{control}}^2}{2}}}$$
- Target: $|\text{SMD}| < 0.10$ across all baseline covariates ($|\text{SMD}| < 0.05$ for primary engagement signals).
- Variance Ratios: The ratio of covariate variances $s_{\text{treated}}^2 / s_{\text{control}}^2$ should lie between $0.5$ and $2.0$.
- Distributional Checks: Inspect Empirical Cumulative Distribution Functions (eCDFs) and propensity score density overlap plots.
- Placebo Tests: Verify that pre-period outcomes (e.g., retention status in the 7 days prior to prompt exposure) show no statistically significant difference across matched groups.
Note: Avoid relying on $t$-test $p$-values for balance checks. In large production datasets, negligible imbalances will trigger low $p$-values, whereas small datasets may hide substantial imbalances behind high $p$-values.
5. Effect Estimation & Uncertainty Quantification
Effect Calculation (ATT)
Compute the weighted average difference across matched pairs: $$\widehat{\text{ATT}} = \frac{1}{N_T} \sum_{i \in T} \left( Y_i - \sum_{j \in C(i)} w_{ij} Y_j \right)$$ To eliminate minor residual linear imbalances within matched pairs, fit a secondary bias-corrected regression of $Y$ on $T$ and $X$ inside the matched cohort.
Computing Standard Errors
- Matching with Replacement: Standard non-parametric bootstrapping is invalid for $1:1$ nearest-neighbor matching due to the discontinuous nature of nearest-neighbor assignment. Use Abadie–Imbens analytical standard errors or cluster-robust standard errors grouped on matched pair identifiers.
- Matching without Replacement: Use pair-clustered standard errors or a block bootstrap.
6. Sensitivity Analysis & Alternative Estimators
If unobserved confounding is suspected or PSM exhibits poor overlap, leverage diagnostic checks and alternative estimators:
- Rosenbaum Sensitivity Analysis: Quantify how strong an unobserved confounder $\Gamma$ would need to be to attribute the observed effect entirely to hidden bias.
- Inverse Probability of Treatment Weighting (IPTW): Instead of discarding units via matching, assign weights $w_i = \frac{T_i}{\hat{e}(X_i)} + \frac{1-T_i}{1-\hat{e}(X_i)}$ (for ATE) or $w_i = T_i + \frac{(1-T_i)\hat{e}(X_i)}{1-\hat{e}(X_i)}$ (for ATT). Apply stabilized weights and trimming to prevent extreme weight instability.
- Doubly Robust Estimation (AIPW): Combines an outcome regression model $\mu(X)$ with a propensity model $\hat{e}(X)$. The estimator yields unbiased causal results if either the propensity score model or the outcome regression model is correctly specified.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import NearestNeighbors
def estimate_att_psm(df, feature_cols, caliper_scale=0.2):
X = df[feature_cols].values
T = df["opt_in"].values
Y = df["retained_7d"].values
# 1. Fit propensity model
ps_model = LogisticRegression(max_iter=1000).fit(X, T)
ps = ps_model.predict_proba(X)[:, 1]
# Transform to logit scale
eps = 1e-7
ps_clipped = np.clip(ps, eps, 1 - eps)
logit_ps = np.log(ps_clipped / (1 - ps_clipped))
# 2. Set caliper threshold
caliper = caliper_scale * np.std(logit_ps)
treated_idx = np.where(T == 1)[0]
control_idx = np.where(T == 0)[0]
# 3. Perform 1:1 nearest neighbor matching with replacement
nn = NearestNeighbors(n_neighbors=1, metric="euclidean")
nn.fit(logit_ps[control_idx].reshape(-1, 1))
distances, matched_nn_idx = nn.kneighbors(logit_ps[treated_idx].reshape(-1, 1))
# Apply caliper constraint
valid_mask = distances.flatten() <= caliper
matched_treated = treated_idx[valid_mask]
matched_control = control_idx[matched_nn_idx.flatten()[valid_mask]]
# 4. Compute ATT estimate
att = np.mean(Y[matched_treated]) - np.mean(Y[matched_control])
retention_rate = np.mean(valid_mask)
return att, retention_rate