In GTSAM, sum-product produces a Bayes net or Bayes tree; DiscreteMarginals is the additional class used to query specific normalized marginals from a discrete factor graph.
import gtsam
import numpy as np
from gtsam.symbol_shorthand import M, X
from IPython.display import Markdown, displayBuilding a small model¶
The first factor prefers A0 = 0. The pairwise factor encourages B0 to agree with A0.
A = (gtsam.symbol("A", 0), 2)
B = (gtsam.symbol("B", 0), 2)
graph = gtsam.DiscreteFactorGraph()
graph.add(A, "0.6 0.4")
graph.add([B, A], "0.8 0.2 0.3 0.7")
marginals = gtsam.DiscreteMarginals(graph)Querying probabilities¶
marginalProbabilities((key, cardinality)) returns a vector ordered by the variable’s integer values. Each vector is normalized even when the original graph contains unnormalized potentials.
p_a = marginals.marginalProbabilities(A)
p_b = marginals.marginalProbabilities(B)
print("P(A0):", p_a)
print("P(B0):", p_b)
assert np.isclose(p_a.sum(), 1.0)
assert np.isclose(p_b.sum(), 1.0)Interpreting the result¶
The marginal is not necessarily the state chosen by a global MPE assignment: summation accounts for all assignments of the other variables. Recreate DiscreteMarginals after changing the graph; the object represents inference for the graph passed to its constructor. Repeated queries can reuse its elimination structure, so one object is preferable to eliminating the same unchanged graph separately for every variable.
Source¶
AI assistance caveat¶
AI was used to help draft this documentation, and inaccuracies could be present.