# Getting started with DoWhy: A simple example

This is a quick introduction to the DoWhy causal inference library. We will load in a sample dataset and estimate the causal effect of a (pre-specified)treatment variable on a (pre-specified) outcome variable.

First, let us add the required path for Python to find the DoWhy code and load all required packages.

[1]:

import os, sys
sys.path.append(os.path.abspath("../../../"))


Let’s check the python version.

[2]:

print(sys.version)

3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0]

[3]:

import numpy as np
import pandas as pd

import dowhy
from dowhy import CausalModel
import dowhy.datasets


Now, let us load a dataset. For simplicity, we simulate a dataset with linear relationships between common causes and treatment, and common causes and outcome.

Beta is the true causal effect.

[4]:

data = dowhy.datasets.linear_dataset(beta=10,
num_common_causes=5,
num_instruments = 2,
num_effect_modifiers=1,
num_samples=10000,
treatment_is_binary=True,
num_discrete_common_causes=1)
df = data["df"]
print(data["dot_graph"])
print("\n")
print(data["gml_graph"])

(10000, 5)
(10000,)

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-9008e6a0369d> in <module>
5         num_samples=10000,
6         treatment_is_binary=True,
----> 7         num_discrete_common_causes=1)
8 df = data["df"]

/mnt/c/Users/amshar/code/dowhy/dowhy/datasets.py in linear_dataset(beta, num_common_causes, num_samples, num_instruments, num_effect_modifiers, num_treatments, treatment_is_binary, outcome_is_binary, num_discrete_common_causes, num_discrete_instruments, num_discrete_effect_modifiers)
48             w_bins = np.quantile(W[:, w_index], q=quantiles)
49             W[:, w_index] = np.digitize(W[:, w_index], bins=w_bins)
---> 50             dummy_vecs = np.eye(len(quantiles)+1)[W[:, w_index]]
51             W_dummy = np.delete(W_dummy, w_index, axis=1)
52             W_dummy = np.concatenate((W_dummy, dummy_vecs), axis=1)

IndexError: arrays used as indices must be of integer (or boolean) type


Note that we are using a pandas dataframe to load the data. At present, DoWhy only supports pandas dataframe as input.

## Interface 1 (recommended): Input causal graph

We now input a causal graph in the GML graph format (recommended). You can also use the DOT format.

[ ]:

# With graph
model=CausalModel(
data = df,
treatment=data["treatment_name"],
outcome=data["outcome_name"],
graph=data["gml_graph"]
)

[ ]:

model.view_model()

[ ]:

from IPython.display import Image, display
display(Image(filename="causal_model.png"))


The above causal graph shows the assumptions encoded in the causal model. We can now use this graph to first identify the causal effect (go from a causal estimand to a probability expression), and then estimate the causal effect.

DoWhy philosophy: Keep identification and estimation separate

Identification can be achieved without access to the data, acccesing only the graph. This results in an expression to be computed. This expression can then be evaluated using the available data in the estimation step. It is important to understand that these are orthogonal steps.

• Identification

[ ]:

identified_estimand = model.identify_effect()
print(identified_estimand)


If you want to disable the warning for ignoring unobserved confounders, you can add a parameter flag ( proceed_when_unidentifiable ). The same parameter can also be added when instantiating the CausalModel object.

[ ]:

identified_estimand = model.identify_effect(proceed_when_unidentifiable=True)
print(identified_estimand)

• Estimation

[ ]:

causal_estimate = model.estimate_effect(identified_estimand,
method_name="backdoor.propensity_score_stratification")
print(causal_estimate)
print("Causal Estimate is " + str(causal_estimate.value))


You can input additional parameters to the estimate_effect method. For instance, to estimate the effect on any subset of the units, you can specify the “target_units” parameter which can be a string (“ate”, “att”, or “atc”), lambda function that filters rows of the data frame, or a new dataframe on which to compute the effect. You can also specify “effect modifiers” to estimate heterogeneous effects across these variables. See help(CausalModel.estimate_effect).

[ ]:

# Causal effect on the control group (ATC)
causal_estimate_att = model.estimate_effect(identified_estimand,
method_name="backdoor.propensity_score_stratification",
target_units = "atc")
print(causal_estimate_att)
print("Causal Estimate is " + str(causal_estimate_att.value))


## Interface 2: Specify common causes and instruments

[ ]:

# Without graph
model= CausalModel(
data=df,
treatment=data["treatment_name"],
outcome=data["outcome_name"],
common_causes=data["common_causes_names"],
effect_modifiers=data["effect_modifier_names"])

[ ]:

model.view_model()

[ ]:

from IPython.display import Image, display
display(Image(filename="causal_model.png"))


We get the same causal graph. Now identification and estimation is done as before.

[ ]:

identified_estimand = model.identify_effect(proceed_when_unidentifiable=True)

• Estimation

[ ]:

estimate = model.estimate_effect(identified_estimand,
method_name="backdoor.propensity_score_stratification")
print(estimate)
print("Causal Estimate is " + str(estimate.value))


## Refuting the estimate

Let us now look at ways of refuting the estimate obtained.

### Adding a random common cause variable

[ ]:

res_random=model.refute_estimate(identified_estimand, estimate, method_name="random_common_cause")
print(res_random)


### Adding an unobserved common cause variable

[ ]:

res_unobserved=model.refute_estimate(identified_estimand, estimate, method_name="add_unobserved_common_cause",
confounders_effect_on_treatment="binary_flip", confounders_effect_on_outcome="linear",
effect_strength_on_treatment=0.01, effect_strength_on_outcome=0.02)
print(res_unobserved)


### Replacing treatment with a random (placebo) variable

[ ]:

res_placebo=model.refute_estimate(identified_estimand, estimate,
method_name="placebo_treatment_refuter", placebo_type="permute")
print(res_placebo)


### Removing a random subset of the data

[ ]:

res_subset=model.refute_estimate(identified_estimand, estimate,
method_name="data_subset_refuter", subset_fraction=0.9)
print(res_subset)


As you can see, the propensity score stratification estimator is reasonably robust to refutations. For reproducibility, you can add a parameter “random_seed” to any refutation method, as shown below.

[ ]:

res_subset=model.refute_estimate(identified_estimand, estimate,
method_name="data_subset_refuter", subset_fraction=0.9, random_seed = 1)
print(res_subset)