Algorithmcore
Inverse probability weighting
Also called IPW, inverse probability of treatment weighting, IPTW.
Weights each unit by one over the probability of the treatment it received, so the weighted sample mimics a randomized experiment.
- Time
- Θ(n) worst · best
- Space
- Θ(1) extra
- Where
- n = the number of units
- Model
- Real RAM
- Properties
- deterministichajek form shift equivariantnot ht form shift equivariantneeds positivitysingle passunbiased with known propensity
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Paul R. Rosenbaum, James M. Robins, 1987
Inverse probability weighting (IPW) estimates the average treatment effect from data in which the treatment was not assigned with equal chances. Each treated unit gets weight and each control gets weight , where is the propensity score. The weighted treated units then stand for the whole sample as if all had been treated, and the weighted controls stand for the whole sample as if none had been treated. Under ignorability, positivity and SUTVA, and with known propensities, the estimate is unbiased; this is the Horvitz-Thompson estimator applied once to each treatment arm. It takes one pass over the data.
In plain words
Suppose people with a mild illness got the new drug one time in four, and people with a severe illness three times in four. Then the treated group has too few mild cases. Each treated mild case had a one in four chance of being treated, so it stands in for four mild people. Each treated severe case stands in for four thirds of a severe person. After weighting, the treated group has the same mix of mild and severe cases as the full sample, and the same holds for the controls with weights one over the chance of no treatment. The difference of the weighted means compares like with like.
This only works if the treatment chance depends on things we measured, and if every kind of person had some chance of each treatment.
The problem
The two parts of the problem are kept apart: what the data can identify, and how to estimate it.
Identification. Each unit has potential outcomes and , a treatment and covariates measured before treatment. The units are independent draws from one distribution. The estimand is . The assumptions are:
- Consistency and SUTVA. The observed outcome is : one version of each treatment, and no effect of other units' treatments.
- Ignorability. : given , the treatment does not depend on the potential outcomes.
- Positivity. with probability 1.
Under these assumptions,
so is a function of the distribution of the observed . Positivity can be checked in part from data: estimated propensities near 0 or 1 show where it fails or nearly fails. Ignorability cannot be checked from the observed data, and SUTVA is a claim about the design. Both rest on knowledge of how the treatment was assigned.
Estimation. The input is triples with . The propensity is known in a designed experiment with unequal assignment chances, and must be estimated in an observational study, for example by logistic regression. The output is two estimates of :
The first is the Horvitz-Thompson form, and the second is the Hájek form, which divides each weighted sum by the sum of its weights instead of by .
The algorithm
IPW-ATE(T, Y, e) ▷ n units; needs 0 < e_i < 1- 1
a1 ← 0; a0 ← 0; w1 ← 0; w0 ← 0 - 2
for i ← 1 to n do - 3
if e_i ≤ 0 or e_i ≥ 1 then error "positivity fails" - 4
if T_i = 1 then a1 ← a1 + Y_i / e_i; w1 ← w1 + 1 / e_i - 5
else a0 ← a0 + Y_i / (1 - e_i); w0 ← w0 + 1 / (1 - e_i) - 6
τ_HT ← (a1 - a0) / n - 7
τ_H ← a1 / w1 - a0 / w0 ▷ needs w1 > 0 and w0 > 0 - 8
return (τ_HT, τ_H)
Line L3 stops on a propensity of 0 or 1, where the weight is infinite or the unit can only ever be in one arm. Lines L4 and L5 build the weighted sums of each arm. With known propensities, and both have expectation , but in a given sample they differ from ; line L6 divides by and line L7 divides by the sums.
Variance. Let , so that is the mean of the . With known propensities, the are independent and identically distributed, and
(divisor ) is an unbiased estimate of . The Hájek form is an M-estimator, and its sandwich estimate is (divisor ) with , where and . The interval is a normal confidence interval of approximate level . Both variance estimates treat as known; with an estimated propensity they are approximations (see the pitfalls).
Example
Eight patients have a stratum (0 for mild, 1 for severe), a treatment and an outcome. The design treated mild patients with probability and severe patients with probability .
| unit | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | |
| 1 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | |
| 8 | 7 | 6 | 5 | 7 | 4 | 3 | 1 | |
| 1/4 | 1/4 | 1/4 | 1/4 | 1/4 | 3/4 | 3/4 | 3/4 | |
| weight | 4 | 4 | 4/3 | 4/3 | 4/3 | 4/3 | 4/3 | 4 |
The naive difference of means is . It compares a treated group that is half severe with a control group that is one quarter severe.
Lines L4 and L5 give , , and . Line L6 gives . Line L7 gives . The two forms disagree because is not : in this sample the treated weights add up to more than the sample, and the Horvitz-Thompson treated mean is larger than every treated outcome.
With the empirical propensities instead, in the mild stratum (2 of 5 treated) and in the severe stratum (2 of 3), and both forms give . That is the stratified estimate: the mild stratum has mean difference , the severe stratum , and . The proofs show that this agreement is exact for every discrete .
The example has no known true effect; it shows the arithmetic. The tests check the general claims by exact enumeration.
Correctness
The proofs below establish, in exact arithmetic:
- the loops compute the two formulas;
- design-based unbiasedness: for fixed potential outcomes and any random assignment with known strictly between 0 and 1, equals the sample average treatment effect ; for independent assignment the variance has a closed form;
- identification and unbiasedness in the superpopulation: under consistency, ignorability and positivity, and , so , and is unbiased for its variance;
- the Hájek form is consistent, by the law of large numbers;
- under complete randomization both forms equal the difference in means;
- with a discrete and the empirical propensities, both forms equal the stratified estimate, and the ATT form equals the stratified ATT.
The coverage of the normal intervals, the bias of the Hájek form in finite samples, and the behaviour with estimated propensities from a model are not proved here; the numbers on this page about them are measured by simulation.
Proof: The IPW estimates are unbiased with known propensities and equal the stratified estimate with empirical onesfull
Unit has treatment , outcome and propensity with . Write . All arithmetic is exact.
Lemma 1 (the loops). IPW-ATE returns and , with , , and .
Proof. Line L1 sets the four sums to 0. The loop L2 visits each unit once. Line L3 does not change the sums. For a treated unit, line L4 adds to and to , which are the terms and ; the terms of and are 0 for this unit, and line L5 does not run. For a control the roles swap. So after the loop the four sums have the stated values. Line L6 returns , and line L7 returns .
Design-based results
Here the potential outcomes of units are fixed numbers, and only the assignment vector is random, with a known distribution (the design). Let , and assume for all . The observed outcome is (consistency). The sample average treatment effect is .
Theorem 2 (unbiased for any design). With , .
Proof. Since , consistency gives and . So , in which only is random. With , . By linearity of expectation and Lemma 1, . The proof uses only the marginal probabilities , so it holds for every joint distribution of the assignment.
Theorem 3 (variance under independent assignment). If the are independent, then
Proof. The are independent, so . Write , and . The variable is with probability and with probability , so and . Then
Theorem 4 (complete randomization). If every assignment with treats exactly units, with , and for all , then , the difference of the arm means, for every such assignment.
Proof. and , so the two forms coincide. And , and in the same way .
Under complete randomization of of units, , so Theorem 2 shows that the difference in means is unbiased for , the result proved on the randomized experiment page.
Superpopulation results
Here the units are independent copies of , with , and for . Assume consistency , ignorability , and positivity with probability 1.
Theorem 5 (identification). and . Hence .
Proof. By consistency . Ignorability gives , so . Since is a function of , by the tower property of conditional expectation, , so is integrable. The same steps without absolute values give
Positivity makes the division by valid with probability 1. The control arm is the same with , and . So for each , and by linearity.
Theorem 6 (unbiased variance estimate). If also , then , and , with the sample variance of with divisor (), satisfies .
Proof. The are independent and identically distributed, since each is the same function of one unit's data. The variance of their mean is , and the sample variance with divisor is unbiased for .
Theorem 7 (the Hájek form is consistent). with probability 1 as .
Proof. By Theorem 5 with replaced by the constant 1, . By the strong law of large numbers, and with probability 1, so . In the same way . For all large , and , so line L7 is defined.
Theorem 7 is a limit statement. It gives no bound on the bias of at a fixed , and the coverage of the normal intervals is not proved here.
Empirical propensities with a discrete covariate
Theorem 8 (equal to the stratified estimate). Let take finitely many values. For each value , let be the number of units with , the number of those treated, , and and the mean outcomes of the treated and the controls with . Assume for every that occurs. With for each unit with ,
The ATT form equals , where .
Proof. The assumption gives . Group the sums by the value of . The treated units with contribute to and to . So and . In the same way, gives and . Since , the two forms agree, and both equal .
For the ATT, a control with has weight . The controls with contribute to the weighted sum and to the sum of weights, so the control term is . The treated mean is . Their difference is the stated sum.
Cost. The loop L2 to L5 runs times and does a constant number of comparisons, divisions and additions per pass; lines L6 to L8 take constant time. So the time is in every case, and the extra space is the four sums, . The loop is over a finite range, so the procedure terminates.
Complexity
Each pass of the loop L2 to L5 does a comparison and two divisions and two additions, so the estimate takes time in both the best and the worst case, and extra space for the four sums. The estimate can run on a stream. The variance estimates take a second pass, because and use the estimate; a single pass with running sums of and also works for , at some cost in rounding error. Estimating the propensity, for example by logistic regression, is a separate cost and usually the larger one.
Properties
- Unbiased with known propensities. The Horvitz-Thompson form is unbiased for the ATE under ignorability and positivity, and for the sample ATE in a randomized design with known, unequal assignment chances. No model for the outcome is needed.
- The Hájek form stays in range. is a weighted average of the treated outcomes, so it lies between their minimum and maximum. The Horvitz-Thompson mean need not: in the example it is , above the largest treated outcome 8.
- Shift equivariance. Adding a constant to every outcome adds 0 to but adds to . In the example, adding 3 to every outcome raises by .
- Complete randomization. If for every unit, then , and both forms are the difference in means of the randomized experiment.
- Stratification. With a discrete and the treated share of stratum , both forms equal , the stratified estimate, as in the example. The tests check this exactly on 500 random tables.
- Large weights. The variance of contains , which grows without bound as approaches 0 or 1, even when positivity holds.
Variants and improvements
- Weighting for the effect on the treated. The ATT keeps the treated units with weight 1 and gives each control weight , which turns the control group into a copy of the treated group's covariate mix. The Hájek form is . It needs only , not .
- Stabilized weights. Multiplying the treated weights by and the control weights by keeps the weights near 1 on average. In a weighted regression of on this does not change the estimate, which is the Hájek form; it matters in models with more terms, such as marginal structural models.
- Trimming. Crump, Hotz, Imbens and Mitnik (2009) drop units whose estimated propensity is outside , with chosen from the data and often near 0.1. The estimand changes to the ATE of the units that remain, and the report must say so.
- Estimated propensities. Hirano, Imbens and Ridder (2003) show that weighting by a suitably flexible nonparametric estimate of gives an estimator with the smallest possible asymptotic variance among regular estimators of the ATE, smaller than weighting by the true .
- Doubly robust estimators. Augmented IPW adds an outcome regression and stays consistent if either the propensity model or the outcome model is right. TMLE and double machine learning build on the same estimating function.
- Other uses of the weight. The same weight appears in importance sampling, in off-policy evaluation of a new policy from logged actions, and in analysis of data missing at random (see missing-data mechanisms).
When to use it
Use IPW when the treatment chances are known from the design, or can be estimated well from measured covariates, and ignorability is credible. It gives one effect estimate for the whole population without a model for the outcome, and it extends to time-varying treatments where regression adjustment fails. Prefer the Hájek form in practice. Check overlap first: if many units have estimated propensities near 0 or 1, the weights are unstable, and propensity score matching for the ATT, trimming, or a doubly robust method is a better choice. When ignorability is in doubt, follow the estimate with a sensitivity analysis.
Pitfalls
- Weights near the positivity limit. In a simulation with uniform on , , effect (true ATE 1), and 2000 repetitions (seed 2026), gave a standard deviation of 0.278 for the Horvitz-Thompson form and 0.191 for the Hájek form, with interval coverage 0.953 and 0.946. With the standard deviations rose to 0.367 and 0.277, the Hájek mean was 1.046 instead of 1, and its 95% interval covered only 0.90 of the time. These numbers are measured, not proved.
- Estimated propensities treated as known. Plugging into or ignores the estimation step. For the ATE with a correctly specified parametric model fitted by maximum likelihood, Lunceford and Davidian (2004) show that this overstates the variance. In a simulation with 3 strata (), , empirical propensities and 2000 repetitions (seed 77), the nominal 95% Hájek interval covered 0.998 of the time. For the ATT the plug-in variance is not always conservative.
- A wrong propensity model. IPW is unbiased only with the right . A logistic model with missing terms leaves imbalance in . Check balance: compare the weighted means of each covariate in the two arms, as the propensity score page explains.
- Good prediction is not the goal. A covariate that predicts but not , such as an instrument, makes the weights more extreme and adds variance, and it can amplify the bias from an unmeasured confounder. Choose for confounding, not for the fit of the treatment model.
- Weighting cannot fix unmeasured confounding. If ignorability fails, the weighted arms still differ in the unmeasured variable, and the estimate is biased by an amount the data cannot reveal.
- The Horvitz-Thompson form out of range. The treated mean can lie above every treated outcome, as in the example, and for a binary outcome it can be above 1. Use the Hájek form, or report both.
- Mixing estimands. Weights and target the ATE, weights and target the ATT, and trimmed weights target a subpopulation. State which one the analysis reports.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inverse-probability-weighting/. The authors are listed in prov/GVS3R2.jsonl.
"""Inverse probability weighting estimates of the average treatment effect.
Unit i has a treatment t[i] in {0, 1}, an outcome y[i] and a propensity e[i],
the probability that unit i is treated given its covariates. The propensities
are inputs: known from the design, or estimated beforehand (for example by
empirical_propensity for a discrete covariate, or by a logistic regression).
With Fraction or int inputs every result except the interval is exact.
"""
import math
from collections.abc import Hashable, Sequence
from statistics import NormalDist
from typing import NamedTuple
class IPWEstimate(NamedTuple):
ht: object # the Horvitz-Thompson form (a1 - a0) / n
hajek: object # the normalized (Hajek) form a1 / w1 - a0 / w0
mu1_ht: object
mu0_ht: object
mu1_hajek: object
mu0_hajek: object
def _check(t: Sequence, y: Sequence, e: Sequence) -> None:
if not (len(t) == len(y) == len(e)):
raise ValueError("t, y and e must have the same length")
if len(t) == 0:
raise ValueError("no units")
for ti in t:
if ti not in (0, 1):
raise ValueError("every treatment must be 0 or 1")
def ipw_ate(t: Sequence[int], y: Sequence, e: Sequence) -> IPWEstimate:
"""Horvitz-Thompson and Hajek IPW estimates of the ATE. Cost: Theta(n) time, O(1) extra space.
Precondition: 0 < e[i] < 1 for every unit (positivity). The Hajek form also
needs at least one treated and one control unit; if an arm is empty its
Hajek mean is None.
"""
_check(t, y, e)
n = len(t)
a1 = a0 = w1 = w0 = 0 # @line L1
for ti, yi, ei in zip(t, y, e): # @line L2
if ei <= 0 or ei >= 1: # @line L3
raise ValueError(f"positivity fails: propensity {ei!r} is not strictly between 0 and 1")
if ti == 1: # @line L4
a1 = a1 + yi / ei
w1 = w1 + 1 / ei
else: # @line L5
a0 = a0 + yi / (1 - ei)
w0 = w0 + 1 / (1 - ei)
mu1_ht, mu0_ht = a1 / n, a0 / n
tau_ht = (a1 - a0) / n # @line L6
mu1_h = a1 / w1 if w1 else None
mu0_h = a0 / w0 if w0 else None
tau_h = mu1_h - mu0_h if w1 and w0 else None # @line L7
return IPWEstimate(tau_ht, tau_h, mu1_ht, mu0_ht, mu1_h, mu0_h) # @line L8
def ipw_variance(t: Sequence[int], y: Sequence, e: Sequence) -> tuple:
"""Variance estimates of the two IPW estimates, treating e as known. Cost: Theta(n).
Returns (v_ht, v_hajek). v_ht is S^2 / n, where S^2 is the sample variance
(divisor n - 1) of psi_i = t y / e - (1 - t) y / (1 - e); it is unbiased for
the variance of the HT estimate over iid units with known e. v_hajek is the
sandwich estimate (divisor n) of the M-estimator that defines the Hajek form.
With estimated propensities both are approximations (see the page).
"""
est = ipw_ate(t, y, e)
n = len(t)
if n < 2:
raise ValueError("need at least two units")
psi = [ti * yi / ei - (1 - ti) * yi / (1 - ei) for ti, yi, ei in zip(t, y, e)]
v_ht = sum((p - est.ht) ** 2 for p in psi) / ((n - 1) * n)
if est.hajek is None:
return v_ht, None
w1 = sum(ti / ei for ti, ei in zip(t, e))
w0 = sum((1 - ti) / (1 - ei) for ti, ei in zip(t, e))
phi = [ti * (yi - est.mu1_hajek) / ei * n / w1 - (1 - ti) * (yi - est.mu0_hajek) / (1 - ei) * n / w0
for ti, yi, ei in zip(t, y, e)]
v_h = sum(f * f for f in phi) / (n * n)
return v_ht, v_h
def ipw_interval(t: Sequence[int], y: Sequence, e: Sequence, alpha: float = 0.05, form: str = "hajek") -> tuple:
"""Normal (Wald) interval tau-hat -/+ z_(1 - alpha/2) sqrt(v). Asymptotic coverage only."""
est = ipw_ate(t, y, e)
v_ht, v_h = ipw_variance(t, y, e)
tau, v = (est.ht, v_ht) if form == "ht" else (est.hajek, v_h)
if tau is None:
raise ValueError("an arm is empty")
z = NormalDist().inv_cdf(1 - alpha / 2)
half = z * math.sqrt(float(v))
return float(tau) - half, float(tau) + half
def ipw_att(t: Sequence[int], y: Sequence, e: Sequence):
"""Hajek IPW estimate of the ATT: treated mean minus the control mean weighted by e / (1 - e).
Needs e[i] < 1 for the controls and at least one unit in each arm. Cost: Theta(n).
"""
_check(t, y, e)
s1 = n1 = s0 = w0 = 0
for ti, yi, ei in zip(t, y, e):
if ti == 1:
s1, n1 = s1 + yi, n1 + 1
else:
if ei <= 0 or ei >= 1:
raise ValueError(f"positivity fails: propensity {ei!r} is not strictly between 0 and 1")
w = ei / (1 - ei)
s0, w0 = s0 + w * yi, w0 + w
if n1 == 0 or w0 == 0:
raise ValueError("an arm is empty")
return s1 / n1 - s0 / w0
def empirical_propensity(x: Sequence[Hashable], t: Sequence[int]) -> list:
"""For a discrete covariate, e-hat(x) = (treated with value x) / (units with value x), as Fractions.
Cost: Theta(n) expected with hashing. Values can be 0 or 1 when a stratum has
only one arm; ipw_ate then reports the failure of positivity.
"""
from fractions import Fraction
tot: dict = {}
tr: dict = {}
for xi, ti in zip(x, t):
tot[xi] = tot.get(xi, 0) + 1
tr[xi] = tr.get(xi, 0) + ti
return [Fraction(tr[xi], tot[xi]) for xi in x]
test_inverse_probability_weighting.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inverse-probability-weighting/. The authors are listed in prov/GVS3R2.jsonl.
import itertools
import math
import random
from fractions import Fraction as Fr
import pytest
from inverse_probability_weighting import empirical_propensity, ipw_ate, ipw_att, ipw_interval, ipw_variance
# The worked example of the page: x is the stratum, e the known design propensity.
EX_X = [0, 0, 0, 0, 0, 1, 1, 1]
EX_T = [1, 1, 0, 0, 0, 1, 1, 0]
EX_Y = [8, 7, 6, 5, 7, 4, 3, 1]
EX_E = [Fr(1, 4)] * 5 + [Fr(3, 4)] * 3
def stratified(x, t, y, weight="all"):
"""Oracle: the subclassification estimate, sum over strata of (share) times (mean difference)."""
out, total = Fr(0), 0
for v in sorted(set(x)):
idx = [i for i in range(len(x)) if x[i] == v]
tr = [y[i] for i in idx if t[i] == 1]
co = [y[i] for i in idx if t[i] == 0]
size = len(idx) if weight == "all" else len(tr)
out += size * (Fr(sum(tr), len(tr)) - Fr(sum(co), len(co)))
total += size
return out / total
def test_worked_example():
est = ipw_ate(EX_T, EX_Y, EX_E)
assert est.mu1_ht == Fr(26, 3) and est.mu0_ht == Fr(7, 2)
assert est.ht == Fr(31, 6)
assert est.mu1_hajek == Fr(13, 2) and est.mu0_hajek == Fr(7, 2)
assert est.hajek == 3
eh = empirical_propensity(EX_X, EX_T)
assert eh == [Fr(2, 5)] * 5 + [Fr(2, 3)] * 3
emp = ipw_ate(EX_T, EX_Y, eh)
assert emp.ht == emp.hajek == Fr(15, 8) == stratified(EX_X, EX_T, EX_Y)
assert ipw_att(EX_T, EX_Y, eh) == 2 == stratified(EX_X, EX_T, EX_Y, "treated")
# the naive difference of means
assert Fr(8 + 7 + 4 + 3, 4) - Fr(6 + 5 + 7 + 1, 4) == Fr(3, 4)
def test_positivity_and_shape_errors():
with pytest.raises(ValueError):
ipw_ate([1, 0], [1, 2], [Fr(1, 2), 1])
with pytest.raises(ValueError):
ipw_ate([1, 0], [1, 2], [0, Fr(1, 2)])
with pytest.raises(ValueError):
ipw_ate([1, 2], [1, 2], [Fr(1, 2), Fr(1, 2)])
with pytest.raises(ValueError):
ipw_ate([], [], [])
with pytest.raises(ValueError):
ipw_att([0, 0], [1, 2], [Fr(1, 2), Fr(1, 2)])
one_arm = ipw_ate([1, 1], [3, 5], [Fr(1, 2), Fr(1, 4)])
assert one_arm.hajek is None and one_arm.ht == Fr(3 * 2 + 5 * 4, 2)
def bernoulli_design(pi):
"""Every assignment vector with its probability under independent Bernoulli(pi_i) assignment."""
for t in itertools.product((0, 1), repeat=len(pi)):
p = Fr(1)
for ti, q in zip(t, pi):
p *= q if ti else 1 - q
yield t, p
def test_ht_unbiased_and_variance_exact_bernoulli():
rng = random.Random(20261114)
for _ in range(60):
n = rng.randint(1, 7)
y0 = [rng.randint(-5, 9) for _ in range(n)]
y1 = [rng.randint(-5, 9) for _ in range(n)]
pi = [Fr(rng.randint(1, 9), 10) for _ in range(n)]
sate = Fr(sum(y1) - sum(y0), n)
mean = var2 = Fr(0)
for t, p in bernoulli_design(pi):
y = [y1[i] if t[i] else y0[i] for i in range(n)]
tau = ipw_ate(t, y, pi).ht
mean += p * tau
var2 += p * tau * tau
assert mean == sate
var = var2 - mean * mean
closed = sum(a * a * (1 - q) / q + b * b * q / (1 - q) + 2 * a * b for a, b, q in zip(y1, y0, pi)) / (n * n)
assert var == closed
def test_complete_randomization_forms_agree_and_unbiased():
rng = random.Random(7)
for _ in range(40):
n = rng.randint(2, 8)
n1 = rng.randint(1, n - 1)
y0 = [Fr(rng.randint(0, 20), 2) for _ in range(n)]
y1 = [Fr(rng.randint(0, 20), 2) for _ in range(n)]
e = [Fr(n1, n)] * n
total, count = Fr(0), 0
for treated in itertools.combinations(range(n), n1):
t = [1 if i in treated else 0 for i in range(n)]
y = [y1[i] if t[i] else y0[i] for i in range(n)]
est = ipw_ate(t, y, e)
dm = sum(y1[i] for i in treated) / n1 - sum(y0[i] for i in range(n) if i not in treated) / (n - n1)
assert est.ht == est.hajek == dm
total += est.ht
count += 1
assert total / count == (sum(y1) - sum(y0)) / n
def test_unequal_marginals_fixed_size_design_unbiased():
"""A design that is not Bernoulli: draw the treated set from a list of sets with given probabilities."""
rng = random.Random(99)
for _ in range(40):
n = rng.randint(3, 6)
sets = [s for k in range(1, n) for s in itertools.combinations(range(n), k)]
w = [rng.randint(1, 5) for _ in sets]
design = {s: Fr(wi, sum(w)) for s, wi in zip(sets, w)}
pi = [sum((p for s, p in design.items() if i in s), Fr(0)) for i in range(n)]
if any(q in (0, 1) for q in pi):
continue
y0 = [rng.randint(0, 9) for _ in range(n)]
y1 = [rng.randint(0, 9) for _ in range(n)]
mean = Fr(0)
for s, p in design.items():
t = [1 if i in s else 0 for i in range(n)]
y = [y1[i] if t[i] else y0[i] for i in range(n)]
mean += p * ipw_ate(t, y, pi).ht
assert mean == Fr(sum(y1) - sum(y0), n)
def test_discrete_x_empirical_propensity_equals_stratified():
rng = random.Random(31)
done = 0
while done < 500:
n = rng.randint(4, 30)
k = rng.randint(1, 4)
x = [rng.randrange(k) for _ in range(n)]
t = [rng.randint(0, 1) for _ in range(n)]
if any(len({t[i] for i in range(n) if x[i] == v}) < 2 for v in set(x)):
continue
y = [Fr(rng.randint(-40, 40), rng.randint(1, 4)) for _ in range(n)]
eh = empirical_propensity(x, t)
est = ipw_ate(t, y, eh)
s = stratified(x, t, y)
assert est.ht == s and est.hajek == s
assert ipw_att(t, y, eh) == stratified(x, t, y, "treated")
done += 1
def test_variance_ht_is_sample_variance_of_psi():
t, y, e = EX_T, EX_Y, EX_E
psi = [Fr(ti * yi) / ei - Fr((1 - ti) * yi) / (1 - ei) for ti, yi, ei in zip(t, y, e)]
m = sum(psi) / len(psi)
s2 = sum((p - m) ** 2 for p in psi) / (len(psi) - 1)
v_ht, v_h = ipw_variance(t, y, e)
assert v_ht == s2 / len(psi)
assert v_h > 0
def simulate(rng, n):
"""A superpopulation with a known propensity; the true ATE is 1."""
t, y, e = [], [], []
for _ in range(n):
x = rng.random()
ei = 0.2 + 0.6 * x
ti = 1 if rng.random() < ei else 0
y0 = 2 * x + rng.gauss(0, 1)
y1 = y0 + 0.5 + x # effect 0.5 + x, mean 1
t.append(ti)
y.append(y1 if ti else y0)
e.append(ei)
return t, y, e
def test_monte_carlo_bias_and_coverage():
rng = random.Random(123)
r, n = 600, 200
cover = {"ht": 0, "hajek": 0}
s_ht = s_h = 0.0
for _ in range(r):
t, y, e = simulate(rng, n)
est = ipw_ate(t, y, e)
s_ht += est.ht
s_h += est.hajek
for form in cover:
lo, hi = ipw_interval(t, y, e, 0.05, form)
cover[form] += lo <= 1.0 <= hi
# the HT form is unbiased; the Hajek form has bias of order 1/n
assert abs(s_ht / r - 1.0) < 0.06
assert abs(s_h / r - 1.0) < 0.06
tol = 4 * math.sqrt(0.05 * 0.95 / r) + 0.01
for form in cover:
assert abs(cover[form] / r - 0.95) < tol, (form, cover[form] / r)
def test_float_inputs_match_fractions():
rng = random.Random(5)
for _ in range(200):
n = rng.randint(2, 12)
t = [rng.randint(0, 1) for _ in range(n)]
y = [rng.randint(-9, 9) for _ in range(n)]
e = [Fr(rng.randint(1, 19), 20) for _ in range(n)]
a = ipw_ate(t, y, e)
b = ipw_ate(t, [float(v) for v in y], [float(v) for v in e])
assert math.isclose(float(a.ht), b.ht, rel_tol=1e-12, abs_tol=1e-12)
if a.hajek is not None:
assert math.isclose(float(a.hajek), b.hajek, rel_tol=1e-12, abs_tol=1e-12)
History
The weight comes from survey sampling, where Horvitz and Thompson (1952) proved that it makes the estimated total unbiased for any design. Rosenbaum (1987) used weighting by the inverse of an estimated propensity score, in his words model-based direct adjustment, to estimate causal effects from observational data. Robins, Rotnitzky and Zhao (1994) built a general theory of inverse probability weighted estimating equations for missing data, which also gave the augmented, doubly robust form. Hirano, Imbens and Ridder (2003) showed that weighting by an estimated propensity score can be efficient. Lunceford and Davidian (2004) compared weighting with stratification and gave sandwich variances, and Crump, Hotz, Imbens and Mitnik (2009) gave a rule for trimming units with poor overlap.
References
- D. G. Horvitz and D. J. Thompson, A generalization of sampling without replacement from a finite universe, Journal of the American Statistical Association 47(260), 1952, pp. 663 to 685 (the weight one over the inclusion probability and the unbiasedness of the weighted total)
- Paul R. Rosenbaum, Model-based direct adjustment, Journal of the American Statistical Association 82(398), 1987, pp. 387 to 394 (weighting by the inverse of the estimated propensity score)
- James M. Robins, Andrea Rotnitzky and Lue Ping Zhao, Estimation of regression coefficients when some regressors are not always observed, Journal of the American Statistical Association 89(427), 1994, pp. 846 to 866 (inverse probability weighted estimating equations and their augmented form)
- Keisuke Hirano, Guido W. Imbens and Geert Ridder, Efficient estimation of average treatment effects using the estimated propensity score, Econometrica 71(4), 2003, pp. 1161 to 1189 (weighting by a nonparametric estimate of the propensity score reaches the efficiency bound)
- Jared K. Lunceford and Marie Davidian, Stratification and weighting via the propensity score in estimation of causal treatment effects, a comparative study, Statistics in Medicine 23(19), 2004, pp. 2937 to 2960 (the weighted estimators, their sandwich variances, and the effect of estimating the propensity score)
- Richard K. Crump, V. Joseph Hotz, Guido W. Imbens and Oscar A. Mitnik, Dealing with limited overlap in estimation of average treatment effects, Biometrika 96(1), 2009, pp. 187 to 199 (trimming units with propensity scores near 0 or 1)
- Guido W. Imbens and Donald B. Rubin, Causal Inference for Statistics, Social, and Biomedical Sciences, Cambridge University Press, 2015, Chapter 12 (unconfounded treatment assignment) and Chapter 14 (assessing overlap)
- Miguel A. Hernán and James M. Robins, Causal Inference, What If, Chapman and Hall/CRC, 2020, Chapter 2 (randomized experiments and weighting) and Chapter 12 (IP weighting)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GVS3R2 Edit this page History Report an error Markdown