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
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()
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)