Causal computation in pyAgrum
Causal Inference (a.k.a. do-calculus)
The main entry point for causal inference is pyagrum.causalImpact(), which computes the
causal effect of an intervention \(do(X=x)\) on a target variable \(Y\) within a
pyagrum.CausalModel, using do-calculus identification.
Identify and evaluate the causal effect of do(doing) on on, optionally conditioning on knowing. |
- class pyagrum.CausalImpact(cm, *, on, doing, knowing=None)
Represents the result of a causal identification query P(on | do(doing), knowing).
CausalImpact encodes the identified causal formula (when the effect is identifiable) as an expression tree that can be evaluated numerically. It also records the identification method used and an explanation string.
The identification procedure tries the following strategies in order: d-separation (no effect), backdoor adjustment, frontdoor adjustment, and general do-calculus (ID algorithm).
Notes
You may prefer to use the high-level function
pyagrum.causalImpact()instead of constructing a CausalImpact object directly.- CausalImpact(cm, *, on, doing, knowing=None) -> CausalImpact
- Parameters:
cm (
pyagrum.CausalModel) – the causal model.on (str or set of str) – target variable(s) of the query. A single string is automatically converted to a one-element set. Keyword-only.
doing (str or set of str) – intervened variable(s) (the do-operator applies to these). A single string is automatically converted to a one-element set. Keyword-only.
knowing (str or set of str, optional) – observed variable(s) to condition on. A single string is automatically converted to a one-element set. Default is empty. Keyword-only.
Example
import pyagrum as gum
bn = gum.fastBN("Z->X->Y;Z->Y")
cm = gum.CausalModel(bn)
ci = gum.CausalImpact(cm, on="Y", doing="X")
ci.isIdentified()
# True
ci.explanation()
# "backdoor ['Z'] found."
ci.toLatex()
# 'P\\left(Y \\mid \\text{do}(X)\\right) = \\sum_{Z}{P\\left(Y\\mid X,Z\\right) \\cdot P\\left(Z\\right)}'
Scientific notes
CausalImpact identifies the distribution \(P(Y \mid do(X), Z)\) in a causal model (pyagrum.CausalModel), that
is, writes it as a formula of the observational distribution \(P\), then evaluates the formula, each of its terms
being computed by exact inference in the observational Bayesian network. The methods are tried in this order.
For a single cause, a single effect and no \(Z\): the back-door adjustment with the set \(W\) given by
pyagrum.CausalModel.backDoor(seepyagrum.DoorCriteriafor the criteria and the choice of the set), then the front-door adjustment with a non-empty set of mediators \(M\) [1]:\[P(y \mid do(x)) = \sum_w P(y \mid x, w)\,P(w), \qquad P(y \mid do(x)) = \sum_m P(m \mid x) \sum_{x'} P(y \mid x', m)\,P(x').\]If \(Y\) and \(X\) are d-separated by \(Z\) in the causal DAG without the arcs into \(X(Z)\), the variables of \(X\) which are not ancestors of \(Z\) (third rule of the do-calculus), there is no causal effect and the answer is \(P(Y \mid Z)\).
Otherwise, the general algorithms of Shpitser and Pearl. ID [2] handles \(P(Y \mid do(X))\): it restricts the model to the ancestors of \(Y\), adds to \(X\) the variables without effect on \(Y\), and factorizes the query along the c-components [3] (two observed variables are in the same c-component when they are linked by a chain of shared latent parents). IDC [4] handles \(Z \neq \emptyset\): a variable \(z \in Z\) such that \(Y\) and \(z\) are d-separated by \(X \cup Z \setminus \{z\}\) in the graph without the arcs into \(X\) and out of \(z\) is moved into the intervention (second rule of the do-calculus), then
\[P(y \mid do(x), z) = \frac{P(y, z \mid do(x))}{P(z \mid do(x))},\]both terms being computed by ID.
ID and IDC are complete: when they fail, the effect is not identifiable from \(P\) in this causal DAG
[2][4]. ID then finds a hedge, a pair of
nested c-forests which witnesses the non-identifiability. The CausalImpact is not identified (isIdentified() is false
and eval() raises an exception), pyagrum.causalImpact returns no tensor, and the explanation names the
c-components of the hedge. The formula is returned as built by the method that succeeded, without simplification.
Methods
Return the causal model associated with this query. |
|
Return the NodeIds of the intervened variables. |
|
Return the names of the intervened variables. |
|
Evaluate the identified causal formula and return the result as a tensor. |
|
Return a human-readable explanation of the identification result. |
|
Return the names of all the variables used by the identified formula: the variables of the query appearing in the formula and the other ones it needs (adjustment set, mediators, summed-out variables). |
|
Return True if the causal effect was successfully identified. |
|
Return the NodeIds of the observed variables. |
|
Return the names of the observed variables. |
|
Return a LaTeX string for the original causal query before identification. |
|
Return the NodeIds of the target variables. |
|
Return the names of the target variables. |
|
Print the AST of a CausalImpact function in a human readable way. |
|
Return the identified causal formula as a JSON-serialisable dictionary. |
|
Return a LaTeX string representation of the causal impact formula. |
|
Return a string representation of the identified causal formula. |
Counterfactual reasoning
Compute a counterfactual distribution in the twin network of Balke and Pearl. |
|
Build the twin network of Balke and Pearl for a counterfactual query. |
- class pyagrum.Counterfactual(cm, on, whatif, profile=None, values=None)
Computes a counterfactual distribution in the twin network of Balke and Pearl.
A counterfactual query asks: ‘Given that we observed profile, what would on have been if whatif had been set to the values in values?’
The twin network (
pyagrum.counterfactualModel) contains the real world and a copyV*of the whatif variables and of their descendants (the counterfactual world), both worlds sharing the other variables, in particular the parentless ones. The counterfactual distribution is the posterior of the copies of on given the profile (observed in the real world) and the values of the copies of whatif: the abduction, action and prediction steps of Pearl are done by a single exact inference, which keeps the dependencies created by the profile between the shared variables.Notes
Prefer using the high-level function
pyagrum.counterfactual()instead of constructing a Counterfactual object directly.A causal model with latent variables is refused (
pyagrum.InvalidArgument): their distributions, needed for the abduction, are unknown.- Counterfactual(cm, on, whatif, profile=None, values=None) -> Counterfactual
- Parameters:
cm (
pyagrum.CausalModel) – the causal model.on (int | str | set[int | str]) – target variables of the counterfactual query.
whatif (int | str | set[int | str]) – variables whose values are changed in the counterfactual scenario.
profile (dict of str → str | int) – the factual observation, given as
{variable_name: value}, a value being a label (str) or the index of a label (int), as for the evidence. Default is empty.values (dict of str → str | int) – counterfactual values for the whatif variables, given as
{variable_name: value}(label or index). If omitted, the full joint distribution over all whatif values is returned.
Example
import pyagrum as gum
bn = gum.fastBN("X->Y->Z")
bn.cpt("X").fillWith([0.4, 0.6])
bn.cpt("Y").fillWith([0.9, 0.1, 0.2, 0.8])
bn.cpt("Z").fillWith([0.7, 0.3, 0.1, 0.9])
cm = gum.CausalModel(bn)
# Y=1 was observed: what would Z have been if X had been 0 ?
cf = gum.Counterfactual(cm, {"Z"}, {"X"}, {"Y": "1"}, {"X": "0"})
print(cf.value())
#
# Z │
# 0 │1 │
# ─────────│─────────│
# 0.6400 │ 0.3600 │
Scientific notes
Counterfactual answers the question “given that profile \(e\) was observed, what would the distribution of
on \(Y\) have been, had whatif \(X\) been set to \(x'\)?”, written \(P(Y_{x'} \mid e)\). It
follows the structural account of counterfactuals [5] (Section 7.1), popularized in
[6] (chapter 8), the parentless observed variables of the model playing the role of the exogenous
variables \(U\). Its three steps (abduction of \(U\) given \(e\), action \(do(X = x')\), prediction of
\(Y\)) are done at once in the twin network of [7] (counterfactualModel):
the real world is the observational Bayesian network;
the counterfactual world is made of a copy \(V^*\) of each variable of \(X\) and of each of their descendants: \(X^*\) has no parent, any other \(V^*\) has the conditional probability table of \(V\), its parents being the copies of the parents of \(V\) when they exist, the parents themselves otherwise;
the other variables, in particular \(U\), are shared by both worlds.
With \(e\) observed in the real world, the exact inference of the twin network gives
where \(P(u \mid e)\) is the joint posterior of the shared variables: the dependence created by the evidence between them is kept. \(X^*\) has no parent and no observed descendant, hence is independent of \(e\); the joint posterior of \((Y^*, X^*)\) divided by the prior of \(X^*\) gives the result for every \(x'\).
Without values, the result is a tensor over \(Y\) and the values of whatif; values selects the
counterfactual values. A causal model with latent variables is refused (InvalidArgument): their distributions are
unknown.
Implementation limit. The variables with parents keep their conditional probability tables, the same in both worlds: the result is the counterfactual of the structural model only when every variable with parents is a deterministic function of them, all the uncertainty being carried by the parentless variables.
Judea Pearl. Causality: Models, Reasoning, and Inference. Cambridge University Press, 2 edition, 2009. URL: https://bayes.cs.ucla.edu/BOOK-2K/, doi:10.1017/CBO9780511803161.
Judea Pearl and Dana Mackenzie. The Book of Why: The New Science of Cause and Effect. Basic Books, 2018. ISBN 978-0-465-09760-9. URL: https://bayes.cs.ucla.edu/WHY/.
Alexander Balke and Judea Pearl. Probabilistic evaluation of counterfactual queries. In Proceedings of the Twelfth National Conference on Artificial Intelligence (AAAI-94), 230–237. AAAI Press, 1994. URL: https://dblp.org/rec/conf/aaai/BalkeP94.
Methods
Return the name of the copy of a variable in the twin network. |
|
Build the twin network of Balke and Pearl (see |
|
Return the causal impact P(on* | do(whatif*), profile) in the twin network. |
|
Return the names of the target variables. |
|
Return the original causal model. |
|
Return the factual evidence used for abduction. |
|
Compute the counterfactual distribution by inference in the twin network. |
|
Return a string description of the counterfactual query and its result. |
|
Return the twin network of Balke and Pearl used for the computation. |
|
Return the counterfactual distribution as a tensor. |
|
Return the counterfactual assignments for the whatif variables. |
|
Return the names of the intervened variables. |
References of the members
Alexander Balke and Judea Pearl. Probabilistic evaluation of counterfactual queries. In Proceedings of the Twelfth National Conference on Artificial Intelligence (AAAI-94), 230–237. AAAI Press, 1994. URL: https://dblp.org/rec/conf/aaai/BalkeP94.