Example #1
0
    def infer(self, sensor_evidence, fsm_evidence):
        # sensor values are always True; their proxy nodes encode the real probability
        evidence = dict(fsm_evidence)
        evidence.update({k: "T" for k in sensor_evidence})

        # update probability of proxy nodes
        for sensor, p in sensor_evidence.iteritems():
            self.net.Vdata[sensor]["cprob"] = {
                "['T']": [p, 1 - p],
                "['F']": [(1 - p), p]
            }

        # refactorize
        fn = TableCPDFactorization(self.net)
        events = []

        for name, output in self.outputs.iteritems():
            fn.refresh()
            query = {}

            for q in output["query"]:
                if is_negated(q):
                    query[normalise_name(q)] = ['F']
                else:
                    query[normalise_name(q)] = ['T']

            prob = result = fn.specificquery(query, evidence)
            ev = output["event"]
            formatted_query = " AND ".join(query)
            # logging.debug("Query p(%s)=%.8f; need p(%s)>%.8f to trigger event %s/%s" % (formatted_query, prob, formatted_query, 1-np.exp(ev["logp"]), ev.get("fsm", None), ev["event"]))

            logger.info(json.dumps({ \
                'type' : 'query',
                'query' : formatted_query,
                'value' : '%.8f' % prob,
                'threshold' : '%.8f' % (1-np.exp(ev['logp'])),
                'fsm' : ev.get("fsm", None),
                'event' : ev['event']
            }))

            if prob > (1 - np.exp(ev["logp"])) + self.event_caution:
                #logging.debug("Fired event %s/%s" % (ev.get("fsm", None), ev["event"]))
                logger.info(
                    json.dumps({
                        'type': 'fire_event',
                        'fsm': ev.get("fsm", None),
                        'event': ev['event']
                    }))

                # generate event
                events.append({
                    "fsm": ev.get("fsm", None),
                    "event": ev["event"]
                })

        return events
Example #2
0
skel = GraphSkeleton()
skel.load("../skeleton.json")

learner = PGMLearner()

result = learner.discrete_mle_estimateparams(skel, listofDicts)

tcf = TableCPDFactorization(result)

#Rating 1 Given Occupation is student
myquery = dict(rating=[1])
myevidence = dict(occupation='student')
result = tcf.specificquery(query=myquery, evidence=myevidence)
print result

tcf.refresh()

#Rating 2 Given Occupation is student
myquery = dict(rating=[2])
myevidence = dict(occupation='student')
result = tcf.specificquery(query=myquery, evidence=myevidence)
print result

tcf.refresh()

#Rating 3 Given Occupation is student
myquery = dict(rating=[3])
myevidence = dict(occupation='student')
result = tcf.specificquery(query=myquery, evidence=myevidence)
print result
Example #3
0
class TestTableCPDFactorization(unittest.TestCase):

    def setUp(self):
        skel = GraphSkeleton()
        skel.load("unittestdict.txt")
        skel.toporder()
        nodedata = NodeData()
        nodedata.load("unittestdict.txt")
        self.bn = DiscreteBayesianNetwork(skel, nodedata)
        self.fn = TableCPDFactorization(self.bn)

    def test_constructor(self):
        self.assertTrue(len(self.fn.originalfactorlist) == 5)
        for x in range(5):
            self.assertTrue(isinstance(self.fn.originalfactorlist[x], TableCPDFactor))

    def test_refresh(self):
        evidence = dict(Letter='weak')
        query = dict(Intelligence=['high'])
        result1 = self.fn.specificquery(query, evidence)
        self.fn.refresh()
        result2 = self.fn.specificquery(query, evidence)
        self.assertEqual(result1, result2)

    def test_sumproducteliminatevar(self):
        self.fn.refresh()
        self.fn.sumproducteliminatevar("Difficulty")
        yes = 0
        for x in range(len(self.fn.factorlist)):
            if (self.fn.factorlist[x].scope == ['Grade', 'Intelligence']):
                yes += 1
                index = x

        self.assertTrue(yes == 1)
        exp = [0.2, 0.33999999999999997, 0.45999999999999996, 0.74, 0.16799999999999998, 0.09200000000000001]
        for x in range(6):
            self.assertTrue(abs(self.fn.factorlist[index].vals[x] - exp[x]) < .01)

    def test_sumproductve(self):
        input = ["Difficulty", "Grade", "Intelligence", "SAT"]
        self.fn.refresh()
        self.fn.sumproductve(input)
        exp = [.498, .502]
        for x in range(2):
            self.assertTrue(abs(self.fn.factorlist.vals[x] - exp[x]) < .01)

    def test_condprobve(self):
        evidence = dict(Grade='C', SAT='highscore')
        query = dict(Intelligence='high')
        self.fn.refresh()
        self.fn.condprobve(query, evidence)
        exp = [.422, .578]
        for x in range(2):
            self.assertTrue(abs(self.fn.factorlist.vals[x] - exp[x]) < .01)

    def test_specificquery(self):
        evidence = dict(Difficulty='easy')
        query = dict(Grade=['A', 'B'])
        self.fn.refresh()
        answer = self.fn.specificquery(query, evidence)
        self.assertTrue(abs(answer - .784) < .01)

    def test_gibbssample(self):
        evidence = dict(Letter='weak')
        gs = self.fn.gibbssample(evidence, 5)
        self.assertTrue(gs[0]["Difficulty"] == 'easy' or gs[0]["Difficulty"] == 'hard')
        self.assertTrue(len(gs) == 5)
        for entry in gs:
            self.assertTrue(entry["Letter"] == 'weak')
skel.load("../skeleton.json")

learner = PGMLearner()

result = learner.discrete_mle_estimateparams(skel, listofDicts)

tcf=TableCPDFactorization(result)

#Rating 1 Given Genre  is Drama
myquery = dict(rating=[1])
myevidence = dict(genre='Drama')
result=tcf.specificquery(query=myquery,evidence=myevidence)
print result


tcf.refresh()

#Rating 2 Given Genre  is Drama
myquery = dict(rating=[2])
myevidence = dict(genre='Drama')
result=tcf.specificquery(query=myquery,evidence=myevidence)
print result

tcf.refresh()

#Rating 3 Given Genre  is multiple
myquery = dict(rating=[3])
myevidence = dict(genre='Drama')
result=tcf.specificquery(query=myquery,evidence=myevidence)
print result
Example #5
0
class TestTableCPDFactorization(unittest.TestCase):
    
    def setUp(self):
        skel = GraphSkeleton()
        skel.load("unittestdict.txt")
        skel.toporder()
        nodedata = NodeData()
        nodedata.load("unittestdict.txt")
        self.bn = DiscreteBayesianNetwork(skel, nodedata)
        self.fn = TableCPDFactorization(self.bn)
    
    def test_constructor(self):
        self.assertTrue(len(self.fn.originalfactorlist) == 5)
        for x in range(5):
            self.assertTrue(isinstance(self.fn.originalfactorlist[x], TableCPDFactor))
    
    def test_refresh(self):
        self.fn.refresh()
        for x in range(5):
            self.assertTrue(isinstance(self.fn.factorlist[x], TableCPDFactor))
                            
    def test_sumproducteliminatevar(self):
        self.fn.refresh()
        self.fn.sumproducteliminatevar("Difficulty")
        yes = 0
        for x in range(len(self.fn.factorlist)):
            if (self.fn.factorlist[x].scope == ['Grade', 'Intelligence']):
                yes += 1 
                index = x
                
        self.assertTrue(yes == 1)
        exp = [0.2, 0.33999999999999997, 0.45999999999999996, 0.74, 0.16799999999999998, 0.09200000000000001]
        for x in range(6):
            self.assertTrue(abs(self.fn.factorlist[index].vals[x] - exp[x]) < .01)

    def test_sumproductve(self):
        input = ["Difficulty", "Grade", "Intelligence", "SAT"]
        self.fn.refresh()
        self.fn.sumproductve(input)
        exp = [.498, .502]
        for x in range(2):
            self.assertTrue(abs(self.fn.factorlist.vals[x] - exp[x]) < .01)
    
    def test_condprobve(self):
        evidence = dict(Grade='C', SAT='highscore')
        query = dict(Intelligence='high')
        self.fn.refresh()
        self.fn.condprobve(query, evidence)
        exp = [.422, .578]
        for x in range(2):
            self.assertTrue(abs(self.fn.factorlist.vals[x] - exp[x]) < .01)
        
    def test_specificquery(self):
        evidence = dict(Difficulty='easy')
        query = dict(Grade=['A', 'B'])
        self.fn.refresh()
        answer = self.fn.specificquery(query, evidence)
        self.assertTrue(abs(answer - .784) < .01)
    
    def test_gibbssample(self):
        evidence = dict(Letter='weak')
        gs = self.fn.gibbssample(evidence, 5)
        self.assertTrue(gs[0]["Difficulty"] == 'easy' or gs[0]["Difficulty"] == 'hard')
        self.assertTrue(len(gs) == 5)
        for entry in gs: 
            self.assertTrue(entry["Letter"] == 'weak')