DoWhy Tutorial: Causal Inference in Python from DAG to Estimate

Use DoWhy's four steps (model, identify, estimate, refute) on a worked example, chart the results, and learn what the refutation tests can't catch.

DoWhy is a Python library that splits causal inference into four steps: create a CausalModel from your data and causal graph, call identify_effect(), call estimate_effect(), then refute_estimate(). This post uses DoWhy 0.14, which supports Python 3.9 to 3.13 but not 3.14 (pip install dowhy matplotlib).

Quick Example

Did a training course raise sales per employee? Employees with longer tenure and those in bigger stores were more likely to take it, and they sell more anyway. The data is simulated with a true effect of 6.

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
from dowhy import CausalModel

rng = np.random.default_rng(179)

# Sample data: who took the training depends on tenure and store size
n = 5000
tenure = rng.uniform(0, 10, n)          # years
store_size = rng.normal(size=n)         # standardized
p = 1 / (1 + np.exp(1.5 - 0.3 * tenure - 0.8 * store_size))
training = rng.binomial(1, p)
sales = 50 + 6 * training + 3 * tenure + 8 * store_size + rng.normal(0, 10, n)
df = pd.DataFrame(dict(tenure=tenure, store_size=store_size,
                       training=training, sales=sales))

# 1. Model: state which variables cause which
graph = nx.DiGraph([
    ("tenure", "training"), ("tenure", "sales"),
    ("store_size", "training"), ("store_size", "sales"),
    ("training", "sales"),
])
model = CausalModel(data=df, treatment="training", outcome="sales",
                    graph=graph)

# 2. Identify: work out what to adjust for
estimand = model.identify_effect()

# 3. Estimate
estimate = model.estimate_effect(
    estimand, method_name="backdoor.linear_regression",
    confidence_intervals=True)
low, high = estimate.get_confidence_intervals()[0]
raw = df.groupby("training").sales.mean().diff().iloc[1]
print(f"raw difference: {raw:.1f}")
print(f"DoWhy estimate: {estimate.value:.1f} (95% CI {low:.1f} to {high:.1f})")

# 4. Refute: a made-up treatment should have no effect
placebo = model.refute_estimate(
    estimand, estimate, method_name="placebo_treatment_refuter",
    placebo_type="permute", num_simulations=100, random_seed=0)
print(f"placebo effect: {placebo.new_effect:.2f}")
raw difference: 17.3
DoWhy estimate: 6.1 (95% CI 5.5 to 6.8)
placebo effect: -0.01

The raw gap is far above the true effect of 6. After adjusting for the two confounders, the estimate lands close to it, and shuffling the treatment column makes the effect disappear.

Draw the causal graph

The graph is an ordinary NetworkX object, so you can plot it:

pos = {"tenure": (0, 1), "store_size": (2, 1),
       "training": (0, 0), "sales": (2, 0)}
fig, ax = plt.subplots(figsize=(7, 4))
nx.draw_networkx(graph, pos, ax=ax, node_size=5200, node_color="#e4ddf2",
                 edgecolors="#4a3b73", font_size=10, arrowsize=18)
ax.margins(0.18)
ax.axis("off")
plt.show()

Causal graph where tenure and store size both point to training and sales, and training points to sales

For layouts and backdoor paths, see drawing causal DAGs in Python.

What does identify_effect() tell you?

print("adjust for:", sorted(estimand.get_backdoor_variables()))
print("instruments:", estimand.get_instrumental_variables())
adjust for: ['store_size', 'tenure']
instruments: []

DoWhy found a backdoor adjustment set and no instrument. print(estimand) shows the formulas and the assumption behind each: here, that nothing unmeasured affects both training and sales.

Compare estimation methods

The same estimand can be estimated several ways. Agreement between methods that model different things (the outcome, or who gets treated) is reassuring.

methods = {
    "Linear regression": ("backdoor.linear_regression", {}),
    "Propensity matching": ("backdoor.propensity_score_matching", {}),
    "Propensity weighting": (
        "backdoor.propensity_score_weighting",
        {"method_params": {"weighting_scheme": "ips_stabilized_weight"}}),
    "Propensity stratification": (
        "backdoor.propensity_score_stratification", {}),
}
results = {"Raw difference": raw}
for label, (name, extra) in methods.items():
    results[label] = model.estimate_effect(
        estimand, method_name=name, **extra).value
results = pd.Series(results)
print(results.round(2))

fig, ax = plt.subplots(figsize=(8, 4))
bars = ax.barh(results.index, results,
               color=["#b4b4b4"] + ["#6c56a3"] * 4)
ax.bar_label(bars, fmt="{:.2f}", padding=7)
ax.axvline(6, color="#d1495b", ls="--", label="True effect (6)")
ax.invert_yaxis()
ax.set_xlim(0, results.max() * 1.15)
ax.set_xlabel("Estimated effect of training on sales")
ax.legend(loc="lower right")
plt.show()
Raw difference               17.27
Linear regression             6.12
Propensity matching           5.96
Propensity weighting          5.75
Propensity stratification     6.78
dtype: float64

Bar chart of the raw difference and four DoWhy estimates; the four adjusted estimates are close to the true effect of 6 and the raw difference is far higher

All four adjusted estimates fall between 5.75 and 6.78. Linear regression is the closest to the truth here partly because the simulated outcome really is linear. For balance checks, which you should do before trusting a propensity method, see propensity score matching.

Run refutation tests

Each refuter changes something and re-estimates:

Refuter Change A healthy result
random_common_cause Adds a random covariate Estimate barely moves
placebo_treatment_refuter Shuffles the treatment Estimate near 0
data_subset_refuter Uses a random 80% of rows Estimate barely moves
def refute(model, estimand, estimate):
    checks = {
        "random_common_cause": {},
        "placebo_treatment_refuter": {"placebo_type": "permute"},
        "data_subset_refuter": {"subset_fraction": 0.8},
    }
    return pd.Series({
        name: model.refute_estimate(
            estimand, estimate, method_name=name, num_simulations=100,
            random_seed=0, **kwargs).new_effect
        for name, kwargs in checks.items()})

print(refute(model, estimand, estimate).round(2))
random_common_cause          6.12
placebo_treatment_refuter   -0.01
data_subset_refuter          6.12
dtype: float64

All three behave as they should.

Do refutation tests catch a missing confounder?

Drop tenure from the data and the graph, as if nobody had recorded it, and run the same steps.

small_graph = graph.copy()
small_graph.remove_node("tenure")
bad_model = CausalModel(data=df.drop(columns="tenure"), treatment="training",
                        outcome="sales", graph=small_graph)
bad_estimand = bad_model.identify_effect()
bad_estimate = bad_model.estimate_effect(
    bad_estimand, method_name="backdoor.linear_regression")
bad_checks = refute(bad_model, bad_estimand, bad_estimate)
good_checks = refute(model, estimand, estimate)

table = pd.DataFrame({"All confounders": good_checks,
                      "Tenure missing": bad_checks})
table.loc["original estimate"] = [estimate.value, bad_estimate.value]
table = table.loc[["original estimate", "random_common_cause",
                   "placebo_treatment_refuter", "data_subset_refuter"]]
print(table.round(2))

labels = ["Original", "Random\ncommon cause", "Placebo\ntreatment",
          "80% subset"]
fig, ax = plt.subplots(figsize=(8, 4.2))
x = np.arange(4)
for offset, column, color in [(-0.2, "All confounders", "#6c56a3"),
                              (0.2, "Tenure missing", "#e08e45")]:
    bars = ax.bar(x + offset, table[column], 0.4, label=column, color=color)
    ax.bar_label(bars, padding=2, labels=[
        "0.0" if abs(v) < 0.05 else f"{v:.1f}" for v in table[column]])
ax.axhline(6, color="#d1495b", ls="--", lw=1, label="True effect")
ax.axhline(0, color="black", lw=0.8)
ax.set_xticks(x, labels)
ax.set_ylim(-1, 17)
ax.set_ylabel("Estimated effect")
ax.legend(ncols=3, loc="upper center")
plt.show()
All confounders  Tenure missing
original estimate                     6.12           12.98
random_common_cause                   6.12           12.98
placebo_treatment_refuter            -0.01           -0.01
data_subset_refuter                   6.12           12.98

Grouped bar chart of refutation results with and without tenure; both pass every check although the estimate without tenure is more than double the true effect

The estimate without tenure is badly wrong and passes every test. These refuters look for instability and false signals. They can't tell you that a confounder is missing, so "refutation passed" is not evidence that the estimate is right.

How strong would a hidden confounder need to be?

add_unobserved_common_cause simulates a confounder of varying strength. Here it flips a share of the treatment values and shifts sales linearly.

flip = [0.01, 0.02, 0.03, 0.04, 0.05]
shift = [1, 3, 5, 7, 9]

np.random.seed(0)
sensitivity = model.refute_estimate(
    estimand, estimate, method_name="add_unobserved_common_cause",
    confounders_effect_on_treatment="binary_flip",
    confounders_effect_on_outcome="linear",
    effect_strength_on_treatment=np.array(flip),
    effect_strength_on_outcome=np.array(shift),
    plotmethod=None)
grid = sensitivity.new_effect_array

fig, ax = plt.subplots(figsize=(6.5, 4.8))
image = ax.imshow(grid, cmap="Purples", vmin=0, vmax=6.5)
for (i, j), value in np.ndenumerate(grid):
    ax.text(j, i, f"{value:.1f}", ha="center", va="center",
            color="white" if value > 3.8 else "black")
ax.set_xticks(range(5), shift)
ax.set_yticks(range(5), [f"{f:.0%}" for f in flip])
ax.set_xlabel("Confounder's effect on sales")
ax.set_ylabel("Share of treatment values flipped")
fig.colorbar(image, label="New estimate")
plt.show()

Heatmap of the re-estimated training effect, shrinking as the simulated unobserved confounder gets stronger

Flipping 1% of treatment values barely changes the estimate. By 5% it has dropped to between 1.4 and 2.2. Flipping treatment also adds noise, which shrinks an effect on its own, so read the grid as a stress test and not as a precise statement about a real confounder. The cells aren't perfectly ordered because each is one random simulation.

When should you use DoWhy?

  • Use it when you want the assumptions written down as a graph and the checks run in a consistent way, or when you're comparing several estimators.
  • For a single regression, statsmodels or scikit-learn code is more transparent.
  • For effects that differ by customer, use a causal forest. DoWhy can also call EconML estimators.
  • For designs such as difference-in-differences or synthetic control, use tools built for them.

Similar Topics