Inference
Inference is the process that consists in computing new probabilistc information from a Bayesian network and some evidence. aGrUM/pyAgrum mainly focus on the computation of (joint) posterior for some variables of the Bayesian networks given soft or hard evidence that are the form of likelihoods on some variables. Inference is a hard task (NP-complete). aGrUM/pyAgrum implements exact inference but also approximated inference that can converge slowly and (even) not exactly but thant can in many cases be useful for applications.
Exact Inference
Lazy Propagation
Lazy Propagation is the main exact inference for classical Bayesian networks in aGrUM/pyagrum.
- class pyagrum.LazyPropagation(*args)
Class used for Lazy Propagation
- LazyPropagation(bn) -> LazyPropagation
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
Scientific notes
LazyPropagation is the lazy propagation of [1]: a message passing in a junction tree, following the Shafer-Shenoy architecture [2], where the cliques and the messages are kept as sets of factors, multiplied only when a variable has to be summed out. This page describes the junction tree and the messages shared by all the exact inferences of pyAgrum.
The junction tree. It is rebuilt only when the targets or the set of observed variables change. pyAgrum first removes the variables that cannot influence the targets: the barren nodes (neither targets nor observed, with no target or observed descendant) and the nodes found irrelevant to the targets given the evidence by the Bayes-Ball algorithm [3]. The remaining graph is moralized, each joint target is made a clique, the observed variables are removed (their CPTs are reduced to the observed values), and the graph is triangulated. The default triangulation eliminates first the simplicial nodes, then the almost simplicial nodes whose clique does not exceed the largest clique created so far [4], and otherwise the node that creates the clique of smallest weight (the product of the domain sizes of its variables). The junction tree is then turned into a binary join tree [5], and each CPT goes to a clique containing its family.
The messages. With \(\Phi_C\) the set of factors of clique \(C\) and \(S_{ij} = C_i \cap C_j\), the message from \(C_i\) to \(C_j\) is
computed lazily: the variables of \(C_i \setminus S_{ij}\) are summed out one by one, first the one producing the smallest table, each time from the product of the factors where it appears only, so that a message is in general a set of small factors. A variable to be summed out that appears in a single factor and is not observed is summed out of that factor alone (barren variable). Only the messages towards the cliques of the targets are computed (collect phase); a posterior is the product of the factors of the clique and of its incoming messages, marginalized and normalized. A soft evidence is a likelihood vector \(\lambda(x)\) multiplied as one more factor; a hard evidence removes the observed variable, as said above.
Exact queries. evidenceProbability multiplies the masses of the connected components and the constants left by
the evidence, with the irrelevance pruning disabled. mpe replaces the sum by a maximization
[6], all the variables being targets, then reads the most probable configuration clique by
clique (ties are broken by the first value found).
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a set of nodes as a new joint target. |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined joint targets. |
|
Clear all the previously defined marginal targets. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the joint target. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Create a |
|
returns the number of threads used by LazyPropagation during inferences. |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Indicates whether LazyPropagation currently overrides aGrUM’s default number of threads (see method setNumberOfThreads). |
|
Compute the joint mutual information (interaction information) among a set of target variables. |
|
Compute the joint posterior of a set of nodes. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Gives the upper bound on the memory used by the inference (see method setMaxMemory). |
|
Find the Most Probable Explanation (MPE) given the evidence (if any) added into LazyPropagation |
|
Find the Most Probable Explanation (MPE) given the evidence (if any) added into LazyPropagation as well as the log2 of its posterior probability |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Sets an upper bound on the memory used by the inference. |
|
If the argument nb is different from 0, this number of threads will be used during inferences, hence overriding aGrUM’s default number of threads. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
Shafer-Shenoy Inference
- class pyagrum.ShaferShenoyInference(*args)
Class used for Shafer-Shenoy inferences.
- ShaferShenoyInference(bn) -> ShaferShenoyInference
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
Scientific notes
ShaferShenoyInference is the propagation of [2] in a junction tree: each clique sends to
each neighbour the product of its factors and of the messages received from its other neighbours, summed out onto
their separator, without any division. The junction tree (pruning of the barren and irrelevant nodes, triangulation,
binary join tree) and the formula of the messages are those of pyagrum.LazyPropagation.
What differs from pyagrum.LazyPropagation is that nothing is lazy: the CPTs (and the soft evidence) assigned to a
clique are multiplied once into a single table on the whole clique, and each message is a single table on its
separator. The memory used grows with the size of the cliques instead of the size of the factors, but a message
already computed is reused as is. The results are the same (evidenceProbability included); mpe is not
available.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a set of nodes as a new joint target. |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined joint targets. |
|
Clear all the previously defined marginal targets. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the joint target. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Create a |
|
returns the number of threads used by LazyPropagation during inferences. |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Indicates whether LazyPropagation currently overrides aGrUM’s default number of threads (see method setNumberOfThreads). |
|
Compute the joint mutual information (interaction information) among a set of target variables. |
|
Compute the joint posterior of a set of nodes. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Gives the upper bound on the memory used by the inference (see method setMaxMemory). |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Sets an upper bound on the memory used by the inference. |
|
If the argument nb is different from 0, this number of threads will be used during inferences, hence overriding aGrUM’s default number of threads. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
Variable Elimination
- class pyagrum.VariableElimination(*args)
Class used for Variable Elimination inference algorithm.
Warning
Even if this inference has the same API than the other (exact) inferences, its mode of operation is different and is specifically dedicated to the calculation of a single posterior. Any other use (for instance for multiple targets) is possibly inefficient.
- VariableElimination(bn) -> VariableElimination
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
Scientific notes
VariableElimination computes each posterior separately, by summing out the other variables one after the other from the product of the factors where they appear [7][8].
For each query (one target, or one joint target), pyAgrum builds the structure of pyagrum.LazyPropagation for this
target alone: the barren nodes and the nodes irrelevant to the target given the evidence (Bayes-Ball
[3]) are removed, the remaining moral graph is triangulated with the default triangulation, and
the elimination order given by this triangulation is used. The factors are kept as sets, as in
[1], and the messages are only collected towards the clique of the target (no binary join tree, no
distribution phase). Nothing is kept from one query to the next: VariableElimination is well suited to a few
posteriors on a large network, and pyagrum.LazyPropagation to many posteriors under the same evidence. There is
neither mpe nor evidenceProbability.
Nevin Lianwen Zhang and David Poole. A simple approach to Bayesian network computations. In Proceedings of the Tenth Biennial Canadian Artificial Intelligence Conference (AI-94), 171–178. 1994. URL: https://www.cs.ubc.ca/~poole/papers/canai94.pdf.
Rina Dechter. Bucket elimination: a unifying framework for reasoning. Artificial Intelligence, 113(1–2):41–85, 1999. URL: https://doi.org/10.1016/S0004-3702(99)00059-4, doi:10.1016/S0004-3702(99)00059-4.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a set of nodes as a new joint target. |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined joint targets. |
|
Clear all the previously defined marginal targets. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the joint target. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Create a |
|
returns the number of threads used by LazyPropagation during inferences. |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Indicates whether LazyPropagation currently overrides aGrUM’s default number of threads (see method setNumberOfThreads). |
|
Compute the joint mutual information (interaction information) among a set of target variables. |
|
Compute the joint posterior of a set of nodes. |
|
Give the junction tree used to compute the posterior of a node. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Gives the upper bound on the memory used by the inference (see method setMaxMemory). |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Sets an upper bound on the memory used by the inference. |
|
If the argument nb is different from 0, this number of threads will be used during inferences, hence overriding aGrUM’s default number of threads. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
Approximated Inference
Loopy Belief Propagation
- class pyagrum.LoopyBeliefPropagation(bn)
Class used for inferences using loopy belief propagation algorithm.
- LoopyBeliefPropagation(bn) -> LoopyBeliefPropagation
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
- Parameters:
bn (
IBayesNet)
Scientific notes
LoopyBeliefPropagation applies Pearl’s message passing for polytrees [9] to a Bayesian network with loops. With \(\lambda_X(x)\) the evidence on \(X\) (likelihood vector, the indicator of the value for a hard evidence, 1 without evidence), the messages along each arc \(U \to X\) are
each message being normalized, and the posterior is \(P(x \mid e) \propto \pi_X(x)\,\lambda_X(x) \prod_{Z} \lambda_{Z \to X}(x)\). On a polytree it is exact; with loops it is an approximation, often good but with no guarantee of convergence [10].
Choices of pyAgrum. All the messages start uniform, and a first sweep follows a topological order. Then each
iteration visits all the nodes in a random order (drawn from a generator with a fixed seed, so that two runs give the
same result), each node updating at once all its outgoing messages from the latest messages received (asynchronous
updates). The error of an iteration is the largest Kullback-Leibler divergence (in bits) between the former and the
new value of a message, and the iterations stop when it falls below epsilon (default \(10^{-8}\)), when its
relative variation falls below the minimal rate (default \(10^{-10}\)), or after maxIter iterations (default
100).
Judea Pearl. Probabilistic Reasoning in Intelligent Systems: Networks of Plausible Inference. Morgan Kaufmann, 1988. URL: https://doi.org/10.1016/C2009-0-27609-4, doi:10.1016/C2009-0-27609-4.
Kevin P. Murphy, Yair Weiss, and Michael I. Jordan. Loopy belief propagation for approximate inference: an empirical study. In Proceedings of the Fifteenth Conference on Uncertainty in Artificial Intelligence (UAI 1999), 467–475. 1999. URL: https://arxiv.org/abs/1301.6725.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|
Sampling
Gibbs Sampling for BN
- class pyagrum.GibbsSampling(bn)
Class for making Gibbs sampling inference in Bayesian networks.
- GibbsSampling(bn) -> GibbsSampling
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
Notes
The Gibbs chain must start from a configuration compatible with the evidence (with a positive probability). When the Bayesian network contains zeros (deterministic relations), finding such a configuration is a hard combinatorial problem in general, and it is searched heuristically: impossible values are first removed, then a few random configurations are tried and gradually repaired.
If the removal of impossible values proves that the evidence is incompatible with the model,
makeInference()raisespyagrum.IncompatibleEvidence.If no compatible configuration is found,
makeInference()raisespyagrum.OperationNotAllowed. This does not prove that the evidence is impossible: with very rare compatible configurations (e.g. long chains of deterministic constraints), the search may fail and its outcome may depend on the random seed. An exact inference such aspyagrum.LazyPropagationcan check it (evidenceProbability()raisespyagrum.IncompatibleEvidencefor an impossible evidence).
- Parameters:
bn (
IBayesNet)
Scientific notes
GibbsSampling is a Markov chain Monte Carlo method [11], applied to Bayesian networks by [12]: the evidence being fixed, the chain moves from one configuration to the next by drawing again the value of some unobserved variables, each one given the current values of the others. In a Bayesian network, this conditional only depends on the Markov blanket of \(X\) (parents, children and parents of the children):
When this product is null for every value, \(X\) keeps its value.
One step, one sample. Each step draws nbrDrawnVar variables, by default \(1 + \lfloor n/2 \rfloor\) for a
network of \(n\) variables (gibbs.percentDrawnSample = 50%, at most the number of unobserved variables that are
not deterministic, see below), chosen at random with replacement (gibbs.drawnAtRandom) or in turn. The configuration
reached after each step is one sample, of weight 1, for the estimator of pyagrum.WeightedSampling. The first
burnIn steps (300 by default) are discarded, so that the chain forgets its starting configuration. That starting
configuration must have a positive probability: the values made impossible by the evidence are removed, then forward
samples are tried and repaired (see the docstring).
Correlated samples. Two consecutive samples share most of their values: \(N\) samples of the chain carry the information of fewer independent samples. The estimator counts them as \(N\) independent samples, so that its Wilson score intervals are too narrow and the stopping criterion is optimistic.
Deterministic CPTs. A variable whose CPT gives the probability 1 to a value for each configuration of its parents is a function of them: moved alone, it would never change. Such a variable (if not observed) is not drawn: its value is computed from its parents, and the move of a variable draws it jointly with the deterministic variables that depend on it.
Defaults. GibbsSampling has its own stopping thresholds (section gibbs), equal to the ones of the other
samplers: epsilon = 0.01 and minEpsilonRate = \(10^{-5}\). Since the samples are correlated, the precision
reached is lower than the one of independent samples.
Implementation limit. A CPT that is only partly deterministic (some null probabilities, without a probability 1
for each configuration of the parents) may prevent the chain from reaching some configurations of positive
probability from its starting point; the estimate is then biased whatever the number of samples. An exact inference
(pyagrum.LazyPropagation) or pyagrum.WeightedSampling do not have this limit.
Stuart Geman and Donald Geman. Stochastic relaxation, Gibbs distributions, and the Bayesian restoration of images. IEEE Transactions on Pattern Analysis and Machine Intelligence, PAMI-6(6):721–741, 1984. URL: https://doi.org/10.1109/TPAMI.1984.4767596, doi:10.1109/TPAMI.1984.4767596.
Judea Pearl. Evidential reasoning using stochastic simulation of causal models. Artificial Intelligence, 32(2):245–257, 1987. URL: https://doi.org/10.1016/0004-3702(87)90012-9, doi:10.1016/0004-3702(87)90012-9.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Returns the current estimation of the posterior of a node (for instance during the inference, in a listener). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|
Simple Monte Carlo Sampling for BN
- class pyagrum.MonteCarloSampling(bn)
Class used for Monte Carlo sampling inference algorithm.
- MonteCarloSampling(bn) -> MonteCarloSampling
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
Notes
The draws incompatible with the hard evidence are rejected.
makeInference()raisespyagrum.IncompatibleEvidence:before any draw, if the removal of impossible values proves that the evidence is incompatible with the model;
if the number of consecutive rejected draws reaches the configuration key
sampling.maxConsecutiveRejections(read when the inference is created), or if the time limit (pyagrum.MonteCarloSampling.setMaxTime) is reached before any compatible draw. The evidence then has a null or very small probability: an exact inference such aspyagrum.LazyPropagationcan tell (evidenceProbability()raisespyagrum.IncompatibleEvidencefor an impossible evidence).
- Parameters:
bn (
IBayesNet)
Scientific notes
MonteCarloSampling is the probabilistic logic sampling of [13]: each sample is drawn forward,
in a topological order, from the CPTs of the Bayesian network, and a sample that contradicts the hard evidence is
rejected as soon as an observed variable gets another value. The accepted samples are samples of the posterior, all of
weight 1: the estimator is a plain frequency and its size is the number of accepted samples. The estimator and its
stopping criterion (Wilson score interval [14]) are detailed in the notes of
pyagrum.WeightedSampling.
The price of rejection is the probability \(P(e)\) of the evidence: about \(1/P(e)\) draws are needed for one
accepted sample, which makes the method impractical for unlikely evidence (pyagrum.WeightedSampling and
pyagrum.ImportanceSampling never reject a draw because of the evidence, unless it is impossible). After
sampling.maxConsecutiveRejections consecutive rejections (\(10^6\) by default), or when the time limit is
reached before any accepted sample, the evidence is declared of null or too small probability.
Max Henrion. Propagating uncertainty in Bayesian networks by probabilistic logic sampling. In John F. Lemmer and Laveen N. Kanal, editors, Uncertainty in Artificial Intelligence 2 (UAI 1986), volume 5 of Machine Intelligence and Pattern Recognition, pages 149–163. North-Holland, 1988. URL: https://doi.org/10.1016/B978-0-444-70396-5.50019-4, doi:10.1016/B978-0-444-70396-5.50019-4.
Edwin B. Wilson. Probable inference, the law of succession, and statistical inference. Journal of the American Statistical Association, 22(158):209–212, 1927. URL: https://doi.org/10.1080/01621459.1927.10502953, doi:10.1080/01621459.1927.10502953.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Returns the current estimation of the posterior of a node (for instance during the inference, in a listener). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|
Weighted Sampling for BN
- class pyagrum.WeightedSampling(bn)
Class used for Weighted sampling inference algorithm.
- WeightedSampling(bn) -> WeightedSampling
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
Notes
The draws incompatible with the hard evidence are rejected.
makeInference()raisespyagrum.IncompatibleEvidence:before any draw, if the removal of impossible values proves that the evidence is incompatible with the model;
if the number of consecutive rejected draws reaches the configuration key
sampling.maxConsecutiveRejections(read when the inference is created), or if the time limit (pyagrum.WeightedSampling.setMaxTime) is reached before any compatible draw. The evidence then has a null or very small probability: an exact inference such aspyagrum.LazyPropagationcan tell (evidenceProbability()raisespyagrum.IncompatibleEvidencefor an impossible evidence).
- Parameters:
bn (
IBayesNet)
Scientific notes
WeightedSampling is likelihood weighting [15][16]: the observed variables are set to their observed values, the other ones are drawn forward from their CPT, and each sample \(x^{(k)}\) is weighted by the probability \(w_k\) of the evidence given its parents. A sample of null weight (an observed value impossible given the drawn parents) is drawn again instead of being counted, which does not change the estimate. Like all the samplers of pyAgrum, it accepts only hard evidence.
The estimator (shared by all the samplers of pyAgrum). After \(N\) samples, the posterior of a value \(x\) of a variable \(X\) is the weighted frequency
(all the weights are 1 for pyagrum.MonteCarloSampling and pyagrum.GibbsSampling, and the ratio of the
probabilities in the network and in the importance function for pyagrum.ImportanceSampling).
The stopping criterion. Each \(\hat p\) is seen as the parameter of a Bernoulli variable estimated from a sample of size \(n\), and the sampling stops when the largest length, over all the values of all the unobserved variables (targets or not), of the 95% Wilson score intervals [14] (\(z = 1.96\))
is below epsilon (0.01 by default, which asks for about \((z/\varepsilon)^2 \approx 38\,400\) samples when
some \(\hat p\) is close to 1/2), or when the relative variation \(|\ell_t - \ell_{t-1}|/\ell_t\) between two
checks is below minEpsilonRate (\(10^{-5}\)), or when a limit of time or of iterations is reached. The criteria
are checked every periodSize (100) samples. Unlike the Wald interval \(2z\sqrt{\hat p(1-\hat p)/n}\),
\(\ell\) never vanishes: it is \(z^2/(n+z^2)\) when all the samples agree, so that a few identical samples are
not taken for a convergence.
The size of a weighted sample. \(N\) weighted samples do not carry the information of \(N\) samples of the posterior: when a few large weights dominate, the estimate rests on a few samples. The effective sample size of importance sampling, \(N / (1 + \mathrm{Var}(W))\) for weights \(W\) normalized to a mean of 1, comes from the work of Kong and is used in [17]; the size \(n\) is its usual estimate from the sample [18]
which is \(N\) when the weights are equal (whatever their value) and decreases down to 1 when a single weight dominates. It is an approximation, which ignores the function being estimated [18]: the criterion is a heuristic, not a guarantee on the error of each posterior.
With a prior (pyagrum.LoopyWeightedSampling, pyagrum.LoopyImportanceSampling…): the posteriors \(\pi\)
given by a loopy belief propagation count as \(n_v\) virtual samples. The estimate becomes
\((n_v\,\pi + N\,\hat p)/(n_v + N)\), the size \(n = n_v + n_{\text{eff}}\), and the criteria on the precision
(epsilon and minEpsilonRate) are only checked once the real samples outnumber the virtual ones
(\(N \geq n_v\)).
Robert Fung and Kuo-Chu Chang. Weighing and integrating evidence for stochastic simulation in Bayesian networks. In Max Henrion, Ross D. Shachter, Laveen N. Kanal, and John F. Lemmer, editors, Uncertainty in Artificial Intelligence 5 (UAI 1989), volume 10 of Machine Intelligence and Pattern Recognition, pages 209–219. North-Holland, 1990. URL: https://arxiv.org/abs/1304.1504, doi:10.1016/B978-0-444-88738-2.50023-3.
Ross D. Shachter and Mark A. Peot. Simulation approaches to general probabilistic inference on belief networks. In Max Henrion, Ross D. Shachter, Laveen N. Kanal, and John F. Lemmer, editors, Uncertainty in Artificial Intelligence 5 (UAI 1989), volume 10 of Machine Intelligence and Pattern Recognition, pages 221–231. North-Holland, 1990. URL: https://arxiv.org/abs/1304.1526, doi:10.1016/B978-0-444-88738-2.50024-5.
Augustine Kong, Jun S. Liu, and Wing Hung Wong. Sequential imputations and bayesian missing data problems. Journal of the American Statistical Association, 89(425):278–288, 1994. URL: https://doi.org/10.1080/01621459.1994.10476469, doi:10.1080/01621459.1994.10476469.
Víctor Elvira, Luca Martino, and Christian P. Robert. Rethinking the effective sample size. International Statistical Review, 90(3):525–550, 2022. URL: https://arxiv.org/abs/1809.04129, doi:10.1111/insr.12500.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Returns the current estimation of the posterior of a node (for instance during the inference, in a listener). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|
Importance Sampling for BN
- class pyagrum.ImportanceSampling(bn)
Class used for inferences using the Importance Sampling algorithm.
- ImportanceSampling(bn) -> ImportanceSampling
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
Notes
The draws incompatible with the hard evidence are rejected.
makeInference()raisespyagrum.IncompatibleEvidence:before any draw, if the removal of impossible values proves that the evidence is incompatible with the model;
if the number of consecutive rejected draws reaches the configuration key
sampling.maxConsecutiveRejections(read when the inference is created), or if the time limit (pyagrum.ImportanceSampling.setMaxTime) is reached before any compatible draw. The evidence then has a null or very small probability: an exact inference such aspyagrum.LazyPropagationcan tell (evidenceProbability()raisespyagrum.IncompatibleEvidencefor an impossible evidence).
- Parameters:
bn (
IBayesNet)
Scientific notes
ImportanceSampling draws the samples from an importance function \(Q\) and weights each sample by the ratio of its
probabilities in the Bayesian network and in \(Q\) [16]; the estimator and its stopping
criterion, with the effective size of a weighted sample, are detailed in the notes of pyagrum.WeightedSampling.
The importance function. \(Q\) is the Bayesian network where each observed variable \(E\) is fixed to its
value \(e\), both in its own CPT and in the CPTs of its children: the unobserved variables are drawn forward from
their CPTs given the drawn and observed values of their parents. As is, \(Q\) is the importance function of
likelihood weighting, and the weight \(w = \prod_E P(e \mid \mathrm{pa}(E))\) is the one of
pyagrum.WeightedSampling.
The lifting of small probabilities. With \(\delta = \varepsilon / d\), where \(\varepsilon\) is the
epsilon of the stopping criterion (0.01 by default) and \(d\) the largest domain size of the variables, if the
smallest positive parameter of \(Q\) is below \(\delta\), every positive parameter of every CPT of \(Q\)
is raised by \(\delta\) and the CPT is normalized again:
where \(k_u\) is the number of positive values of \(P(\cdot \mid u)\). The weight becomes
Each ratio is at most \(1 + k_u\delta\): the values of tiny prior probability, which the evidence may make likely,
are drawn more often and weighted down, instead of being missed or drawn rarely with a few dominating weights. Since
\(Q\) and \(P\) have the same null parameters, the estimator stays consistent. This is close to the heuristic
initialization of AIS-BN [19], which replaces each probability below a threshold \(\theta\)
(0.04 in its experiments) by \(\theta\), taken from the largest probability of the distribution. pyAgrum differs:
the lifting is additive on all the positive parameters, its threshold follows epsilon (changing epsilon changes
\(Q\)), and \(Q\) is not adapted during the sampling.
Jian Cheng and Marek J. Druzdzel. AIS-BN: an adaptive importance sampling algorithm for evidential reasoning in large Bayesian networks. Journal of Artificial Intelligence Research, 13:155–188, 2000. URL: https://arxiv.org/abs/1106.0253, doi:10.1613/jair.764.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Returns the current estimation of the posterior of a node (for instance during the inference, in a listener). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|
Loopy sampling
Pure Loopy Gibbs Sampling
- class pyagrum.LoopyGibbsSampling(bn)
Class used for inferences using a loopy version of importance sampling.
- LoopyImportanceSampling(bn) -> LoopyImportanceSampling
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
- Parameters:
bn (
IBayesNet)
Scientific notes
LoopyGibbsSampling runs first a loopy belief propagation [9][10] with the same
hard evidence, then the sampling of pyagrum.GibbsSampling [11][12]. The
posteriors \(\pi\) of the loopy belief propagation initialize the estimator as \(n_v\) virtual samples
(virtualLBPSize, 5000 by default): after \(N\) real samples, the estimate is
\((n_v\,\pi + N\,\hat p)/(n_v + N)\). The criteria on the precision (epsilon and minEpsilonRate, Wilson
score interval [14]) are only checked once \(N \geq n_v\), so that at least \(n_v\)
samples are drawn (unless the time or iteration limit stops the sampling first). The estimator and its stopping
criterion are detailed in the notes of pyagrum.WeightedSampling.
The loopy belief propagation is exact on a polytree and approximate otherwise; its error enters the estimate with the
weight \(n_v/(n_v+N)\). It stops after at most 100 iterations (lbp.maxIter), converged or not. It mainly gives a
sensible estimate before the real samples dominate.
With a large epsilon (0.2 for instance), the criterion is met as soon as it is checked
(\(n = n_v + N \geq 2 n_v\)): the sampling draws about \(n_v\) samples, and the result is then an equal mix of
the loopy belief propagation and of the Gibbs chain. With the default epsilon (0.01), the real samples dominate.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Returns the current estimation of the posterior of a node (for instance during the inference, in a listener). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Performs the inference: use |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|
Loopy Monte Carlo Sampling
- class pyagrum.LoopyMonteCarloSampling(bn)
Class used for inferences using a loopy version of importance sampling.
- LoopyImportanceSampling(bn) -> LoopyImportanceSampling
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
- Parameters:
bn (
IBayesNet)
Scientific notes
LoopyMonteCarloSampling runs first a loopy belief propagation [9][10] with the
same hard evidence, then the sampling of pyagrum.MonteCarloSampling [13]. The posteriors
\(\pi\) of the loopy belief propagation initialize the estimator as \(n_v\) virtual samples (virtualLBPSize,
5000 by default): after \(N\) real samples, the estimate is \((n_v\,\pi + N\,\hat p)/(n_v + N)\). The criteria
on the precision (epsilon and minEpsilonRate, Wilson score interval [14]) are only checked
once \(N \geq n_v\), so that at least \(n_v\) samples are drawn (unless the time or iteration limit stops the
sampling first). The estimator and its stopping criterion are detailed in the notes of pyagrum.WeightedSampling.
The loopy belief propagation is exact on a polytree and approximate otherwise; its error enters the estimate with the
weight \(n_v/(n_v+N)\). It stops after at most 100 iterations (lbp.maxIter), converged or not. It mainly gives a
sensible estimate before the real samples dominate.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Returns the current estimation of the posterior of a node (for instance during the inference, in a listener). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Performs the inference: use |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|
Loopy Weighted Sampling
- class pyagrum.LoopyWeightedSampling(bn)
Class used for inferences using a loopy version of importance sampling.
- LoopyImportanceSampling(bn) -> LoopyImportanceSampling
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
- Parameters:
bn (
IBayesNet)
Scientific notes
LoopyWeightedSampling runs first a loopy belief propagation [9][10] with the same
hard evidence, then the sampling of pyagrum.WeightedSampling [15][16]. The
posteriors \(\pi\) of the loopy belief propagation initialize the estimator as \(n_v\) virtual samples
(virtualLBPSize, 5000 by default): after \(N\) real samples, the estimate is
\((n_v\,\pi + N\,\hat p)/(n_v + N)\). The criteria on the precision (epsilon and minEpsilonRate, Wilson
score interval [14]) are only checked once \(N \geq n_v\), so that at least \(n_v\)
samples are drawn (unless the time or iteration limit stops the sampling first). The estimator and its stopping
criterion are detailed in the notes of pyagrum.WeightedSampling.
The loopy belief propagation is exact on a polytree and approximate otherwise; its error enters the estimate with the
weight \(n_v/(n_v+N)\). It stops after at most 100 iterations (lbp.maxIter), converged or not. It mainly gives a
sensible estimate before the real samples dominate.
The share \(n_v/(n_v+N)\) of the prior counts the real samples, not their effective size: when the weights are very unequal, the prior is outweighed faster than the information of the samples grows.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Returns the current estimation of the posterior of a node (for instance during the inference, in a listener). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Performs the inference: use |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|
Loopy Importance Sampling
- class pyagrum.LoopyImportanceSampling(bn)
Class used for inferences using a loopy version of importance sampling.
- LoopyImportanceSampling(bn) -> LoopyImportanceSampling
- Parameters:
bn (
pyagrum.BayesNet) – a Bayesian network
- Parameters:
bn (
IBayesNet)
Scientific notes
LoopyImportanceSampling runs first a loopy belief propagation [9][10] with the
same hard evidence, then the sampling of pyagrum.ImportanceSampling [16]. The
posteriors \(\pi\) of the loopy belief propagation initialize the estimator as \(n_v\) virtual samples
(virtualLBPSize, 5000 by default): after \(N\) real samples, the estimate is
\((n_v\,\pi + N\,\hat p)/(n_v + N)\). The criteria on the precision (epsilon and minEpsilonRate, Wilson
score interval [14]) are only checked once \(N \geq n_v\), so that at least \(n_v\)
samples are drawn (unless the time or iteration limit stops the sampling first). The estimator and its stopping
criterion are detailed in the notes of pyagrum.WeightedSampling.
The loopy belief propagation is exact on a polytree and approximate otherwise; its error enters the estimate with the
weight \(n_v/(n_v+N)\). It stops after at most 100 iterations (lbp.maxIter), converged or not. It mainly gives a
sensible estimate before the real samples dominate.
The share \(n_v/(n_v+N)\) of the prior counts the real samples, not their effective size: when the weights are very unequal, the prior is outweighed faster than the information of the samples grows.
Methods
Add all the nodes as targets. |
|
Adds a new evidence on a node (might be soft or hard). |
|
Add a marginal target to the list of targets. |
|
Change the value of an already existing evidence on a node (might be soft or hard). |
|
Returns the current estimation of the posterior of a node (for instance during the inference, in a listener). |
|
Disable epsilon as a stopping criterion. |
|
Disable max iterations as a stopping criterion. |
|
Disable max time as a stopping criterion. |
|
Disable a min epsilon rate as a stopping criterion. |
|
Enable epsilon as a stopping criterion. |
|
Enable max iterations as a stopping criterion. |
|
Enable max time as a stopping criterion. |
|
Enable a min epsilon rate as a stopping criterion. |
|
Removes all the evidence entered into the network. |
|
Clear all previously defined targets (marginal and joint targets). |
|
Remove the evidence, if any, corresponding to the node Id or name. |
|
Remove, if existing, the marginal target. |
|
Create a |
|
Indicates whether a node has received evidence or, without argument, whether at least one node has. |
|
The error at the start of each period of the last run: one value every |
|
Tells the inference that the values of tensors of its model changed in place. |
|
Perform the heavy computations needed to compute the targets’ posteriors |
|
Performs the inference: use |
|
Computes and returns the posterior of a node. |
|
Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces. |
|
Remove all the targets and add the ones in parameter. |
|
Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence). |
|