<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 load all required packages.<jupyter_code>import numpy as np
import pandas as pd

import dowhy
from dowhy import CausalModel
import dowhy.datasets 

# Avoid printing dataconversion warnings from sklearn
import warnings
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)

# Config dict to set the logging level
import logging.config
DEFAULT_LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'loggers': {
        '': {
            'level': 'WARN',
        },
    }
}

logging.config.dictConfig(DEFAULT_LOGGING)<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=20000, 
        treatment_is_binary=True,
        num_discrete_common_causes=1)
df = data["df"]
print(df.head())
print(data["dot_graph"])
print("\n")
print(data["gml_graph"])
data['df']<jupyter_output><empty_output><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.To create the causal graph for your dataset, you can use a tool like [DAGitty](http://dagitty.net/dags.html) that provides a GUI to construct the graph. You can export the graph string that it generates. The graph string is very close to the DOT format: just rename `dag` to `digraph`, remove newlines and add a semicolon after every line, to convert it to the DOT format and input to DoWhy.<jupyter_code># With graph
model=CausalModel(
        data = df,
        treatment=data["treatment_name"],
        outcome=data["outcome_name"],
        graph=data["gml_graph"]
        )
data["treatment_name"]<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(proceed_when_unidentifiable=True)
print(identified_estimand)<jupyter_output>Estimand type: nonparametric-ate

### Estimand : 1
Estimand name: backdoor
Estimand expression:
  d                                    
─────(Expectation(y|W1,W2,W0,W3,W4,X0))
d[v₀]                                  
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W2,W0,W3,W4,X0,U) = P(y|v0,W1,W2,W0,W3,W4,X0)

### Estimand : 2
Estimand name: iv
Estimand expression:
Expectation(Derivative(y, [Z1, Z0])*Derivative([v0], [Z1, Z0])**(-1))
Estimand assumption 1, As-if-random: If U→→y then ¬(U →→{Z1,Z0})
Estimand assumption 2, Exclusion: If we remove {Z1,Z0}→{v0}, then ¬({Z1,Z0}→y)

### Estimand : 3
Estimand name: frontdoor
No such variable found!<jupyter_text>Note the parameter flag *proceed\_when\_unidentifiable*. It needs to be set to *True* to convey the assumption that we are ignoring any unobserved confounding. The default behavior is to prompt the user to double-check that the unobserved confounders can be ignored.  * 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>*** Causal Estimate ***

## Identified estimand
Estimand type: nonparametric-ate

### Estimand : 1
Estimand name: backdoor
Estimand expression:
  d                                    
─────(Expectation(y|W1,W2,W0,W3,W4,X0))
d[v₀]                                  
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W2,W0,W3,W4,X0,U) = P(y|v0,W1,W2,W0,W3,W4,X0)

## Realized estimand
b: y~v0+W1+W2+W0+W3+W4+X0
Target units: ate

## Estimate
Mean value: 12.22245148106945

Causal Estimate is 12.22245148106945<jupyter_text>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)`.<jupyter_code># 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))<jupyter_output>*** Causal Estimate ***

## Identified estimand
Estimand type: nonparametric-ate

### Estimand : 1
Estimand name: backdoor
Estimand expression:
  d                                    
─────(Expectation(y|W1,W2,W0,W3,W4,X0))
d[v₀]                                  
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W2,W0,W3,W4,X0,U) = P(y|v0,W1,W2,W0,W3,W4,X0)

## Realized estimand
b: y~v0+W1+W2+W0+W3+W4+X0
Target units: atc

## Estimate
Mean value: 12.085030088973811

Causal Estimate is 12.085030088973811<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><empty_output><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>*** Causal Estimate ***

## Identified estimand
Estimand type: nonparametric-ate

### Estimand : 1
Estimand name: backdoor
Estimand expression:
  d                                 
─────(Expectation(y|W0,W3,W1,W2,W4))
d[v₀]                               
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W3,W1,W2,W4,U) = P(y|v0,W0,W3,W1,W2,W4)

## Realized estimand
b: y~v0+W0+W3+W1+W2+W4
Target units: ate

## Estimate
Mean value: 9.60353896239299

Causal Estimate is 9.60353896239299<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>Refute: Add a Random Common Cause
Estimated effect:9.60353896239299
New effect:9.602995259163794<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>Refute: Add an Unobserved Common Cause
Estimated effect:9.60353896239299
New effect:7.591550789699005<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>Refute: Use a Placebo Treatment
Estimated effect:9.60353896239299
New effect:0.005166426876598622
p value:0.47<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>Refute: Use a subset of data
Estimated effect:9.60353896239299
New effect:9.6152898407909
p value:0.42<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>Refute: Use a subset of data
Estimated effect:9.60353896239299
New effect:9.618271557173077
p value:0.33
StarcoderdataJupyterStructuredCleanDedup