<jupyter_start><jupyter_text>Getting started with DoWhy: A simple exampleThis 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.<jupyter_code>import os, sys
sys.path.append(os.path.abspath("../../../"))<jupyter_output><empty_output><jupyter_text>Let's check the python version.<jupyter_code>print(sys.version)
import numpy as np
import pandas as pd

import dowhy
from dowhy import CausalModel
import dowhy.datasets<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>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)
df = data["df"]
print(df.head())
print(data["dot_graph"])
print("\n")
print(data["gml_graph"])<jupyter_output>X0   Z0        Z1        W0        W1        W2        W3        W4  \
0 -1.043320  0.0  0.523430 -1.390494  0.499882  2.059895  1.275582 -0.801243   
1  0.277130  1.0  0.657054 -0.703268  0.181127  1.979497  1.685872 -1.274490   
2  0.355053  0.0  0.495130 -0.240308 -0.262587 -1.507041 -0.894224 -0.577460   
3 -1.740237  1.0  0.664943 -0.255855 -0.857088  0.506427 -0.091888 -1.859506   
4  0.132229  0.0  0.451824 -1.711469 -0.702885  0.734297  1.056272 -0.987051   

       v          y  
0   True   5.927543  
1   True   8.147414  
2  False  -7.564643  
3  False -15.067172  
4  False -12.062976  
digraph { v ->y; U[label="Unobserved Confounders"]; U->v; U->y;W0-> v; W1-> v; W2-> v; W3-> v; W4-> v;W0-> y; W1-> y; W2-> y; W3-> y; W4-> y;Z0-> v; Z1-> v;X0-> y;}


graph[directed 1node[ id "v" label "v"]node[ id "y" label "y"]node[ id "Unobserved Confounders" label "Unobserved Confounders"]edge[source "v" target "y"]edge[source "Unobserved Confounders" target "v"]edge[source "Unobs[...]<jupyter_text>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.<jupyter_code># 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"))<jupyter_output><empty_output><jupyter_text>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<jupyter_code>identified_estimand = model.identify_effect()
print(identified_estimand)<jupyter_output>INFO:dowhy.causal_identifier:Common causes of treatment and outcome:['W3', 'Unobserved Confounders', 'W2', 'W0', 'W4', 'W1']
WARNING:dowhy.causal_identifier:There are unobserved common causes. Causal effect cannot be identified.<jupyter_text>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.<jupyter_code>identified_estimand = model.identify_effect(proceed_when_unidentifiable=True)
print(identified_estimand)<jupyter_output>INFO:dowhy.causal_identifier:Common causes of treatment and outcome:['W3', 'Unobserved Confounders', 'W2', 'W0', 'W4', 'W1']
WARNING:dowhy.causal_identifier:There are unobserved common causes. Causal effect cannot be identified.
INFO:dowhy.causal_identifier:Continuing by ignoring these unobserved confounders because proceed_when_unidentifiable flag is True.
INFO:dowhy.causal_identifier:Instrumental variables for treatment and outcome:['Z1', 'Z0']<jupyter_text>* Estimation<jupyter_code>causal_estimate = model.estimate_effect(identified_estimand,
        method_name="backdoor.propensity_score_stratification")
print(causal_estimate)
print("Causal Estimate is " + str(causal_estimate.value))<jupyter_output>INFO:dowhy.causal_estimator:INFO: Using Propensity Score Stratification Estimator
INFO:dowhy.causal_estimator:b: y~v+W3+W2+W0+W4+W1
/usr/local/lib/python3.5/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)<jupyter_text>Interface 2: Specify common causes and instruments<jupyter_code># 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"))<jupyter_output><empty_output><jupyter_text>We get the same causal graph. Now identification and estimation is done as before.<jupyter_code>identified_estimand = model.identify_effect(proceed_when_unidentifiable=True)<jupyter_output>INFO:dowhy.causal_identifier:Common causes of treatment and outcome:['W3', 'W2', 'W0', 'W4', 'W1', 'U']
WARNING:dowhy.causal_identifier:There are unobserved common causes. Causal effect cannot be identified.
INFO:dowhy.causal_identifier:Continuing by ignoring these unobserved confounders because proceed_when_unidentifiable flag is True.
INFO:dowhy.causal_identifier:Instrumental variables for treatment and outcome:[]<jupyter_text>* Estimation<jupyter_code>estimate = model.estimate_effect(identified_estimand,
                                 method_name="backdoor.propensity_score_stratification")         
print(estimate)
print("Causal Estimate is " + str(estimate.value))<jupyter_output>INFO:dowhy.causal_estimator:INFO: Using Propensity Score Stratification Estimator
INFO:dowhy.causal_estimator:b: y~v+W3+W2+W0+W4+W1
/usr/local/lib/python3.5/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)<jupyter_text>Refuting the estimateLet us now look at ways of refuting the estimate obtained.  Adding a random common cause variable<jupyter_code>res_random=model.refute_estimate(identified_estimand, estimate, method_name="random_common_cause")
print(res_random)<jupyter_output>INFO:dowhy.causal_estimator:INFO: Using Propensity Score Stratification Estimator
INFO:dowhy.causal_estimator:b: y~v+W3+W2+W0+W4+W1+w_random
/usr/local/lib/python3.5/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)<jupyter_text>Adding an unobserved common cause variable<jupyter_code>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)<jupyter_output>INFO:dowhy.causal_estimator:INFO: Using Propensity Score Stratification Estimator
INFO:dowhy.causal_estimator:b: y~v+W3+W2+W0+W4+W1
/usr/local/lib/python3.5/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)<jupyter_text>Replacing treatment with a random (placebo) variable<jupyter_code>res_placebo=model.refute_estimate(identified_estimand, estimate,
        method_name="placebo_treatment_refuter", placebo_type="permute")
print(res_placebo)<jupyter_output>INFO:dowhy.causal_estimator:INFO: Using Propensity Score Stratification Estimator
INFO:dowhy.causal_estimator:b: y~placebo+W3+W2+W0+W4+W1
/usr/local/lib/python3.5/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)<jupyter_text>Removing a random subset of the data<jupyter_code>res_subset=model.refute_estimate(identified_estimand, estimate,
        method_name="data_subset_refuter", subset_fraction=0.9)
print(res_subset)<jupyter_output>INFO:dowhy.causal_estimator:INFO: Using Propensity Score Stratification Estimator
INFO:dowhy.causal_estimator:b: y~v+W3+W2+W0+W4+W1
/usr/local/lib/python3.5/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)<jupyter_text>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.<jupyter_code>res_subset=model.refute_estimate(identified_estimand, estimate,
        method_name="data_subset_refuter", subset_fraction=0.9, random_seed = 1)
print(res_subset)<jupyter_output>INFO:dowhy.causal_estimator:INFO: Using Propensity Score Stratification Estimator
INFO:dowhy.causal_estimator:b: y~v+W3+W2+W0+W4+W1
/usr/local/lib/python3.5/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
{'fraction_non_alphanumeric': 0.09326726901777907, 'fraction_numerical': 0.04420479937821821, 'mean_word_length': 4.988365328679465, 'pattern_counts': {'":': 0, '<': 50, '<?xml version=': 0, '>': 66, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '581272', 'license': 'MIT', 'n_tokens_mistral': 3685, 'n_tokens_neox': 3334, 'n_words': 845, 'path': 'docs/source/example_notebooks/dowhy_simple_example.ipynb', 'repo_name': 'Lnk2past/dowhy', 'size': '10293'}