Exemple #1
0
# Compute conditional independencies from a directed graphical model

# Uses this library
# https://github.com/ijmbarr/causalgraphicalmodels

# Code is based on
# https://fehiepsi.github.io/rethinking-numpyro/06-the-haunted-dag-and-the-causal-terror.html

from causalgraphicalmodels import CausalGraphicalModel

dag = CausalGraphicalModel(
    nodes=["X", "Y", "C", "U", "B", "A"],
    edges=[
        ("X", "Y"),
        ("U", "X"),
        ("A", "U"),
        ("A", "C"),
        ("C", "Y"),
        ("U", "B"),
        ("C", "B"),
    ],
)

all_independencies = dag.get_all_independence_relationships()
print(all_independencies)
print('\n')
Exemple #2
0
"""
Treatment appears to have negligible effect even though βF posterior indicates fungus impacts
growth.
The problem is that fungus is a consequence of treatment; i.e. fungus is a post-treatment variable.
The model asked the question "Once we know fungus is present does treatment matter?" ⇒ No.
The next model ignores the fungus variable
"""

with pm.Model() as m8:
    σ = pm.Exponential('σ', 1)
    α = pm.Lognormal('α', 0, 0.2)
    βT = pm.Normal('βT', 0, 0.5)
    p = α + βT * d.treatment.values
    μ = d.h0.values * p
    h1 = pm.Normal('h1', mu=μ, sd=σ, observed=d.h1.values)
    trc8 = pm.sample(tune=1000)

pm.summary(trc8)
"""
Now the treatment effect is plain to see. Note that:
1. It makes sense to control for pre-treatment differences such as initial height, h0, here.
2. Including post-treatment variables can mask the treatment itself.
3. Note that model m7 is still useful to identify the causal mechanism!
"""
plant_dag = CausalGraphicalModel(nodes=['H0', 'H1', 'T', 'F'],
                                 edges=[('H0', 'H1'), ('T', 'F'), ('F', 'H1')])
plant_dag.draw()
plant_dag.is_d_separated('T', 'H1')
plant_dag.is_d_separated('T', 'H1', 'F')
plant_dag.get_all_independence_relationships()