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:

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

\[\Psi_{i\to j} = \sum_{C_i \setminus S_{ij}} \;\prod_{\phi \in \Phi_{C_i} \cup \bigcup_{k \neq j} \Psi_{k\to i}} \phi ,\]

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

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addJointTarget()

Add a set of nodes as a new joint target.

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllJointTargets()

Clear all previously defined joint targets.

eraseAllMarginalTargets()

Clear all the previously defined marginal targets.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseJointTarget()

Remove, if existing, the joint target.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

evidenceJointImpact()

Create a pyagrum.Tensor for P(joint targets|evs) (for all instanciation of targets and evs)

evidenceProbability()

getNumberOfThreads()

returns the number of threads used by LazyPropagation during inferences.

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isGumNumberOfThreadsOverriden()

Indicates whether LazyPropagation currently overrides aGrUM’s default number of threads (see method setNumberOfThreads).

isJointTarget()

isTarget()

joinTree()

jointMutualInformation()

Compute the joint mutual information (interaction information) among a set of target variables.

jointPosterior()

Compute the joint posterior of a set of nodes.

jointTargets()

junctionTree()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

maxMemory()

Gives the upper bound on the memory used by the inference (see method setMaxMemory).

mpe()

Find the Most Probable Explanation (MPE) given the evidence (if any) added into LazyPropagation

mpeLog2Posterior()

Find the Most Probable Explanation (MPE) given the evidence (if any) added into LazyPropagation as well as the log2 of its posterior probability

nbrEvidence()

nbrHardEvidence()

nbrJointTargets()

nbrSoftEvidence()

nbrTargets()

posterior()

Computes and returns the posterior of a node.

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxMemory()

Sets an upper bound on the memory used by the inference.

setNumberOfThreads()

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.

setTargets()

Remove all the targets and add the ones in parameter.

softEvidenceNodes()

targets()

updateEvidence()

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:

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

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addJointTarget()

Add a set of nodes as a new joint target.

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllJointTargets()

Clear all previously defined joint targets.

eraseAllMarginalTargets()

Clear all the previously defined marginal targets.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseJointTarget()

Remove, if existing, the joint target.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

evidenceJointImpact()

Create a pyagrum.Tensor for P(joint targets|evs) (for all instanciation of targets and evs)

evidenceProbability()

getNumberOfThreads()

returns the number of threads used by LazyPropagation during inferences.

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isGumNumberOfThreadsOverriden()

Indicates whether LazyPropagation currently overrides aGrUM’s default number of threads (see method setNumberOfThreads).

isJointTarget()

isTarget()

joinTree()

jointMutualInformation()

Compute the joint mutual information (interaction information) among a set of target variables.

jointPosterior()

Compute the joint posterior of a set of nodes.

jointTargets()

junctionTree()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

maxMemory()

Gives the upper bound on the memory used by the inference (see method setMaxMemory).

nbrEvidence()

nbrHardEvidence()

nbrJointTargets()

nbrSoftEvidence()

nbrTargets()

posterior()

Computes and returns the posterior of a node.

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxMemory()

Sets an upper bound on the memory used by the inference.

setNumberOfThreads()

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.

setTargets()

Remove all the targets and add the ones in parameter.

softEvidenceNodes()

targets()

updateEvidence()

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:

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.

Methods

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addJointTarget()

Add a set of nodes as a new joint target.

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllJointTargets()

Clear all previously defined joint targets.

eraseAllMarginalTargets()

Clear all the previously defined marginal targets.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseJointTarget()

Remove, if existing, the joint target.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

evidenceJointImpact()

Create a pyagrum.Tensor for P(joint targets|evs) (for all instanciation of targets and evs)

getNumberOfThreads()

returns the number of threads used by LazyPropagation during inferences.

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isGumNumberOfThreadsOverriden()

Indicates whether LazyPropagation currently overrides aGrUM’s default number of threads (see method setNumberOfThreads).

isJointTarget()

isTarget()

jointMutualInformation()

Compute the joint mutual information (interaction information) among a set of target variables.

jointPosterior()

Compute the joint posterior of a set of nodes.

jointTargets()

junctionTree()

Give the junction tree used to compute the posterior of a node.

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

maxMemory()

Gives the upper bound on the memory used by the inference (see method setMaxMemory).

nbrEvidence()

nbrHardEvidence()

nbrJointTargets()

nbrSoftEvidence()

nbrTargets()

posterior()

Computes and returns the posterior of a node.

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxMemory()

Sets an upper bound on the memory used by the inference.

setNumberOfThreads()

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.

setTargets()

Remove all the targets and add the ones in parameter.

softEvidenceNodes()

targets()

updateEvidence()

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:
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

\[\pi_X(x) = \sum_{u} P(x \mid u) \prod_{U_i \in \mathrm{pa}(X)} \pi_{U_i \to X}(u_i), \qquad \pi_{X \to Y}(x) \propto \pi_X(x)\, \lambda_X(x) \prod_{Z \in \mathrm{ch}(X) \setminus \{Y\}} \lambda_{Z \to X}(x),\]
\[\lambda_{X \to U}(u) \propto \sum_{x} \lambda_X(x) \prod_{Z \in \mathrm{ch}(X)} \lambda_{Z \to X}(x) \sum_{u' } P(x \mid u, u') \prod_{U_i \neq U} \pi_{U_i \to X}(u_i),\]

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).

Methods

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

Sampling

Gibbs Sampling for BN

class pyagrum.GibbsSampling(bn)

Class for making Gibbs sampling inference in Bayesian networks.

GibbsSampling(bn) -> GibbsSampling
Parameters:

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() raises pyagrum.IncompatibleEvidence.

  • If no compatible configuration is found, makeInference() raises pyagrum.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 as pyagrum.LazyPropagation can check it (evidenceProbability() raises pyagrum.IncompatibleEvidence for 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):

\[P(x \mid \text{rest}) \propto P(x \mid \mathrm{pa}(X)) \prod_{C \in \mathrm{ch}(X)} P(c \mid \mathrm{pa}(C)).\]

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.

Methods

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

burnIn()

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentPosterior()

Returns the current estimation of the posterior of a node (for instance during the inference, in a listener).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isDrawnAtRandom()

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrDrawnVar()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setBurnIn()

setDrawnAtRandom()

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setNbrDrawnVar()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

Simple Monte Carlo Sampling for BN

class pyagrum.MonteCarloSampling(bn)

Class used for Monte Carlo sampling inference algorithm.

MonteCarloSampling(bn) -> MonteCarloSampling
Parameters:

Notes

The draws incompatible with the hard evidence are rejected. makeInference() raises pyagrum.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 as pyagrum.LazyPropagation can tell (evidenceProbability() raises pyagrum.IncompatibleEvidence for 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.

Methods

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentPosterior()

Returns the current estimation of the posterior of a node (for instance during the inference, in a listener).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

Weighted Sampling for BN

class pyagrum.WeightedSampling(bn)

Class used for Weighted sampling inference algorithm.

WeightedSampling(bn) -> WeightedSampling
Parameters:

Notes

The draws incompatible with the hard evidence are rejected. makeInference() raises pyagrum.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 as pyagrum.LazyPropagation can tell (evidenceProbability() raises pyagrum.IncompatibleEvidence for 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

\[\hat p = \frac{\sum_{k=1}^{N} w_k \, \mathbb{1}[x^{(k)}_X = x]}{\sum_{k=1}^{N} w_k}\]

(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\))

\[\ell = \frac{2z}{1 + z^2/n} \sqrt{\frac{\hat p (1 - \hat p)}{n} + \frac{z^2}{4n^2}}\]

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]

\[n_{\text{eff}} = \frac{\left(\sum_{k=1}^{N} w_k\right)^2}{\sum_{k=1}^{N} w_k^2} = \frac{1}{\sum_{k=1}^{N} \bar w_k^2}, \qquad \bar w_k = \frac{w_k}{\sum_j w_j},\]

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\)).

Methods

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentPosterior()

Returns the current estimation of the posterior of a node (for instance during the inference, in a listener).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

Importance Sampling for BN

class pyagrum.ImportanceSampling(bn)

Class used for inferences using the Importance Sampling algorithm.

ImportanceSampling(bn) -> ImportanceSampling
Parameters:

Notes

The draws incompatible with the hard evidence are rejected. makeInference() raises pyagrum.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 as pyagrum.LazyPropagation can tell (evidenceProbability() raises pyagrum.IncompatibleEvidence for 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:

\[Q(x \mid u) = \frac{P(x \mid u) + \delta}{1 + k_u\,\delta} \quad \text{if } P(x \mid u) > 0, \qquad Q(x \mid u) = 0 \text{ otherwise},\]

where \(k_u\) is the number of positive values of \(P(\cdot \mid u)\). The weight becomes

\[w = \prod_E P(e \mid \mathrm{pa}(E)) \prod_{X \notin E} \frac{P(x \mid \mathrm{pa}(X))}{Q(x \mid \mathrm{pa}(X))}.\]

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.

Methods

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentPosterior()

Returns the current estimation of the posterior of a node (for instance during the inference, in a listener).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

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:
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

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

burnIn()

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentPosterior()

Returns the current estimation of the posterior of a node (for instance during the inference, in a listener).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isDrawnAtRandom()

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

makeInference_()

Performs the inference: use makeInference instead.

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrDrawnVar()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setBurnIn()

setDrawnAtRandom()

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setNbrDrawnVar()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

setVirtualLBPSize()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

virtualLBPSize()

Loopy Monte Carlo Sampling

class pyagrum.LoopyMonteCarloSampling(bn)

Class used for inferences using a loopy version of importance sampling.

LoopyImportanceSampling(bn) -> LoopyImportanceSampling
Parameters:
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

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentPosterior()

Returns the current estimation of the posterior of a node (for instance during the inference, in a listener).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

makeInference_()

Performs the inference: use makeInference instead.

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

setVirtualLBPSize()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

virtualLBPSize()

Loopy Weighted Sampling

class pyagrum.LoopyWeightedSampling(bn)

Class used for inferences using a loopy version of importance sampling.

LoopyImportanceSampling(bn) -> LoopyImportanceSampling
Parameters:
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

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentPosterior()

Returns the current estimation of the posterior of a node (for instance during the inference, in a listener).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

makeInference_()

Performs the inference: use makeInference instead.

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

setVirtualLBPSize()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

virtualLBPSize()

Loopy Importance Sampling

class pyagrum.LoopyImportanceSampling(bn)

Class used for inferences using a loopy version of importance sampling.

LoopyImportanceSampling(bn) -> LoopyImportanceSampling
Parameters:
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

BN()

H()

addAllTargets()

Add all the nodes as targets.

addEvidence()

Adds a new evidence on a node (might be soft or hard).

addTarget()

Add a marginal target to the list of targets.

chgEvidence()

Change the value of an already existing evidence on a node (might be soft or hard).

currentPosterior()

Returns the current estimation of the posterior of a node (for instance during the inference, in a listener).

currentTime()

disableEpsilon()

Disable epsilon as a stopping criterion.

disableMaxIter()

Disable max iterations as a stopping criterion.

disableMaxTime()

Disable max time as a stopping criterion.

disableMinEpsilonRate()

Disable a min epsilon rate as a stopping criterion.

enableEpsilon()

Enable epsilon as a stopping criterion.

enableMaxIter()

Enable max iterations as a stopping criterion.

enableMaxTime()

Enable max time as a stopping criterion.

enableMinEpsilonRate()

Enable a min epsilon rate as a stopping criterion.

epsilon()

eraseAllEvidence()

Removes all the evidence entered into the network.

eraseAllTargets()

Clear all previously defined targets (marginal and joint targets).

eraseEvidence()

Remove the evidence, if any, corresponding to the node Id or name.

eraseTarget()

Remove, if existing, the marginal target.

evidenceImpact()

Create a pyagrum.Tensor for P(target|evs) (for all instanciation of target and evs)

hardEvidenceNodes()

hasEvidence()

Indicates whether a node has received evidence or, without argument, whether at least one node has.

hasHardEvidence()

hasSoftEvidence()

history()

The error at the start of each period of the last run: one value every periodSize() iterations, recorded only when the verbosity is enabled (see setVerbosity()).

invalidateTensors()

Tells the inference that the values of tensors of its model changed in place.

isEnabledEpsilon()

isEnabledMaxIter()

isEnabledMaxTime()

isEnabledMinEpsilonRate()

isTarget()

makeInference()

Perform the heavy computations needed to compute the targets’ posteriors

makeInference_()

Performs the inference: use makeInference instead.

maxIter()

maxTime()

messageApproximationScheme()

minEpsilonRate()

nbrEvidence()

nbrHardEvidence()

nbrIterations()

nbrSoftEvidence()

nbrTargets()

periodSize()

posterior()

Computes and returns the posterior of a node.

setEpsilon()

setEvidence()

Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.

setMaxIter()

setMaxTime()

setMinEpsilonRate()

setPeriodSize()

setTargets()

Remove all the targets and add the ones in parameter.

setVerbosity()

setVirtualLBPSize()

softEvidenceNodes()

targets()

updateEvidence()

Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).

verbosity()

virtualLBPSize()