Propensity Scores: Matching & Weighting
In a randomized trial, chance decides who is treated, so the arms differ at baseline only by chance. In routine care a clinician decides, and sicker patients get the stronger drug. A propensity score is each patient’s probability of treatment given the baseline covariates. Weighting or matching on that score builds a comparison in which the measured covariates are balanced, as a trial would balance them, and it does nothing for a covariate that nobody recorded.
Get the data
Section titled “Get the data”Download ra_cohort.csv into your working directory. The invented table has 1,500 rows, one per patient with rheumatoid arthritis, and seven columns: patient_id, age, female, das28_baseline, hemoglobin_g_dl, biologic (1 for a patient who started a biologic drug, 0 for one who stayed on conventional therapy) and das28_month6. DAS28 is a disease activity score, and a lower value is better. The patient is the unit of analysis.
The values come from a simulation with known answers. Clinicians gave the biologic more often to younger patients, to women, to patients with a higher baseline DAS28 and to patients with a lower hemoglobin, and each of those four covariates also moves the DAS28 at month 6. The biologic lowers the month 6 score by exactly 1.0 point in every patient. The average effect in the whole cohort and the average effect in the treated patients are therefore both −1.0.
The naive comparison
Section titled “The naive comparison”Start with the comparison that ignores how treatment was chosen: the difference in mean month 6 DAS28 between the two groups.
library(MatchIt)library(WeightIt)library(cobalt)library(sandwich)library(ggplot2)
cohort <- read.csv("ra_cohort.csv")dir.create("outputs", showWarnings = FALSE)covariates <- c("age", "female", "das28_baseline", "hemoglobin_g_dl")ps_formula <- biologic ~ age + female + das28_baseline + hemoglobin_g_dlestimates <- list()
#' Print one effect estimate with its 95% limits.#'#' @param label Text to print before the numbers.#' @param values A numeric vector with the estimate, the lower limit and#' the upper limit.#' @return Invisibly, values.ReportEstimate <- function(label, values) { cat(sprintf("%s %.3f, 95%% CI [%.3f, %.3f]\n", label, values[1], values[2], values[3])) invisible(values)}
cat(sprintf("%d patients: %d on the biologic, %d on conventional therapy\n", nrow(cohort), sum(cohort$biologic == 1), sum(cohort$biologic == 0)))naive_fit <- lm(das28_month6 ~ biologic, data = cohort)estimates[["Naive difference"]] <- c(coef(naive_fit)[["biologic"]], confint(naive_fit)["biologic", ])ReportEstimate("Naive difference", estimates[["Naive difference"]])1500 patients: 634 on the biologic, 866 on conventional therapyNaive difference -0.478, 95% CI [-0.582, -0.374]from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport statsmodels.formula.api as smffrom statsmodels.treatment.treatment_effects import TreatmentEffect
cohort = pd.read_csv("ra_cohort.csv")output = Path("outputs")output.mkdir(exist_ok=True)covariates = ["age", "female", "das28_baseline", "hemoglobin_g_dl"]ps_formula = "biologic ~ age + female + das28_baseline + hemoglobin_g_dl"treated = (cohort["biologic"] == 1).to_numpy()estimates = {}
def report_estimate(label, values): """Print one effect estimate with its 95% limits.
Args: label: Text to print before the numbers. values: A sequence with the estimate, the lower limit and the upper limit.
Returns: The same values, as a list. """ values = list(values) print(f"{label} {values[0]:.3f}, 95% CI [{values[1]:.3f}, " f"{values[2]:.3f}]") return values
print(f"{len(cohort)} patients: {treated.sum()} on the biologic, " f"{(~treated).sum()} on conventional therapy")naive_fit = smf.ols("das28_month6 ~ biologic", data=cohort).fit()estimates["Naive difference"] = report_estimate( "Naive difference", [naive_fit.params["biologic"], *naive_fit.conf_int().loc["biologic"]])1500 patients: 634 on the biologic, 866 on conventional therapyNaive difference -0.478, 95% CI [-0.582, -0.374]The treated patients score 0.478 points lower at month 6, with a tight 95% interval from 0.374 to 0.582. The true effect is a reduction of 1.0, so the naive comparison finds less than half of it, and its interval excludes the truth. The biologic went to patients with more active disease, who would have scored higher at month 6 without it, so the naive comparison hides half of the benefit.
Balance before adjustment
Section titled “Balance before adjustment”The standardized mean difference measures how far apart the two groups sit on a covariate: the difference in means divided by a standard deviation. This page divides by the pooled standard deviation, the square root of the mean of the two group variances, and uses p(1 − p) as the variance of a 0/1 covariate. The measure does not depend on the sample size, which a p-value does, so it describes imbalance in a cohort of any size. Values below 0.1 are a common rule of thumb for good balance.
bal.tab() in cobalt computes the table. It reports a binary covariate as a raw difference in proportions unless binary = "std" asks for the standardized form. The Python tab writes the calculation as a function, with optional weights for the next steps.
before <- bal.tab(ps_formula, data = cohort, s.d.denom = "pooled", binary = "std", disp = "means")print(round(before$Balance[covariates, c("M.0.Un", "M.1.Un", "Diff.Un")], 3)) M.0.Un M.1.Un Diff.Unage 55.299 53.000 -0.195female 0.657 0.749 0.203das28_baseline 4.720 5.503 0.828hemoglobin_g_dl 13.480 12.720 -0.662def standardized_differences(data, names, weights=None): """Compute the standardized mean difference of each covariate.
The numerator uses the weights. The denominator is the pooled standard deviation of the unweighted groups, so it stays the same before and after weighting.
Args: data: A data frame with the 0/1 column biologic and the covariates. names: The names of the covariate columns. weights: Optional array of weights, one per row.
Returns: A data frame with the mean of each group and the standardized mean difference, one row per covariate. """ if weights is None: weights = np.ones(len(data)) is_treated = (data["biologic"] == 1).to_numpy() rows = [] for name in names: values = data[name].to_numpy() mean_1 = np.average(values[is_treated], weights=weights[is_treated]) mean_0 = np.average(values[~is_treated], weights=weights[~is_treated]) if data[name].isin([0, 1]).all(): raw_1 = values[is_treated].mean() raw_0 = values[~is_treated].mean() variance_1 = raw_1 * (1 - raw_1) variance_0 = raw_0 * (1 - raw_0) else: variance_1 = values[is_treated].var(ddof=1) variance_0 = values[~is_treated].var(ddof=1) pooled_sd = np.sqrt((variance_1 + variance_0) / 2) rows.append({"covariate": name, "mean_0": mean_0, "mean_1": mean_1, "smd": (mean_1 - mean_0) / pooled_sd}) return pd.DataFrame(rows).set_index("covariate")
before = standardized_differences(cohort, covariates)print(before.round(3)) mean_0 mean_1 smdcovariateage 55.299 53.000 -0.195female 0.657 0.749 0.203das28_baseline 4.720 5.503 0.828hemoglobin_g_dl 13.480 12.720 -0.662Every covariate is out of balance. The treated patients started with a baseline DAS28 of 5.50 against 4.72, a standardized difference of 0.828, and with a hemoglobin 0.76 g/dL lower, a difference of −0.662. They are also about two years younger and more often women. A comparison of outcomes between these two groups compares different kinds of patients.
Estimate the propensity score
Section titled “Estimate the propensity score”The propensity score comes from a logistic regression of treatment on the baseline covariates, the model of the logistic regression page with the treatment as its outcome. The fitted probability is the score. Plot its distribution in each group before any weighting, because the methods below can compare only patients whose scores occur in both groups.
ps_fit <- glm(ps_formula, family = binomial, data = cohort)cohort$ps <- fitted(ps_fit)cohort$group <- ifelse(cohort$biologic == 1, "Biologic", "Conventional")for (group in c("Conventional", "Biologic")) { scores <- cohort$ps[cohort$group == group] cat(sprintf("%-12s score %.3f to %.3f, median %.3f\n", group, min(scores), max(scores), median(scores)))}highest_control <- max(cohort$ps[cohort$biologic == 0])lowest_treated <- min(cohort$ps[cohort$biologic == 1])cat(sprintf("Outside the shared range: %d treated above, %d controls below\n", sum(cohort$ps > highest_control), sum(cohort$ps < lowest_treated)))ps_plot <- ggplot(cohort, aes(ps, fill = group)) + geom_histogram(position = "identity", alpha = 0.55, bins = 30, boundary = 0) + scale_fill_manual(values = c(Biologic = "#c44e52", Conventional = "#69b3a2"), name = NULL) + labs(x = "Propensity score", y = "Patients") + theme_classic(base_size = 12) + theme(legend.position = "top")ggsave("outputs/propensity-overlap-r.png", ps_plot, width = 6, height = 3.5, dpi = 150)Conventional score 0.024 to 0.911, median 0.303Biologic score 0.053 to 0.927, median 0.538Outside the shared range: 5 treated above, 22 controls below
ps_fit = smf.logit(ps_formula, data=cohort).fit(disp=0)cohort["ps"] = ps_fit.predict()for label, group in (("Conventional", ~treated), ("Biologic", treated)): scores = cohort.loc[group, "ps"] print(f"{label:<12} score {scores.min():.3f} to {scores.max():.3f}, " f"median {scores.median():.3f}")highest_control = cohort.loc[~treated, "ps"].max()lowest_treated = cohort.loc[treated, "ps"].min()print(f"Outside the shared range: " f"{(cohort['ps'] > highest_control).sum()} treated above, " f"{(cohort['ps'] < lowest_treated).sum()} controls below")figure, axes = plt.subplots(figsize=(6, 3.5))bins = np.linspace(0, 1, 31)axes.hist(cohort.loc[~treated, "ps"], bins=bins, alpha=0.55, color="#4c72b0", label="Conventional")axes.hist(cohort.loc[treated, "ps"], bins=bins, alpha=0.55, color="#c44e52", label="Biologic")axes.set_xlabel("Propensity score")axes.set_ylabel("Patients")axes.legend(frameon=False)figure.tight_layout()figure.savefig(output / "propensity-overlap-python.png", dpi=150)plt.close(figure)Conventional score 0.024 to 0.911, median 0.303Biologic score 0.053 to 0.927, median 0.538Outside the shared range: 5 treated above, 22 controls below
The two histograms sit apart, as the imbalance predicts, and they overlap over nearly the whole range. Read the tails, since they decide what can be estimated. Five treated patients score above every control, and 22 controls score below every treated patient. A region with treated patients and no controls holds no information about what those treated patients would have scored without the drug, and here that region is small.
Weight for the average treatment effect
Section titled “Weight for the average treatment effect”The average treatment effect compares the whole cohort treated with the whole cohort untreated. Inverse probability of treatment weighting gives each treated patient the weight 1 / score and each control 1 / (1 − score). A treated patient who had a low probability of treatment stands in for the many similar patients who were not treated, so that patient counts for more. weightit() fits the same logistic model and returns these weights, and the Python tab computes them from the fitted scores.
Weights cost precision. The effective sample size, the squared sum of the weights divided by the sum of their squares, says how many equally weighted patients would give the same precision. Print it with the range of the weights, then check balance again with the weights applied.
w_out <- weightit(ps_formula, data = cohort, method = "glm", estimand = "ATE")weight_summary <- summary(w_out)for (group in c("Control", "Treated")) { cat(sprintf("%s weights %.2f to %.2f, effective sample size %.1f of %d\n", group, weight_summary$weight.range[[group]][1], weight_summary$weight.range[[group]][2], weight_summary$effective.sample.size["Weighted", group], weight_summary$effective.sample.size["Unweighted", group]))}after <- bal.tab(w_out, binary = "std", un = TRUE)print(round(after$Balance[covariates, c("Diff.Un", "Diff.Adj")], 3))love <- love.plot(w_out, binary = "std", abs = TRUE, drop.distance = TRUE, var.order = "unadjusted", thresholds = c(m = 0.1))ggsave("outputs/love-plot-r.png", love, width = 6, height = 3.5, dpi = 150)Control weights 1.02 to 11.29, effective sample size 660.1 of 866Treated weights 1.08 to 18.81, effective sample size 435.5 of 634 Diff.Un Diff.Adjage -0.195 -0.027female 0.203 -0.001das28_baseline 0.828 0.004hemoglobin_g_dl -0.662 -0.023
weights = np.where(treated, 1 / cohort["ps"], 1 / (1 - cohort["ps"]))for label, group in (("Control", ~treated), ("Treated", treated)): group_weights = weights[group] effective = group_weights.sum() ** 2 / (group_weights**2).sum() print(f"{label} weights {group_weights.min():.2f} to " f"{group_weights.max():.2f}, effective sample size " f"{effective:.1f} of {group.sum()}")after = standardized_differences(cohort, covariates, weights=weights)balance = pd.DataFrame({"before": before["smd"], "after": after["smd"]})print(balance.round(3))order = balance["before"].abs().sort_values().indexfigure, axes = plt.subplots(figsize=(6, 3.5))axes.scatter(balance.loc[order, "before"].abs(), order, color="#c44e52", label="Before weighting")axes.scatter(balance.loc[order, "after"].abs(), order, color="#4c72b0", marker="s", label="After weighting")axes.axvline(0.1, color="0.4", linestyle="--")axes.set_xlabel("Absolute standardized mean difference")axes.legend(frameon=False)figure.tight_layout()figure.savefig(output / "love-plot-python.png", dpi=150)plt.close(figure)Control weights 1.02 to 11.29, effective sample size 660.1 of 866Treated weights 1.08 to 18.81, effective sample size 435.5 of 634 before aftercovariateage -0.195 -0.027female 0.203 -0.001das28_baseline 0.828 0.004hemoglobin_g_dl -0.662 -0.023
After weighting, every standardized difference is below 0.03 in absolute value. The plot of these differences before and after adjustment is called a love plot. Balance on the means is what the weights were built to deliver, so this table checks the propensity model: if a covariate stayed out of balance, the model would need an interaction or a curved term, and you would fit it again before looking at any outcome.
The largest weight belongs to a treated patient whose score was near 0.05, and that one patient counts for almost 19. The 634 treated patients carry the information of about 436 equally weighted ones. Report both numbers. A handful of weights of 50 or 100 can decide an estimate, and the reader cannot know unless the range is in the report.
Estimate the weighted effect
Section titled “Estimate the weighted effect”The weighted difference in means is the coefficient of a weighted regression of the outcome on treatment. Its standard error needs care, because the model-based standard error of a weighted fit treats the weights as known precisions and is wrong here. The WeightIt documentation recommends lm_weightit(), whose default variance uses M-estimation to account for the fact that the weights were themselves estimated. Its vcov = "HC0" option gives the robust sandwich variance that treats the weights as fixed.
In Python, weighted least squares with cov_type="HC0" is that same fixed-weight sandwich. TreatmentEffect in statsmodels takes the fitted logistic model and returns the inverse probability weighted effect with a standard error from the joint estimating equations of both models.
weighted_fit <- lm_weightit(das28_month6 ~ biologic, data = cohort, weightit = w_out)fixed_fit <- lm_weightit(das28_month6 ~ biologic, data = cohort, weightit = w_out, vcov = "HC0")estimates[["Weighting"]] <- c(coef(weighted_fit)[["biologic"]], confint(weighted_fit)["biologic", ])cat(sprintf("Standard error %.4f with estimated weights, %.4f with fixed\n", sqrt(vcov(weighted_fit)["biologic", "biologic"]), sqrt(vcov(fixed_fit)["biologic", "biologic"])))ReportEstimate("Weights estimated:", estimates[["Weighting"]])ReportEstimate("Weights fixed: ", c(coef(fixed_fit)[["biologic"]], confint(fixed_fit)["biologic", ]))Standard error 0.0536 with estimated weights, 0.0696 with fixedWeights estimated: -0.982, 95% CI [-1.087, -0.877]Weights fixed: -0.982, 95% CI [-1.118, -0.846]fixed_fit = smf.wls("das28_month6 ~ biologic", data=cohort, weights=weights).fit(cov_type="HC0")outcome_model = smf.ols("das28_month6 ~ 1", data=cohort)weighted_fit = TreatmentEffect(outcome_model, cohort["biologic"], results_select=ps_fit).ipw()print(f"Standard error {weighted_fit.sd[0]:.4f} with estimated weights, " f"{fixed_fit.bse['biologic']:.4f} with fixed")estimates["Weighting"] = report_estimate( "Weights estimated:", [weighted_fit.effect[0], *weighted_fit.conf_int()[0]])report_estimate("Weights fixed: ", [fixed_fit.params["biologic"], *fixed_fit.conf_int().loc["biologic"]])Standard error 0.0536 with estimated weights, 0.0696 with fixedWeights estimated: -0.982, 95% CI [-1.087, -0.877]Weights fixed: -0.982, 95% CI [-1.118, -0.846]The weighted estimate is −0.982, against a truth of −1.0 and a naive estimate of −0.478. The two languages agree on the estimate and on both standard errors to four decimals.
The two standard errors differ from each other, 0.0536 against 0.0696. Estimating the weights from the data makes the estimate of the average treatment effect more precise than known weights would, since the fitted scores also balance chance differences in the covariates, so the fixed-weight standard error is too large here. Its interval is valid and wider than it needs to be. The WeightIt documentation notes that this direction holds for the average treatment effect and can reverse for other estimands, so use the estimator that accounts for the weights when your software has one.
Match for the effect in the treated
Section titled “Match for the effect in the treated”Matching answers a narrower question, the average effect in the patients who were treated. Each treated patient is paired with the control whose score is nearest, and the unpaired controls are set aside. matchit() with method = "nearest" takes the treated patients in descending order of score and gives each one the closest unused control. link = "linear.logit" measures closeness on the logit of the score, and caliper forbids a pair that is further apart than that many standard deviations of the logit. A treated patient with no control inside the caliper stays unmatched.
This step is in R only, because statsmodels 0.15 has no matching estimator.
The code tries two caliper widths and judges them on balance alone. No outcome is involved in the choice.
for (width in c(0.2, 0.1)) { m_out <- matchit(ps_formula, data = cohort, method = "nearest", distance = "glm", link = "linear.logit", caliper = width) m_balance <- bal.tab(m_out, binary = "std", s.d.denom = "pooled", un = TRUE)$Balance counts <- summary(m_out)$nn cat(sprintf("Caliper %.1f: %d treated matched, %d unmatched, ", width, counts["Matched", "Treated"], counts["Unmatched", "Treated"])) adjusted <- abs(m_balance[covariates, "Diff.Adj"]) cat(sprintf("largest |SMD| %.3f (%s)\n", max(adjusted), covariates[which.max(adjusted)]))}print(round(m_balance[covariates, c("Diff.Un", "Diff.Adj")], 3))is_treated <- cohort$biologic == 1is_matched <- m_out$weights > 0cat(sprintf("Mean score of treated patients: matched %.3f, unmatched %.3f\n", mean(cohort$ps[is_treated & is_matched]), mean(cohort$ps[is_treated & !is_matched])))Caliper 0.2: 511 treated matched, 123 unmatched, largest |SMD| 0.107 (das28_baseline)Caliper 0.1: 481 treated matched, 153 unmatched, largest |SMD| 0.055 (das28_baseline) Diff.Un Diff.Adjage -0.195 0.004female 0.203 0.023das28_baseline 0.828 0.055hemoglobin_g_dl -0.662 -0.028Mean score of treated patients: matched 0.471, unmatched 0.742With a caliper of 0.2 standard deviations, baseline DAS28 keeps a standardized difference above 0.1. Each treated patient may take a control up to 0.2 standard deviations away. Treated patients outnumber controls at high scores, so the nearest free control usually has the lower score, and the small gaps add up to a residual imbalance. A caliper of 0.1 brings every covariate under 0.06 and costs 30 more treated patients. The rest of this section uses the 0.1 match, which the loop leaves in m_out.
That match keeps 481 of the 634 treated patients. The 153 who found no control are not a random subset: their mean score is 0.742, against 0.471 for the matched patients. The cohort has too few controls who resemble them. The MatchIt documentation states the consequence: once a caliper drops treated patients, the estimate describes the treated patients in the matched sample and no longer all treated patients.
For the standard error, the MatchIt documentation recommends a cluster-robust variance with pair membership as the cluster. match_data() returns the matched rows with a subclass column that identifies each pair, and vcovCL() in sandwich computes the variance.
matched <- match_data(m_out)match_fit <- lm(das28_month6 ~ biologic, data = matched, weights = weights)match_estimate <- coef(match_fit)[["biologic"]]match_vcov <- vcovCL(match_fit, cluster = ~subclass)match_se <- sqrt(match_vcov["biologic", "biologic"])estimates[["Matching"]] <- c(match_estimate, match_estimate - qnorm(0.975) * match_se, match_estimate + qnorm(0.975) * match_se)cat(sprintf("%d pairs, cluster-robust standard error %.4f\n", length(unique(matched$subclass)), match_se))ReportEstimate("Matched difference", estimates[["Matching"]])481 pairs, cluster-robust standard error 0.0587Matched difference -0.969, 95% CI [-1.084, -0.854]The matched estimate is −0.969, with an interval that contains −1.0. In this simulation the effect is the same in every patient, so the effect in the matched patients equals the effect in everyone. In a real cohort the patients with the highest scores, here the ones with the most active disease, may respond differently, and the matched estimate would say nothing about them.
Every estimate beside the truth
Section titled “Every estimate beside the truth”One more estimate completes the table: a multiple regression of the outcome on treatment and the four covariates, with no propensity score at all.
adjusted_fit <- lm(das28_month6 ~ biologic + age + female + das28_baseline + hemoglobin_g_dl, data = cohort)estimates[["Regression adjustment"]] <- c( coef(adjusted_fit)[["biologic"]], confint(adjusted_fit)["biologic", ])methods <- c("Naive difference", "Regression adjustment", "Weighting", "Matching")comparison <- as.data.frame(do.call(rbind, estimates[methods]))names(comparison) <- c("estimate", "lower", "upper")comparison["Truth", ] <- c(-1, NA, NA)print(round(comparison, 3)) estimate lower upperNaive difference -0.478 -0.582 -0.374Regression adjustment -0.976 -1.069 -0.884Weighting -0.982 -1.087 -0.877Matching -0.969 -1.084 -0.854Truth -1.000 NA NAadjusted_fit = smf.ols( "das28_month6 ~ biologic + age + female + das28_baseline" " + hemoglobin_g_dl", data=cohort).fit()estimates["Regression adjustment"] = [ adjusted_fit.params["biologic"], *adjusted_fit.conf_int().loc["biologic"]]methods = ["Naive difference", "Regression adjustment", "Weighting"]comparison = pd.DataFrame([estimates[method] for method in methods], index=methods, columns=["estimate", "lower", "upper"])comparison.loc["Truth"] = [-1, np.nan, np.nan]print(comparison.round(3)) estimate lower upperNaive difference -0.478 -0.582 -0.374Regression adjustment -0.976 -1.069 -0.884Weighting -0.982 -1.087 -0.877Truth -1.000 NaN NaNThe naive difference is the only estimate whose interval misses −1.0. Regression adjustment, weighting and matching all land within 0.04 of the truth.
Regression adjustment has the narrowest interval, and this simulation flatters it: the outcome was generated as a straight-line function of the four covariates, which is the model that lm() fits. If the outcome curved with a covariate, or the effect varied with one, that regression could be biased until you found the right terms. The propensity methods never model the outcome. They need the treatment model to balance the covariates, and you can check that on the balance table before any outcome is analyzed. Matching has the widest interval of the three because it uses 962 of the 1,500 patients.
The estimands differ too. Weighting targets the whole cohort, matching targets the matched treated patients, and the regression coefficient assumes one effect for every patient. The three agree here because the simulated effect is constant. In a randomized trial none of this is needed for bias, and ANCOVA adjusts for a baseline covariate to gain precision.
What balance cannot fix
Section titled “What balance cannot fix”Every method above balances the covariates that went into the propensity model. Suppose the baseline DAS28 had never been recorded. The analysis below repeats the weighting with the three remaining covariates, checks their balance, and estimates the effect.
w_partial <- weightit(biologic ~ age + female + hemoglobin_g_dl, data = cohort, method = "glm", estimand = "ATE")partial_balance <- bal.tab(w_partial, data = cohort, binary = "std", un = TRUE, addl = ~das28_baseline)print(round(partial_balance$Balance[covariates, c("Diff.Un", "Diff.Adj")], 3))partial_fit <- lm_weightit(das28_month6 ~ biologic, data = cohort, weightit = w_partial)ReportEstimate("Weighted estimate without baseline DAS28", c(coef(partial_fit)[["biologic"]], confint(partial_fit)["biologic", ])) Diff.Un Diff.Adjage -0.195 -0.021female 0.203 -0.001das28_baseline 0.828 0.694hemoglobin_g_dl -0.662 -0.003Weighted estimate without baseline DAS28 -0.638, 95% CI [-0.742, -0.535]partial_fit = smf.logit("biologic ~ age + female + hemoglobin_g_dl", data=cohort).fit(disp=0)partial_score = partial_fit.predict()partial_weights = np.where(treated, 1 / partial_score, 1 / (1 - partial_score))partial_after = standardized_differences(cohort, covariates, weights=partial_weights)print(pd.DataFrame({"before": before["smd"], "after": partial_after["smd"]}).round(3))partial_effect = TreatmentEffect(outcome_model, cohort["biologic"], results_select=partial_fit).ipw()report_estimate("Weighted estimate without baseline DAS28", [partial_effect.effect[0], *partial_effect.conf_int()[0]]) before aftercovariateage -0.195 -0.021female 0.203 -0.001das28_baseline 0.828 0.694hemoglobin_g_dl -0.662 -0.003Weighted estimate without baseline DAS28 -0.638, 95% CI [-0.742, -0.535]Age, sex and hemoglobin are balanced to within 0.03 after weighting. An analyst who had only those three covariates would see a clean balance table and a tight interval, and the estimate would be −0.638 with an upper limit of −0.535, well short of −1.0. The das28_baseline row shows why. Baseline DAS28 still differs by 0.694 standard deviations between the weighted groups, and nothing in the analysis could reveal that, because the column would not exist.
The weighted estimate did move from the naive −0.478 toward the truth. Weighting removed the confounding by hemoglobin, age and sex. Hemoglobin is also correlated with baseline DAS28, so balancing it removed part of the hidden imbalance. A measured proxy helps and does not finish the job.
Mistakes to avoid
Section titled “Mistakes to avoid”Do not choose the propensity model by the outcome result. Fitting several models or calipers, estimating the effect under each, and keeping the one you prefer turns the analysis into a search for a result. The caliper above was chosen between 0.2 and 0.1 on the balance table, before any matched outcome was computed. Settle the model on balance and overlap, then estimate the effect once.
Do not include a variable measured after treatment started. A DAS28 at month 3, or a steroid dose that changed after the biologic was started, is partly a result of the treatment. Balancing it removes some of the effect you want to estimate. Only covariates that were fixed before the treatment decision belong in the model.
Do not judge the propensity model by its AUC. The model exists to balance covariates, and the balance table tests that directly. An AUC near 1 means the two groups barely overlap, which is bad news for the comparison, and a variable that predicts treatment without affecting the outcome raises the AUC while it only inflates the weights.
Do not leave extreme weights unreported. Give the range of the weights and the effective sample size, here a largest weight near 19 and 436 effective treated patients out of 634.
Do not read a matched estimate as the effect in the whole population. This match describes 481 of the 634 treated patients, the ones for whom a comparable control existed. It is not the effect in all treated patients, and it is not the average effect in the cohort.
Scientific references
Section titled “Scientific references”Rosenbaum and Rubin, 1983 define the propensity score and show that adjustment for it removes the bias from the observed covariates.
Ho and colleagues, 2011 describe the MatchIt package and matching as preprocessing before a parametric analysis.
The WeightIt package by Greifer estimates balancing weights and fits weighted outcome models whose variance accounts for the estimation of the weights.
The cobalt package by Greifer computes covariate balance tables and love plots for weighted and matched samples.
Zeileis, Köll, and Graham, 2020 describe the clustered covariance estimators of the sandwich package.
Further reading
Section titled “Further reading”The MatchIt guide to estimating effects explains which standard error fits each matching method, including matching with replacement and full matching, which this page does not cover.
The WeightIt guide to estimating effects covers the average effect in the treated, binary and survival outcomes, and covariate adjustment in the weighted outcome model.
The cobalt love plot guide shows how to label, order and combine love plots for several adjustment methods.
The statsmodels treatment effects documentation describes TreatmentEffect, including the doubly robust estimators that combine weighting with an outcome regression.
The risk measures page handles one categorical confounder by stratification with the Mantel-Haenszel method.