November 18, 2026

Inverse Probability of Treatment Weighting (IPTW): The Practitioner's Playbook

Part I

IPTW fundamentals

01What is IPTW?

Inverse probability of treatment weighting (IPTW) is a causal inference method that restores balance between the treatment and control groups [covariate balance] by equalizing the weighted number of subjects within each subgroup of covariates.

02How IPTW restores stochastic balance in the observational data

Let's start with an example. Say we have observational data with 30 people. We have measurements for one covariate — smoking status — and whether they were in the treatment or control group.

We summarize the data, and observe the following:

Raw observed data30 real people, exactly as they showed up in the data

Smoking statusTreatment, n (%)Control, n (%)Total
Smoker1 (16.7%)9 (37.5%)10
Non-smoker5 (83.3%)15 (62.5%)20
Total6 (100%)24 (100%)30

Three things are off here:

  1. Each covariate profile is not evenly split between treatment and control — 1 treated / 9 control for smokers, and 5 treated / 15 control for non-smokers.
  2. The total number of subjects in the treatment and control groups is not the same — 6 subjects in treatment, 24 in control.
  3. The distribution of smoking status is not the same (balanced) between the groups — 16.7% smokers / 83.3% non-smokers in the treatment group, versus 37.5% smokers / 62.5% non-smokers in the control group.

Normally, in a 1:1 randomized controlled trial — where every subject has a 50/50 chance of landing in either group — we would expect those 10 smokers to split into 5 treated and 5 control, and those 20 non-smokers to split into 10 treated and 10 control.

The balanced table, if we could run a 1:1 randomized controlled trial, would look something like this:

Data if we could run a 1:1 randomized controlled trialThe world we're trying to recreate

Smoking statusTreatment, n (%)Control, n (%)Total
Smoker5 (33.3%)5 (33.3%)10
Non-smoker10 (66.7%)10 (66.7%)20
Total15 (100%)15 (100%)30

Notice how:

  1. Each covariate profile is evenly split — 5 / 5 for smokers, 10 / 10 for non-smokers.
  2. The group totals are the same — 15 subjects in treatment, 15 in control.
  3. The distribution of smoking status is the same in both groups — 33.3% smokers / 66.7% non-smokers in each.

Through IPTW, we essentially want to recreate what we would see in a 1:1 randomized controlled trial. I'll go over the mathematical mechanics shortly, but essentially we mathematically weight the subjects in the treatment and control groups so that our [pseudo-population] — meaning our effective population after applying the weights — looks like this:

Data when we use IPTW on the raw observational dataWeighted counts — nobody new was enrolled, everybody just counts for more

Smoking statusTreatment, weighted n (%)Control, weighted n (%)Total
Smoker10 (33.3%)10 (33.3%)20
Non-smoker20 (66.7%)20 (66.7%)40
Total30 (100%)30 (100%)60

Notice how:

  1. Each covariate profile is evenly split — 10 / 10 for smokers, 20 / 20 for non-smokers.
  2. The group totals are the same — 30 weighted subjects in treatment, 30 in control.
  3. The distribution of smoking status is the same in both groups — 33.3% / 66.7% in each.
  4. Both the treatment and control groups are each weighted up to the full population of subjects in the raw observational data.
Why "pseudo"?

We call it a pseudo-population because the total effective population is 60, when in fact we only had 30 real subjects in our observational data. But our pseudo-population now looks like what we would see in a 1:1 randomized controlled trial — and that resemblance is the whole point.

04Why use IPTW over other causal inference methods?

Here are a few reasons why you would choose IPTW over other causal inference methods, such as matching:

You don't want to discard data from your observational study

Notice how, when we constructed our pseudo-population, we didn't throw out a single data point — we simply weighted subjects differently to restore balance between the treatment and control groups. By contrast, matching forces you to discard unmatched subjects (such as excess control subjects left over after pairing, or treated subjects with no close match in the control group).

You want the effect for the whole population, not just the treated

You want to calculate the [average treatment effect] — the effect of the treatment across the entire population — rather than just the [average treatment effect on the treated], which is what standard matching targets.

In the real world, we only observe one outcome per person: we see what happened to the treatment group with the drug, and what happened to the control group without it. IPTW estimates the missing potential outcomes [potential outcomes] by scaling each group up to represent the entire population:

The average treatment effect is simply the difference between those two weighted averages: the expected outcome if all subjects in the population received treatment minus the expected outcome if all subjects did not receive treatment.

ATE = E[Y1] − E[Y0] Y1 is the outcome a person would have if treated; Y0 is the outcome they would have if not treated. We never see both for the same person — IPTW reconstructs both averages at the population level.

You are running a time-varying analysis

You are running a time-varying analysis, where treatment at time 0 changes a patient's covariates at time 1, which in turn affects whether they receive treatment at time 1 [treatment–confounder feedback]. Matching and ordinary regression adjustment break down here; IPTW doesn't. We work a full example of this in section 13.

05Intuition on how IPTW allows us to calculate potential outcomes

In an observational study, we face the fundamental problem of causal inference [fundamental problem of causal inference]: for any single patient, we only observe one potential outcome. If they took the drug, we observe Y1, and their untreated outcome Y0 is missing. If they didn't take the drug, we observe Y0, and their treated outcome Y1 is missing.

IPTW doesn't guess the missing outcome for each individual person one by one. Instead, it fills in the missing outcomes at the covariate-group (and population) level using the weights:

  1. Estimating what would have happened if everyone received treatment (E[Y1]): Suppose in a specific covariate profile of 10 patients, only 2 received the drug and 8 were in the control group. For those 8 control patients, we are missing what would have happened if they had taken the drug. By giving each of the 2 treated patients a weight of 1/0.2 = 5, those 2 treated patients now count as 2 × 5 = 10 patients in our pseudo-population. Their observed outcomes stand in for both themselves and the 8 control patients with the exact same covariate profile whose treated outcomes were missing. Taking the weighted average of the treatment group — which is simply the standard average calculated directly on the treated pseudo-population (e.g., total weighted heart attacks divided by total weighted patients) — gives us the expected outcome if the entire population had been treated.
  2. Estimating what would have happened if no one received treatment (E[Y0]): In that same 10-patient profile, 8 patients did not receive the drug, while the 2 treated patients are missing their untreated outcomes. By giving each of the 8 control patients a weight of 1/(1 − 0.2) = 1.25, those 8 control patients now count as 8 × 1.25 = 10 patients in our pseudo-population — standing in for both themselves and the 2 treated patients. Taking the weighted average of the control group — that is, the standard average calculated directly on the control pseudo-population — gives us the expected outcome if the entire population had gone untreated.
  3. Calculating the ATE: Once both groups are weighted up to represent the full population, you simply take the weighted average outcome of the treatment group minus the weighted average outcome of the control group — in other words, the standard average outcome in the treated pseudo-population minus the standard average outcome in the control pseudo-population.
The one idea to keep

Each treated person counts for themselves plus the similar people who didn't get treated. Each control person counts for themselves plus the similar people who did. That's the entire trick — everything else is machinery for doing it carefully.

06How to calculate the weights for IPTW

Now let's actually run through the mathematics for how we calculated this weighted population:

Mechanics of calculating the weights and the pseudo-populationπ is the propensity score — the probability of treatment within that covariate profile

Smoking statusTreated, nControl, nπ = P(treatment) Treatment weight (1/π)Treated, weighted n Control weight (1/(1−π))Control, weighted n
Smoker191/10 = 0.10101 × 10 = 1010/9 ≈ 1.119 × 10/9 = 10
Non-smoker5155/20 = 0.2545 × 4 = 2020/15 ≈ 1.3315 × 20/15 = 20
Total624——30—30
  1. First, for each covariate profile L, we calculate the [propensity score] — the probability that a subject with that covariate profile receives treatment: π(L) = P(A = 1 | L). For example, look at the covariate profile of smokers: one in ten smokers is treated, so the propensity score for subjects with that profile is 0.10.
  2. For the treated population, the weight for each subject is 1/π.
  3. For the control population, the weight for each subject is 1/(1 − π).
  4. Finally, we multiply each subject by their appropriate weight and sum the new weighted counts across the treatment and control groups.

This is how we ended with 30 weighted control subjects and 30 weighted treatment subjects, for a total balanced pseudo-population of 60.

Weight = Aπ(L) + 1 − A1 − π(L) One formula, both groups: if you were treated (A = 1) the second term vanishes and your weight is 1/π; if you were control (A = 0) the first term vanishes and your weight is 1/(1 − π). In words: one divided by the probability of the treatment you actually received.

Try it: the weight explorer

Drag the propensity score π and watch the two weights move. Notice what happens near the edges — that's the extreme-weights problem from section 9, arriving early.

If treated · weight = 1/π
5.00

Each treated person counts as 5 people in the pseudo-population.

If control · weight = 1/(1−π)
1.25

Each control person counts as 1.25 people in the pseudo-population.

At π = 0.20 this is our 10-patient profile from section 5: 2 treated × 5 = 10, and 8 controls × 1.25 = 10. Balanced.

In the real world

07How to check for balance

One way to check for balance in the pseudo-population is to create a Table 1 (which is covered in other blog posts). But essentially, we look at the [standardized mean difference] between the treatment and the control group for each of the covariates, before and after the weighting.

Recall that the standardized mean difference is essentially the difference in means between the treatment and the control group, divided by their pooled standard deviation — and we take the absolute value, because we care about the size of the imbalance, not its direction:

|SMD| = | meantreated − meancontrol |pooled SD   where   pooled SD = √ (st² + sc²) / 2  For a yes/no covariate (like smoker), use proportions instead of means: pooled SD = √[ (pt(1 − pt) + pc(1 − pc)) / 2 ]. Rule of thumb: |SMD| below 0.1 counts as balanced.

So it would look something like the table below. This is an illustrative example — a larger study than our 30-person toy, with 180 treated and 320 control patients:

Balance before and after weighting — illustrative exampleTreated n = 180 · Control n = 320. Continuous covariates shown as mean (SD); yes/no covariates as %.

CovariateTreatedControl|SMD| beforeTreated, weightedControl, weighted|SMD| after
Age, years62.4 (11.2)57.1 (10.6)0.48659.359.00.028
Systolic blood pressure, mm Hg138 (18)130 (17)0.457133.2132.80.023
Smoker24%45%0.45333.8%33.3%0.011
Diabetes38%22%0.35528.4%27.9%0.011
Body mass index29.8 (5.4)28.3 (5.1)0.28628.928.80.019
Male58%52%0.12154.5%54.0%0.010

Notice how the standardized mean difference decreased significantly after weighting the data — every covariate drops from well above the 0.1 line to well below it. We can also visualize this table in an SMD plot [Love plot]:

Standardized mean differences before and after weighting

Covariates sorted by their unweighted |SMD|, largest first. The dashed line marks the 0.1 rule of thumb. Use the toggle to isolate a view.

0.1 threshold 0 0.2 0.3 0.4 0.5 Age Systolic BP Smoker Diabetes BMI Male Age after weighting: 0.028 Systolic BP after weighting: 0.023 Smoker after weighting: 0.011 Diabetes after weighting: 0.011 BMI after weighting: 0.019 Male after weighting: 0.010 0.0280.0230.011 0.0110.0190.010 Age before weighting: 0.486 Systolic BP before weighting: 0.457 Smoker before weighting: 0.453 Diabetes before weighting: 0.355 BMI before weighting: 0.286 Male before weighting: 0.121 0.4860.4570.453 0.3550.2860.121 Before weighting After weighting Absolute standardized mean difference

What happens if you don't see balance after weighting?

You might need to go back to the propensity score model — the logistic regression model that determines the weights — and refine it. For example, by including covariates that were not included the first time but are actually needed, or by adding interactions or flexible terms. It isn't cheating to refine the propensity model at this stage, because we haven't looked at the outcomes yet.

In general, you would tune and iterate the logistic regression model, then reassess balance to see how well the propensity scores are doing at achieving covariate balance. Balance first, outcomes second — that ordering is what keeps the process honest.

08A quick reminder on the assumptions: exchangeability and positivity

Like all observational causal inference methods, IPTW relies on the [exchangeability] (or [ignorability]) assumption — meaning that our measured covariates L fully capture all confounding, and there are no hidden, unmeasured confounders.

To see what exchangeability actually means in plain English, look back at our 10-patient covariate profile, where the propensity score of receiving the drug is 0.2 (2 patients got the treatment, and 8 were in the control group).

[Conditional exchangeability] simply says that within this specific covariate profile, every single one of those 10 patients had the exact same 20% likelihood of receiving the drug, and it was purely by chance that those specific 2 patients were the ones who got it. There is nothing secretly "special" or different about the 2 treated patients compared to the 8 control patients — meaning there are no hidden, unmeasured variables separating them, and you could freely swap (or exchange) any of the subjects within that profile.

Why does this matter for IPTW? Remember that IPTW works by giving each of those 2 treated patients a weight of 5, so they count as 10 patients — standing in for both themselves and the 8 control patients whose treated outcomes are missing. That "stand-in" trick is only valid if those 2 treated patients are genuinely interchangeable with the other 8.

⚠ If exchangeability is violated

Say those 2 specific patients were only given the drug because they had a severe, unrecorded symptom — a hidden confounder [unmeasured confounding] that we didn't include in L. Then they are not fair stand-ins for the 8 healthier control patients. By weighting those 2 secretly sicker patients up by 5, we aren't creating an unbiased pseudo-population — we are just multiplying that hidden, unmeasured bias by 5 across the entire group.

The second assumption is [positivity]: every subject must have some chance — not zero, not one — of receiving either treatment or control, given their covariates: 0 < π(L) < 1 for every covariate profile that occurs. If some profile is always treated, there is nobody in the control group to stand in for them, and no weighting scheme can fix that. Keep positivity in mind — it comes back, wearing a disguise, in the next section.

09Handling extreme values

Okay, so what happens when we have very large weights? And what can we do about it?

First, some intuition on why large weights happen: think of it as how odd that subject is, in terms of their propensity to receive treatment versus what they actually received. If a subject received treatment but their propensity to receive treatment was very low, that results in a very large weight. Similarly, if the propensity to receive treatment was very high but the subject was in the control group, that also results in a very large weight.

We can see this mathematically with the propensity score π. If they're in the treatment group, the weight is 1/π — so if π is very low but they're in the treatment group, the weight is going to be high. If the subject is in the control group, the weight is 1/(1 − π) — so if π is very high, the weight is also going to be very high. (Go back to the weight explorer and push π toward 0.01 or 0.99 to feel this.)

This is a problem because very large weights distort the population, and therefore the estimated expected outcomes. Say one very odd subject contributes a pseudo-population of, let's say, 10,000 subjects. If we didn't have that subject in the study, we might only have a pseudo-population of 100 subjects. If we calculate the expected outcome including this very odd subject — who counts for 10,000 subjects in the pseudo-population — the expected outcome is going to skew very heavily toward the outcome of this one very odd subject.

Extreme weights are also a problem because they lead to larger standard errors. For intuition, think of bootstrapping [bootstrap], which is a way to estimate standard error: we take samples from the population with replacement, record our estimate, and repeat that B times. The standard deviation of the distribution of those draws is basically the standard error. Now, if we have one subject who is worth 10,000 subjects, sometimes we're going to draw that subject in our bootstrap sample, and sometimes we're not. If we do draw them, the statistic we calculate skews heavily toward that subject; if we don't, the statistic will be essentially normal. The statistic for that sample really depends on whether this extremely heavy subject is in the sample or not — and you can see how including this heavy subject increases the standard deviation of the bootstrap distribution, compared to a world where the heavy subject did not exist.

Positivity, almost violated

Recall that the [positivity] assumption means the propensity to receive treatment is not deterministic — it is not 0 or 1. Any given subject in the population has some probability of receiving either treatment or control. Extreme weights mean the propensity score is very close to 0 or 1. It's not exactly 0 or 1, so positivity isn't technically violated — but it's getting very close.

Step 1: Look at the distribution of your weights

First, we want to quantify the problem by looking at the distribution of the weights. One way is to plot the distribution and just see the percentage or frequency of weights that are extreme:

Distribution of IPTW weights — illustrative example

Most patients carry small, well-behaved weights near 1–3. A long, thin tail stretches to the right.

01020 304050 Weight Most weights live here A few extreme weights →

Another good plot: put each patient's rank on the x-axis and their weight on the y-axis, and you can see exactly where the weights start to become extreme:

Weights by rank — illustrative example

Sorted smallest to largest. Flat and boring for almost everyone — then a wall at the far right.

0150300 450Patient rank (sorted by weight) 100500 Small, stable weights for ~97% of patients The spike: a few patients carry the study

Or you could use whichever method you like — summary statistics, box plots, or your favorite way of checking the distribution of any set of numbers.

Step 2: Diagnose the root cause

The first option is to pull out the rows with very high weights and check them manually for anything odd. For example: is it a data entry problem? Are the covariates nonsensical?

Or is there potentially a problem with the logistic regression model used to calculate the propensity scores? Here's one common reason for very high weights. Say there's one covariate, and let's call it covariate X. The typical range of X falls within −0.5 to 0.5 units — let's say 99.9% of the values in the observed dataset fall within that range. But then we observe one subject with X = 10 units, well outside the typical range. After looking at it, we determine that 10 units is an anomaly, but it is valid in the dataset.

Our logistic regression model might be very good at predicting the probability of treatment when X is within −0.5 to 0.5. But once X becomes 10, the model basically has no information around that range, so it's not very good at predicting the propensity of treatment for that covariate profile. If you look at a logistic regression curve, −0.5 to 0.5 sits within the near-linear middle part of the S-curve. Out near the tails, where the curve flattens out, multiple curves can still fit the data well. At x = 10, the propensity score could be 0.7, 0.8, 0.9, or 0.99 — all reasonable fits to the data at −0.5 to 0.5, but we're basically just guessing at the extreme. And of course, propensity scores of 0.7, 0.8, 0.9, and 0.99 would all affect that subject's weight drastically differently (a treated patient at π = 0.99 is fine; a control patient there gets weight 100).

Many logistic curves fit the data you have — and disagree about the data you don't

Four curves that are nearly identical where 99.9% of patients live (−0.5 to 0.5, shaded) fan out to very different propensity scores at x = 10.

0.700.80 0.900.99 One lone patient at x = 10 −0.500.510 00.50.80.90.991.0 Typical range — where the data live one lone patient at x = 10 Covariate X Propensity π(x)

Step 3a: Trimming the tails

Another option is to remove the subjects with extreme weights. This can be justified by making the positivity assumption more plausible — remember, at the extremes the propensity to receive treatment is almost deterministic, and we don't want that.

Let's first look at the distribution of propensity scores in the treated and control groups:

Propensity score distributions and the trimming cutoffs

Blue: control patients. Orange: treated patients. Green band: the overlap we keep. Grey tails: trimmed away.

00.15 0.5 0.75 1.0 Propensity score π Control Treated Common support — keep (0.15 to 0.75) trimmed trimmed

A major problem arises at the extreme edges — the "tails" of these two distributions. Suppose you have treated patients with a 95% propensity score, and almost zero control patients ever score that high. That means there are no comparable untreated patients in that range. Furthermore, if one rare control outlier does exist up at 99%, their IPTW weight will be 1/(1 − 0.99) = 100 — meaning that single person will count as 100 people and make the causal estimate wildly unstable.

1. Cut off treated patients who scored higher than almost all control patients (the upper cutoff)

How it works: Look only at your control group first and find where their scores top out — specifically, the 98th percentile. Suppose 98% of your control patients have a propensity score of 0.75 or lower (only a tiny 2% of control outliers scored higher). That means 0.75 is the practical "ceiling" where control patients stop existing in meaningful numbers. Next, apply that 0.75 ceiling to your dataset and remove any treated patients (and the few control outliers) who scored above 0.75. Why? Because above 0.75, treated patients have no real control counterparts to be compared against.

2. Cut off control patients who scored lower than almost all treated patients (the lower cutoff)

How it works: Now flip the process and look only at your treated group to find where their scores bottom out — specifically, the 2nd percentile. Suppose 98% of your treated patients have a propensity score of 0.15 or higher, and only 2% scored below 0.15. That means 0.15 is the practical "floor" below which treated patients virtually disappear. Apply that 0.15 floor to your dataset and remove any control patients (and the few treated outliers) who scored below 0.15. Why? Because a control patient with a score of 0.02 is someone who would almost never be prescribed the drug in the real world, leaving nobody in the treated group down there to compare them to.

What you're left with: the "Goldilocks" zone of overlap

Once you slice off the extreme right tail (where only treated patients exist) and the extreme left tail (where only control patients exist), you are left strictly with the [common support] middle zone — in our example, patients scoring between 0.15 and 0.75. Trimming gives you two major wins, along with one important trade-off:

  1. It protects the positivity assumption: every patient remaining had a genuine, realistic probability of landing in either group.
  2. It eliminates massive outlier weights: with the extreme tails gone, your weights stay well-behaved and your standard errors stay small.
  3. The trade-off — the target population shifts: by deleting patients at the extremes, you are no longer estimating the causal effect for the entire population. Your results now apply to the subpopulation in the middle — the patients for whom doctors didn't have an obvious, automatic choice and who could have reasonably gone either way. In medicine and data science, this is often the exact group we care about most.

Step 3b: Weight truncation (capping the weights)

The other option — whether we trim the tails or not — is to simply cap (or truncate) the weights [weight truncation] at a certain maximum value. Unlike trimming, we aren't dropping anyone from the dataset. Instead, we decide ahead of time on a maximum allowable weight:

The trade-off, in short:

When we truncate, we reduce the variance of our estimate because a single extreme observation can no longer dominate the sample. However, because we are manually altering the weights and no longer properly weighting that subpopulation to achieve perfect balance, we let a small amount of confounding slip back in — which introduces bias. Ultimately, this is a classic [bias–variance trade-off]: the decision is whether a big decrease in variance is worth a small increase in bias.

MSE = bias² + variance Mean squared error [mean squared error] is how we score the trade-off: total error = squared bias + variance.

Simulation studies have shown that when you only truncate a small number of extreme outlier weights (like at the 98th or 99th percentile), the massive drop in variance usually outweighs the tiny increase in bias, leading to a lower overall MSE and a much more reliable estimate. In practice, you should compare your truncated and untruncated estimates side by side as a sensitivity analysis [sensitivity analysis], to verify that your overall conclusion remains consistent while your confidence intervals tighten up.

Part II

Modeling using IPTW data

10Intuition on marginal structural models

The big shift: potential outcomes vs. observed outcomes

To understand a marginal structural model [marginal structural model], we first have to understand the difference between modeling observed outcomes versus potential outcomes:

Why is it called "marginal"?

In standard statistics, when you want to control for a bunch of confounding variables (like age, blood pressure, and health history), you throw them all into your regression equation. That gives you a conditional effect [conditional effect] — the effect of the drug holding age and blood pressure strictly constant.

An MSM is marginal because it doesn't force those background variables into the final regression equation. Thanks to our IPTW weights, all those background variables have already been balanced out behind the scenes. Marginalizing simply means this: because our weights have already smoothed out differences in things like age and blood pressure between groups, those factors don't need to clutter up our final equation. We can remove them from the regression model and zoom out to look at the big-picture, population-level relationship [marginal effect] between the treatment and the outcome.

Types of marginal structural models

There are different types of marginal structural models, and I'll briefly outline some of the common ones below. Essentially, once we fit these models onto the pseudo-population, we can answer different questions about the treatment effect on potential outcomes — the model type is chosen by the link function [link function]:

Common marginal structural modelsSame pseudo-population, three different questions

Model typeWhat it calculatesThe question it answersIn plain English
Linear MSM (identity link)Average treatment effect"What is the absolute difference in heart attack rates if everyone took the drug versus if no one did?"Measures a flat, absolute change — e.g., "the drug prevents 3 heart attacks per 100 people across the population."
Log-link MSM (log link)Causal relative risk"What is the ratio of heart attack risk if everyone took the drug versus if no one did?"Measures a proportional scaling factor — e.g., "taking the drug scales your risk down to 70% of what it would have been."
Logistic MSM (logit link)Causal odds ratio"How do the odds of a heart attack compare between a world where everyone takes the drug versus no one?"Compares the odds of the event occurring under the two counterfactual worlds (commonly used in case-control or logistic regression workflows).

Linear MSM example

As an example, let's walk through fitting a linear marginal structural model onto the pseudo-population. As we just said, the linear MSM basically helps us determine the average treatment effect. Previously, we saw how IPTW lets us calculate the ATE by taking the standard average in our treated pseudo-population (E[Y1]) minus the standard average in our control pseudo-population (E[Y0]). If we write out a simple linear MSM, it looks just like a standard regression equation, with one crucial difference:

E[Ya] = β0 + β1·a Read Ya as "the outcome if we set treatment to a for everyone."

The catch: setting a vs. conditioning on observed treatment A

You may ask: why can't we just fit this model on our raw observational data using standard regression, E[Y | A = a]? Because that formula answers an associative question: "What was the average outcome among the subset of patients who actually received treatment versus the subset who did not?" We can calculate this directly from raw observed data, because we know which group each patient ended up in and what happened to them — but because of confounding, those two groups aren't comparable (e.g., unhealthy patients received the drug and healthy patients did not).

In a marginal structural model, E[Ya], the question is fundamentally different: "What would the expected outcome be across all patients if everyone were given treatment, versus if no one were given treatment?" In the real world, we are missing half of the data needed to answer this. For the observed treated group, we don't have data showing what their outcomes would have been had they gone untreated; for the control group, we don't have data showing what would have happened had they been treated.

IPTW gives us a methodology to bypass this missing-data problem: by weighting each group to represent the entire population, we construct a balanced pseudo-population that mimics those missing potential outcomes, allowing us to fit a standard regression model directly on the weighted data (the pseudo-population).

The mechanics: fitting regression on the pseudo-population

Here is where IPTW bridges the gap. Look back at how we built our pseudo-population in the 10-patient example:

In this weighted pseudo-population, both groups have been scaled up to represent the exact same 10-patient profile, completely erasing confounding. Because the weighted treatment group is now an exact mirror of the entire population (just like in a randomized controlled trial), we no longer have to worry about selection bias. Simply looking at the outcomes of the treated group inside our pseudo-population tells us what would happen if the entire population were given the drug — and looking at the weighted control group tells us what would happen if no one were given the drug. In practice, this means we can treat the weighted pseudo-population as if its observed outcomes are the potential outcomes.

Mathematically, when you run a standard generalized linear model [generalized linear model] — like linear or logistic regression — the software estimates parameters by solving an equation that balances the weighted differences (residuals) between each patient's observed outcome Y and the model's predicted average. To fit an MSM, we use the exact same regression machinery, but we multiply each patient's contribution by their IPTW weight W:

Unweighted:  Σi ( Yi − predictedi ) · xi = 0
Weighted (MSM):  Σi Wi · ( Yi − predictedi ) · xi = 0 This is a [weighted estimating equation]: the only change from ordinary regression is that each person's residual counts W times — once for themselves, and once for each person they're standing in for.

In our 10-patient example, the software gives each of the 2 treated patients 5 times the voice in the regression, and each of the 8 control patients 1.25 times the voice. Because the regression is now fitting directly to the unconfounded pseudo-population, the coefficients that come out of your standard regression software are no longer biased observational associations — they are the causal parameters of your marginal structural model.

Testing subgroup effects (effect modification)

Suppose you balanced 30 confounders using IPTW, and now you want to know if the drug works differently for patients with diabetes (V = 1) versus without diabetes (V = 0) [effect modification]. Instead of wrestling with 30 covariates, you only include treatment a, diabetes status V, and their interaction in your weighted regression:

E[Ya] = β0 + β1a + β2V + β3aV

…while keeping all other 29 confounders safely marginalized (averaged out) in the background.

Adjusting the standard errors

Don't skip this step

Notice that in our 10-patient profile, weighting turned 2 treated patients and 8 control patients into 10 weighted treated patients and 10 weighted control patients (20 total "pseudo-patients"). Because weighting artificially inflates the apparent sample size, standard regression software will think you have more data than you really do, and output standard errors that are too small. Therefore, when fitting an MSM on weighted data, always pair your model with robust "sandwich" standard errors [robust sandwich standard errors] or bootstrapping, so your confidence intervals reflect your true sample size.

11The two-model workflow: propensity scores vs. marginal structural models

One of the most common points of confusion when learning IPTW is that you end up running regression models at two entirely different stages of the analysis. Because both involve fitting a model, it's easy to mix them up. To keep them straight, remember that they have completely different jobs, inputs, and goals. Here is how to tell them apart:

Two models, two completely different jobs

FeatureModel 1: the propensity score modelModel 2: the marginal structural model
What is its main job?To calculate the probability of treatment and build the weights.To estimate the actual causal effect of the treatment on your outcome.
What goes into the model?Your covariates (L) predict the treatment (A).The treatment (A) predicts the outcome (Y) — fitted as a weighted regression, where the IPTW weights enter as regression weights, not as a predictor variable.
Do you include your 30 confounders?Yes. You throw all your background variables (age, blood pressure, history) into this model to figure out selection bias.No. The weights have already balanced out those confounders behind the scenes, keeping your final equation clean.
What kind of model is it?Almost always a logistic regression (since treatment status is binary: 0 or 1).A weighted regression chosen based on your outcome type (e.g., linear regression for continuous outcomes, logistic or log-link regression for binary outcomes like heart attacks).
What comes out of it?A propensity score (π) for each patient, which becomes a weight (1/π or 1/(1 − π)).A causal parameter — such as a causal relative risk, odds ratio, or mean difference.

Summary of the pipeline

Step 1

Fit the propensity score model

You use a logistic regression across your raw observational data to look at all the messy confounding factors and figure out who tended to get the drug. You turn those predictions into weights.

Step 2

Build the pseudo-population

You multiply your patients by those weights, creating a balanced world where confounding is erased — and check balance (section 7) before going further.

Step 3

Fit the marginal structural model

You run a standard regression (linear or logistic) directly on that weighted pseudo-population. Because the weights did the heavy lifting beforehand, the coefficient you get out is your true, unconfounded causal effect.

12Intuition on doubly robust estimators

Having two chances to be right

Up to this point, we've seen how IPTW lets us estimate causal effects. By modeling the probability of receiving treatment (the propensity score) and weighting our patients accordingly, we create a balanced pseudo-population where we can calculate the expected outcome if everyone received the drug (E[Y1]), the expected outcome if no one received the drug (E[Y0]), and the difference between them — the average treatment effect.

There is just one lingering question with IPTW: what if our propensity score model is wrong? In the real world, we don't know the true mathematical formula that doctors used to prescribe the drug. If we accidentally miss an important interaction term or a non-linear relationship when building our propensity score model, our weights will be off, and our causal estimate will be biased.

Enter doubly robust estimators [doubly robust / augmented IPTW] — also known as augmented inverse probability of treatment weighting (AIPTW). The main idea is simple: instead of relying entirely on a single model to remove confounding, we combine two different models into one formula, so that we only have to get one of them right to get an unbiased causal estimate.

1. What are the two models trying to predict (and what data do they use)?

Let's first distinguish between the overall goal of the estimator and the two individual models that feed into it. The overall goal, just like standard IPTW, is to calculate the population-level potential outcomes — specifically, the average outcome if the entire population took the drug (E[Y1]) versus if no one took the drug (E[Y0]). To get there, we train two completely separate models on our raw, unweighted observed data:

Notice the symmetry: the IPTW path is unbiased if your propensity score model π(L) is correct, while the outcome regression path is unbiased if your outcome model m1(L) is correct.

2. How AIPTW combines both models (the math & intuition)

A doubly robust estimator puts both models into a single equation. Let's look at how AIPTW estimates E[Y1] (the average outcome if everyone in our sample of n patients took the drug):

Ê[Y1] = 1n Σi [ m1(Li) + Ai(Yi − m1(Li))πi ] In words: start with the outcome model's prediction for everyone, then add an IPTW-weighted correction using only the treated patients' prediction errors.

Here is what each variable means in plain English:

3. Why you only need one model to be right

The magic of this equation is easiest to see when we also write out its algebraically rearranged version:

Ê[Y1] = 1n Σi [ AiYiπi − (Ai − πi)πi · m1(Li) ] Same estimator, rearranged: plain IPTW, minus a correction term. The two scenarios below are about which term does the saving — and the cancellations happen in expectation (on average, over repeated samples), not exactly in any single dataset.

Look at how this acts as a built-in safety net under two different scenarios:

In short: each model acts as an insurance policy for the other.

4. When and why should you use doubly robust estimators?

Beyond the peace of mind of getting "two chances to be right," there are three practical reasons why data scientists and clinical researchers increasingly prefer AIPTW over standard IPTW:

  1. Insurance against model misspecification [model misspecification]: in complex healthcare or user-behavior data, sometimes it is much easier to model how doctors make prescribing decisions (π) than it is to model complex biological disease progression (m) — or vice versa. Doubly robust estimation protects you as long as you capture at least one of those two mechanisms accurately.
  2. Smaller variance (higher efficiency) [efficiency]: even when your propensity score model is 100% correct, semiparametric theory shows that AIPTW is more statistically efficient than standard IPTW when both models are correct. By anchoring the estimate with outcome predictions, AIPTW produces tighter confidence intervals and smaller standard errors than weighting alone.
  3. The gateway to modern machine learning causal inference: because AIPTW separates treatment prediction (π) and outcome prediction (m) into two unweighted models on observed data whose errors multiply together, it forms the foundation for modern machine learning causal methods, like double/debiased machine learning [double machine learning] and targeted maximum likelihood estimation [targeted maximum likelihood estimation].
One honest limit

"Doubly robust" does not protect against unmeasured confounding. Both models still rely on the exchangeability assumption — that you measured all the necessary confounders L in the first place. Two chances to be right about the models; no extra chances about the data.

13Worked example of time-varying analysis with IPTW

Let's start with a group of 200 patients who all share the same baseline covariate profile — let's call it "overall health" (X). Over a 2-year period, we want to understand if patients who take a drug for 2 years straight have a lower myocardial infarction rate at year 2 than patients who do not take the drug in either year. The drug is potentially administered at time 0 and again at year 1, with the outcome measured at year 2. At time 0, some of these patients with the same initial health profile receive the drug (the treatment group) and others do not (the control group).

One year later, at year 1, the doctor reassesses each subject's covariate profile before deciding whether to prescribe the drug for the second year. Even though everyone started with the same health profile at time 0, their covariate profiles have now shifted over time — both due to the time-0 drug and due to natural factors. For example, most of the patients who took the drug at time 0 may have gotten healthier, while most of the patients who did not take the drug at time 0 may have gotten sicker.

Why can't we use matching at year 1?

Look at what happens if we match on health profiles at year 1. First, matching at year 1 changes our question to: "What is the isolated effect of receiving the drug at year 1 on myocardial infarction rates at year 2?" — which completely ignores the benefit the drug already produced during year 0. For instance, at year 1 we would match the healthy profiles of patients who took the drug at time 0 with the healthy profiles of patients in the control group who didn't take the drug. But this completely ignores the fact that the healthy profiles in the treatment group are newly healthy, and the healthy profiles in the control group are likely outliers, because they stayed healthy without the drug. Matching across groups at year 1 completely erases this historical information. (Furthermore, since those healthy subjects in the control group are likely rare outliers, we'd likely be throwing out a lot of information with matching.)

Now look at what happens when we use IPTW instead. Weighting preserves the patients' history at year 1 by scaling subjects within their own trajectory rather than matching across groups. In the treatment group, we look at the subjects who took the drug at both time 0 and year 1, and we weight them accordingly to stand in for the subjects who started in the treatment group at time 0 but dropped off the drug at year 1. We do the exact same thing in the control group: at year 1, we take the subjects who remained untreated in both years and weight them accordingly to stand in for the subjects who started in the control group at time 0 but dropped off the control trajectory because they were prescribed the drug at year 1.

By weighting this way, we preserve the historical covariate profile shift from time 0 to year 1 and reconstruct a pseudo-population of our original time-0 treatment and control groups — allowing us to fairly compare the myocardial infarction rates of taking the drug for 2 full years versus not taking the drug in either year.

Here is the diagram with toy numbers to illustrate the point and give mathematical intuition:

Longitudinal IPTW tree diagram: 200 patients split at time 0 into 140 drug and 60 no drug; each branch splits by year-1 health (healthy or sick) and year-1 treatment, with the always-treated paths totaling 200 pseudo-patients and the never-treated paths totaling 200 pseudo-patients
The full two-year tree. Only the paths that stayed the course — always treated, or never treated — get weighted up; each one ends up representing all 200 original patients. ("Dropped" paths are the patients who switched, and whom the stayers stand in for.)

Step 1: Time 0 weights (W0)

You start with 200 patients sharing the exact same baseline profile (X):

Step 2: Year 1 weights (W1) — branch by branch

At year 1, doctors look at whether a patient is healthy or sick and decide whether to prescribe the drug for year 1. The year-1 health split: of the 140 who took the drug at time 0, 112 are healthy (80%) and 28 are sick (20%); of the 60 who didn't, 12 are healthy (20%) and 48 are sick (80%). Look at the pattern in the four branches:

Because we want to compare "always treated" (drug in both years) against "never treated" (no drug in both years) [treatment strategies], let's trace the 4 groups of patients who stayed the course and see who they are standing in for:

A. The "always treated" branches (drug at time 0 → drug at year 1)

  1. Top branch (drug → healthy → drug): 28 patients. Out of the 112 healthy patients here, only 28 stayed on the drug while 84 dropped off. Probability of continuing the drug given healthy: 28/112 = 0.25. Year 1 weight W1 = 1/0.25 = 4. Intuition: each of these 28 patients is weighted by 4 at year 1, so 28 × 4 = 112 — standing in for themselves plus the 84 healthy patients who stopped taking the drug.
  2. Second branch (drug → sick → drug): 21 patients. Out of the 28 sick patients here, 21 stayed on the drug while 7 dropped off. Probability of continuing the drug given sick: 21/28 = 0.75. Year 1 weight W1 = 1/0.75 = 4/3 ≈ 1.33. Intuition: each of these 21 patients is weighted by 4/3 at year 1, so 21 × 4/3 = 28 — standing in for themselves plus the 7 sick patients who stopped taking the drug.

B. The "never treated" branches (no drug at time 0 → no drug at year 1)

  1. Third branch (no drug → healthy → no drug): 9 patients. Out of the 12 healthy patients here, 9 stayed off the drug while 3 started taking it. Probability of staying off the drug given healthy: 9/12 = 0.75. Year 1 weight W1 = 1/0.75 = 4/3 ≈ 1.33. Intuition: each of these 9 patients is weighted by 4/3, so 9 × 4/3 = 12 — standing in for all 12 healthy control patients.
  2. Bottom branch (no drug → sick → no drug): 12 patients. Out of the 48 sick patients here, 12 stayed off the drug while 36 started taking it. Probability of staying off the drug given sick: 12/48 = 0.25. Year 1 weight W1 = 1/0.25 = 4. Intuition: each of these 12 patients is weighted by 4, so 12 × 4 = 48 — standing in for all 48 sick control patients.

Step 3: Total final weights (W0 × W1) and how to apply them

In longitudinal IPTW [longitudinal IPTW], a patient's final weight is simply the product of their weights at each time point (Wtotal = W0 × W1). Look at how cleanly the numbers multiply out, so that both groups represent all 200 original patients:

Final weights for the patients who stayed the courseEveryone else switched at year 1 — these are the patients who stand in for them

Subgroup pathObserved patients, nTime 0 weightYear 1 weightTotal weightWeighted pseudo-patients
Always treated (healthy at year 1)2810/7440/7 ≈ 5.7128 × 40/7 = 160
Always treated (sick at year 1)2110/74/340/21 ≈ 1.9021 × 40/21 = 40
Total "always treated"49———200
Never treated (healthy at year 1)910/34/340/9 ≈ 4.449 × 40/9 = 40
Never treated (sick at year 1)1210/3440/3 ≈ 13.3312 × 40/3 = 160
Total "never treated"21———200

Every single group adds back up to 200:

Putting it all together: from longitudinal weights to causal estimates

The beauty of longitudinal IPTW is that all the heavy lifting happens during this weight-calculation step. Once you multiply the weights across each time period to get a single final weight for each patient (Wtotal), the rest of your outcome analysis is 100% identical to the single-time-point workflow we covered earlier:

The takeaway

Accounting for multiple time periods and time-varying confounders only changes how we build the weights. Once every patient has their final weight, you analyze the weighted pseudo-population the exact same way. That's the whole playbook: model who gets treated → build weights → check balance → handle the extremes → run a weighted regression → report a causal effect.