import numpy as np from pyugm.factor import DiscreteFactor # Specify the potential table factor_data = np.array([[1, 2], [2, 1]]) # The variable names ("1" and "2") and cardinalities (2 and 2). variables_names_and_cardinalities = [(1, 2), (2, 2)] # Construct the factor factor = DiscreteFactor(variables_names_and_cardinalities, data=factor_data) print factor factor.data # The potential table # Marginalise out all the variables that is not named "1". (i.e. marginalise out variable "2") marg = factor.marginalize([1]) print marg print marg.data from pyugm.factor import DiscreteBelief # Create a belief that is based on a factor belief = DiscreteBelief(factor) # Reduce the original factor by observing variable "1" taking on the value 0. [TODO: implement efficient factor reduction] # Evidence is set by a dictionary where the key is a variable name and the value its observed value. belief.set_evidence({1: 0}) print belief print belief.data from pyugm.model import Model factor1 = DiscreteFactor([(1, 2), (2, 2)], data=np.array([[1, 2], [2, 1]])) factor2 = DiscreteFactor([(2, 2), ('variable3', 3)], # Variable names can also be strings data=np.array([[0, 0.2, 0.3], [0.1, 0.5, 0.3]])) # Cardinalities of 2 and 3 means the factor table must be 2x3 # [TODO: cardinalities can be inferred from data shape when provided] factor3 = DiscreteFactor([('variable3', 3), (4, 2)], data=np.array([[0, 1], [1, 2], [0.5, 0]])) model = Model([factor1, factor2, factor3]) model.edges # returns a set of tuples from pyugm.model import Model from pyugm.infer_message import LoopyBeliefUpdateInference factor1 = DiscreteFactor([(1, 2), (2, 2)], data=np.array([[1, 2], [2, 1]])) factor2 = DiscreteFactor([(2, 2), ('variable3', 3)], data=np.array([[0, 0.2, 0.3], [0.1, 0.5, 0.3]])) factor3 = DiscreteFactor([('variable3', 3), (4, 2)], data=np.array([[0, 1], [1, 2], [0.5, 0.1]])) model = Model([factor1, factor2, factor3]) inferrer = LoopyBeliefUpdateInference(model) inferrer.calibrate() # Calibrated marginals print inferrer.get_marginals(1)[0], inferrer.get_marginals(1)[0].data print inferrer.get_marginals(2)[0], inferrer.get_marginals(2)[0].data # Natural logarithm of the normalizing factor print inferrer.partition_approximation() inferrer.calibrate(evidence={'variable3': 1}) # Calibrated marginals print inferrer.get_marginals(1)[0], inferrer.get_marginals(1)[0].data print inferrer.get_marginals(2)[0], inferrer.get_marginals(2)[0].data # Natural logarithm of the normalizing factor print inferrer.partition_approximation()