Asking questions¶
What a variable is worth, given everything or given part of it. Nothing here is approximate.
The calls¶
| Call | What it does |
|---|---|
variable.posterior(observations=None, engine=None) |
P(this | observations). Returns a Distribution. |
graph.marginals(observations=None, engine=None) |
Every variable at once, for about the cost of one posterior(). |
variable.observe(state) |
Record an observation on the graph. None means nobody looked, which is a third state and not a synonym for false. |
pf.eliminate.cost(graph, query=None, observations=None) |
What a query would cost, as the size of the largest factor, answered before paying it. |
An observations dict overrides what is recorded, for one query, without
disturbing the graph. {variable: None} un-observes one thing and leaves the
rest, which is the cheap way to ask what one witness was worth.
Explaining away, which is the reason to keep a graph¶
import probability_flow as pf
g = pf.CausalGraph("Why is the sidewalk wet?")
rain = g.add_variable("It rained last night")
sprinkler = g.add_variable("The sprinkler ran")
wet = g.add_variable("The sidewalk is wet")
rain.set_prior(0.2)
sprinkler.set_prior(0.4)
rain.causes(wet)
sprinkler.causes(wet)
wet.set_cpd(pf.CPT(causes=[rain, sprinkler], table=[[0.01, 0.90],
[0.90, 0.99]]))
float(sprinkler.posterior({wet: True})) # 0.765
float(sprinkler.posterior({wet: True, rain: True})) # 0.4231
A wet sidewalk makes the sprinkler likely. Learning that it rained pulls the sprinkler back down, because the rain already accounts for the water. Nothing connects the two causes directly, and the amber outline marks what was observed rather than inferred.
Virtual evidence¶
A virtual-evidence node hangs off a variable and carries the probability of the observation if the variable is true and if it is false.
forecast = rain.add_evidence("the forecast", p_if=0.8, p_if_not=0.3)
float(wet.posterior({forecast: True}))
Observing one does not cut the path through its parent. It reweights the
parent rather than fixing it, so evidence still flows upward past it. A variable
carries at most one, reachable afterwards as rain.evidence. It is a single
node and not a collection, so there is nothing to subscript.
The three engines¶
All exact, and chosen for you.
| Engine | When it runs |
|---|---|
| variable elimination | posterior(), one query |
| junction tree | marginals(), every variable at once |
| enumeration | never automatically |
Enumeration sums the whole joint. It is the reference the other two are tested against, and it is never selected for you because it is both the slowest and, measurably, the least accurate.
The junction tree is Shafer-Shenoy, which propagates without dividing, so a
structural zero stays a zero rather than becoming a nan on the way out.
pf.eliminate.cost(graph) answers what a query would cost before you pay it, as
the size of the largest factor the elimination would build. pf.engines carries
the names and the per-graph ceilings.