示例#1
0
    def enumeration_infer(self, X, e=None) -> ProbDist:  #page 525-528
        """
        Return the conditional probability distribution of variable X
        given evidence e
        """
        '''
        Use evidence passed to function call, otherwise use default
        '''
        if e == None:
            e = self.evidence

        assert X not in e, 'Query variable must be distinct from evidence'
        assert X in self.net.variables, 'Variable needs to be in network'
        """
        * Initialize a probability distribution 
        * For each outcome sum over all the hidden variables
        * Normalize
        """
        Q = ProbDist(X)
        # print(Q)
        # print('im here')
        # for each value xi of X do
        for xi in self.net.variable_values(X):
            # e[xi] = X
            exi = self.copy_assign(e, X, xi)
            # print(exi,'exiGHGHGHGHGHHGHGHGHGHGHG')
            # Q(xi)←ENUMERATE-ALL(bn.VARS, exi )
            Q[xi] = self.enumerate_all(self.net.variables, exi)
            # print(e)
        """YOUR CODE"""
        # return NORMALIZE(Q(X))
        # print(Q, "this is Q")
        return Q.normalize()
示例#2
0
    def rejection_sampling(self,
                           X: str,
                           N: int,
                           e: dict = None) -> ProbDist:  #533
        """
        Estimate the probability distribution of variable X given using 
        N samples and evidence e.  If not evidence is given, use the default
        for the Inference object.
        """
        if e == None:
            e = self.evidence

        # Q = ProbDist(X)
        """YOUR CODE"""
        countV = ProbDist(X)

        for j in range(N):  #N is the sample spaces.
            x = self.sample()  #   x←PRIOR-SAMPLE(bn)
            # px=ProbDist(x)
            #new way. want to find if e is subset of x items.
            setx = set(x.items())
            sete = set(e.items())
            if (sete.issubset(setx)):  #yay
                if x[X] is True:
                    countV[x[X]] = countV[x[X]] + 1
                if (x[X] is False):
                    countV[x[X]] = countV[x[X]] + 1
        # print(ProbDist.normalize(countV))
        return ProbDist.normalize(countV)  #<-- fix this too
示例#3
0
 def likelihood_weighting(self,
                          X: str,
                          N: int,
                          e: dict = None) -> ProbDist:  #page 534
     """Estimate the probability distribution of variable X given
     evidence e
     """
     if e == None:
         e = self.evidence
     W = ProbDist(X)
     for j in range(N):
         x, w = self.weighted_sample(e.copy())
         W[x[X]] = W[x[X]] + w
     return ProbDist.normalize(W)
示例#4
0
 def likelihood_weighting(self, X: str, N: int, e: dict = None) -> ProbDist:
     """
     TODO: Estimate the probability distribution of variable X given evidence e.
     X = query variable
     N = total number of samples generated
     e = evidence as event
     need bayesian net
     """
     """YOUR CODE"""
     if e == None:
         e = self.evidence
     W = {True: 0.0, False: 0.0}
     for i in range(N):
         x, w = self.weighted_sample(e)
         sam = x[X]
         W[sam] += w
     return ProbDist(X, W)  # <- put parameters in it
示例#5
0
    def rejection_sampling(self, X: str, N: int, e: dict = None) -> ProbDist:
        """
        TODO: Estimate the probability distribution of variable X given using 
        N samples and evidence e. If not evidence is given, use the default
        for the Inference object.
        X = query variable
        N = total number of samples generated
        e = evidence as event
        need bayesian net
        return P(X|e)
        """
        if e == None:
            e = self.evidence
        """YOUR CODE"""
        W = {True: 0.0, False: 0.0}

        for i in range(N):
            s = self.sample()
            if self.consistent(s, e):
                sam = s[X]
                W[sam] += 1
        return ProbDist(X, W)  # <- put parameters in it
示例#6
0
    def enumeration_ask(self, X, e=None) -> ProbDist:
        """
        TODO: Return the conditional probability distribution of variable X
        given evidence e
        """

        # Use evidence passed to function call, otherwise use default
        if e == None:
            e = self.evidence

        assert X not in e, 'Query variable must be distinct from evidence'
        assert X in self.net.variables, 'Variable needs to be in network'
        """
        * Initialize a probability distribution 
        * For each outcome sum over all the hidden variables
        * Normalize
        """
        """YOUR CODE"""
        vars = {}
        for xi in self.net.variables:
            vars[xi] = self.enumerate_all()
        return ProbDist().normalize()  # <- may need to tweak a bit
示例#7
0
        There are two ways to initialize distributions
        * Give it dictionary where the keys are the element of the sample space 
          and the values are counte or un-normalized probablities <<-- Will use this one
        * Give a sample_space list/tuple of domain values and a list/tuple that defines
          the distibution
    '''
    ''' roll virtual dice '''
    counts = {}
    for i in range(1, 6 + 1):
        counts[i] = 0
    for rolls in range(100):
        roll = round((random.random() * 6 -
                      0.5)) + 1  #scale and shift so round will work
        counts[roll] += 1
    print('Raw counts: ' + str(counts))
    pdice = ProbDist('Dice', counts)
    print('ProbDist Object: ' + str(pdice))
    print('Probability Dsitribution: ' + str(pdice.show_approx()))
    '''
    BayesNodes and BayesNets
    Each node is specified with its parent names and the neccesarey CPT
    The CPTs are a little tricky. They are a dictionary where the keys are tuples 
    of possible values from the sample space of the parent domains. The value 
    is a probability vector that has the same length as the sample space. 
    '''

    testNode = BayesNode(
        'Node', 'val1 val2 val3', 'A/B-Parent C/D-Parent', {
            ('A', 'C'): (0.1, 0.2, 0.7),
            ('A', 'D'): (0.3, 0.5, 0.2),
            ('B', 'C'): (0.0, 0.2, 0.8),