def conditionalModel(bn, evs): """ create a new condtional bn from a bn and a instanticiation of some variable :param bn: a bayesian network :param evs: map of evidence :return: a bayesian network """ newbn = gum.BayesNet(bn) newevs = dict(evs) for name in evs: nid = newbn.idFromName(name) for ch in newbn.children(nid): # create the new cpt q = newbn.cpt(ch) \ .extract({name: evs[name]}) \ .reorganize([v.name() for v in newbn.cpt(ch).variablesSequence() if v.name() != name]) # erase arc newbn.eraseArc(nid, ch) # update cpt # todo : add a Potential::fillWithParamOF(Potential) in agrum newbn.cpt(ch)[:] = q[:] # remove evidence without parent if len(newbn.parents(nid)) == 0: newbn.erase(nid) newevs.pop(name) return newbn, newevs
def testWithInstantiation(self): bn = gum.BayesNet() id_list = [] self.fillBN(bn, id_list) list3 = bn.cpt(id_list[3]) list3[:] = [[[1, 0], [0.1, 0.9]], [[0.1, 0.9], [0.01, 0.99]]] i = gum.Instantiation(list3) list3.set(i, 0) i.inc() list3.set(i, 1) self.assertListsAlmostEqual(list3[:], [[[0, 1], [0.1, 0.9]], [[0.1, 0.9], [0.01, 0.99]]]) self.assertListsAlmostEqual(list3[:], bn.cpt(id_list[3])[:])
def unsharpenedModel(bn, epsilon=1e-2): """ Modify the cpts of a BN in order to tend to uniform distributions :param bn: a bayesian netwok :param epsilon: a value that will be added every where before normalization :return: the newBN """ if bn.minNonZeroParam() < epsilon: newbn = gum.BayesNet(bn) for k in newbn.ids(): # adding epsilon on all non-zero value, and normalize as CPT again newbn.cpt(k)[:] = (newbn.cpt(k).isNonZeroMap().scale(epsilon) + newbn.cpt(k)).normalizeAsCPT()[:] else: newbn = bn return newbn