py-why/dowhy

DoWhy is a Python library for causal inference that supports explicit modeling and testing of causal assumptions. DoWhy is based on a unified language for causal inference, combining causal graphical models and potential outcomes frameworks.

DoWhy – End‑to‑End Causal Inference in Python

What it is

  • A Python library that lets you ask causal questions ("what if I intervene?", "what caused this outcome?", "what are the root causes of an anomaly?") and get statistically sound answers.
  • It combines two major causal‑inference frameworks: graphical causal models (Pearl’s do‑calculus) and the potential‑outcomes approach.
  • Part of the PyWhy ecosystem, which focuses on tools for causality.

Key capabilities

Capability What you can do
Effect estimation Identify causal effects, compute average or conditional treatment effects, use instrumental variables, etc.
Causal influence quantification Mediation analysis, direct/indirect effect strengths, intrinsic influence measures.
What‑if / counterfactual analysis Generate samples from an interventional distribution, compute counterfactual outcomes for individuals.
Root‑cause analysis & explanations Attribute anomalies to specific variables, explain distribution shifts, rank feature relevance.
Refutation / falsification Run robustness checks (e.g., random common cause, placebo tests) to see if your causal claim holds under alternative assumptions.

Typical workflow (four steps)

  1. Model – supply data, treatment/outcome names, and a causal graph (NetworkX, DOT, etc.).
  2. Identify – let DoWhy apply do‑calculus to derive the estimand (the mathematical expression of the causal effect).
  3. Estimate – plug in a statistical estimator (propensity‑score matching, linear regression, EconML’s DML, etc.) to compute the effect.
  4. Refute – automatically run one or more falsification tests to gauge robustness.

Quick start

# Install the latest stable release
pip install dowhy          # or `conda install -c conda-forge dowhy`
from dowhy import CausalModel
import dowhy.datasets as ds

# Load a synthetic dataset
data = ds.linear_dataset(beta=10, num_common_causes=5,
                         num_instruments=2, num_samples=10000,
                         treatment_is_binary=True)

model = CausalModel(data=data["df"],
                    treatment=data["treatment_name"],
                    outcome=data["outcome_name"],
                    graph=data["gml_graph"])  # graph can also be a NetworkX DiGraph

identified_estimand = model.identify_effect()
estimate = model.estimate_effect(identified_estimand,
                                 method_name="backdoor.propensity_score_matching")
refute_res = model.refute_estimate(identified_estimand, estimate,
                                   method_name="random_common_cause")
print(estimate)
print(refute_res)

The library prints a readable summary of assumptions, the identified estimand, the numeric estimate, and the refutation results.

Graphical Causal Model (GCM) extension

  • Beyond effect estimation, DoWhy‑GCM lets you define structural causal models (SCMs) with explicit functional mechanisms for each node.
  • You can fit these SCMs to data, evaluate their fit, and then perform tasks such as:
    • Root‑cause attribution (gcm.attribute_anomalies)
    • Interventional sampling (gcm.interventional_samples)
    • Counterfactual queries
  • Example (X → Y → Z):
import networkx as nx, pandas as pd, numpy as np
from dowhy import gcm

# synthetic data
X = np.random.normal(size=1000)
Y = 2*X + np.random.normal(size=1000)
Z = 3*Y + np.random.normal(size=1000)
df = pd.DataFrame(dict(X=X, Y=Y, Z=Z))

scm = gcm.StructuralCausalModel(nx.DiGraph([('X','Y'),('Y','Z')]))
gcm.auto.assign_causal_mechanisms(scm, df)
gcm.fit(scm, df)

# root‑cause of an anomalous Z value
anomaly = pd.DataFrame(dict(X=[0.1], Y=[6.2], Z=[19]))
print(gcm.attribute_anomalies(scm, "Z", anomaly))

Where to learn more

  • Full documentation & tutorials: https://py-why.github.io/dowhy/
  • Example notebooks (effect estimation, root‑cause analysis, CATE with EconML, etc.)
  • Video webinars from Microsoft Research and PyCon talks (links in the README)
  • Academic papers: arXiv 2020 (core DoWhy) and JMLR 2024 (DoWhy‑GCM)

Community & contribution

  • Discord chat for questions: https://discord.gg/cSBGb3vsZb
  • Issues are filed on GitHub; contributions are welcomed via the usual pull‑request workflow.

Bottom line DoWhy provides a clean, high‑level API that hides the heavy mathematics of causal inference while still giving you full control over graphs, estimators, and robustness checks. It’s suitable for data scientists, researchers, and engineers who need to move beyond correlation and make decisions based on causation.

Related

  • Project
  • Project
  • Project
  • Project
  • Project