def reduce_model(model, evidence): model = copy.deepcopy(model) # continuous_factors = [factor for factor in model.factors if isinstance(factor, ContinuousFactor)] for var, val in evidence.items(): for factor in model.factors: if var in factor.scope( ): # and "F(" in var: # make sure that we only reduce at this stage for continuous values, let the inference algorithm deal with reducing for binary variables try: factor.reduce([(var, val)]) except ValueError as e: print(factor) raise e new_model = FactorGraph() additional_evidence = {} for node in model.factors: if isinstance(node, ContinuousFactor): if len(node.scope()) == 1: node = TabularCPD(str(node.scope()[0]), 2, [[node.assignment(0), node.assignment(1)]]).to_factor() if len(node.scope()) == 0: continue # try: # var = node.variable # except: # print(node.scope()) # for v in node.scope(): # if var != v: # new_model.add_edge(str(v), str(var)) # if "same_reason" in var: # additional_evidence[var] = 1 new_model.add_nodes_from([str(n) for n in node.scope()]) new_model.add_factors(node) return new_model, additional_evidence
def reduce_model(self, evidence): model = copy.deepcopy(self.model) continuous_factors = [ factor for factor in model.factors if isinstance(factor, ContinuousFactor) ] for var, val in evidence.items(): for factor in continuous_factors: if var in factor.scope( ) and "F(" in var: # make sure that we only reduce at this stage for continuous values, let the inference algorithm deal with reducing for binary variables factor.reduce([(var, val)]) new_model = BayesianModel() additional_evidence = {} for node in model.factors: if isinstance(node, ContinuousFactor): if len(node.scope()) == 1: node = TabularCPD( str(node.scope()[0]), 2, [[node.assignment(0), node.assignment(1)]]) else: node = to_CPD(node) var = node.variable for v in node.scope(): if var != v: new_model.add_edge(str(v), str(var)) if "same_reason" in var: additional_evidence[var] = 1 new_model.add_nodes_from([str(n) for n in node.scope()]) new_model.add_cpds(node) return new_model, additional_evidence