def solve(self): current = {} measure = self.measure.pop(0) aux = copy.deepcopy(measure) for key in aux: measure[key + "_p"] = measure[key] measure.pop(key, None) measure = {**measure, **self.measure.pop(0)} for room in self.rooms.values(): current[room.name] = elimination_ask( room.name, measure, self.network_template).prob[True] print(measure) while self.measure: for room in current: self.network_template.variable_node(room + "_p").cpt = { (): current[room] } measure = self.measure.pop(0) for room in self.rooms.values(): current[room.name] = elimination_ask( room.name, measure, self.network_template).prob[True] room = max(current, key=current.get) likelihood = current[room] return (room, likelihood)
def tryOne(bn, query): X = query['variable'] e = query['evidence'] estr = str(e)[1:-1] print('P( %s | %s ) = ' % (X, estr), end='') prob = elimination_ask(X, e, bn) print(prob.show_approx())
def solve(self): # Place here your code to determine the maximum likelihood solution # returning the solution room name and likelihood # use probability.elimination_ask() to perform probabilistic inference time = 1 # Add all evidences along time to the evidence dictionary # Evidences ---> Measurements form t=1 to t=T evidence = {} for measurements in self.measurements: for measurement in measurements: if measurement[1] == "F": evidence.update({measurement[0]+"_t"+ str(time): False}) else: evidence.update({measurement[0]+"_t"+ str(time): True}) time +=1 room = "" likelihood = 0 # Finds the room with the highest likelihood given the evidence for room_search in self.rooms: room_query = room_search + "_t" + str(self.T) prob = probability.elimination_ask(room_query, evidence, self.BNet) if prob[True] > likelihood: likelihood = prob[True] room = room_search return (room, likelihood)
def solve(self): " " print('-------------------------------------------') print(self.NB) print('--- SOLVE ---') m = {} T, F = True, False for time in self.M: sensor = self.M[time].keys() for names in sensor: state = self.M[time][names] j = names + '_' + str(time) if state == 'T': m[j] = True else: m[j] = False for room in self.R: actual_room = room + '_' + str(len(self.M)) print(actual_room) print(m) probs = probability.elimination_ask(actual_room, m, self.NB).show_approx('{:}') t = float(probs.split(',')[1].split(': ')[1]) self.RoomProbs[room] = t solution_room = max(self.RoomProbs, key=self.RoomProbs.get) solution = [solution_room, self.RoomProbs[solution_room]] return tuple(solution)
def print_all(self): for t in range(1, self.T + 1): for n in self.room_names: var = n + str(t) print(var, end=":") print( probability.elimination_ask(var, self.evidence, self.net)[True])
def solve(self): self.gen_net() cpts = [(n, probability.elimination_ask(n + str(self.T), self.evidence, self.net)[True]) for n in self.room_names] ml = max(cpts, key=lambda x: x[1]) ml = (self.room_names[cpts.index(ml)], ml[1]) return ml
def solve(self): self.gen_net() #self.print_all() cpts = [(n, probability.elimination_ask(n + str(self.T), self.evidence, self.net)[True]) for n in self.room_names] ml = max(cpts, key=lambda x: x[1]) ml = (self.room_names[cpts.index(ml)], ml[1]) print("Most likely final time step:", ml) return ml
def solve(self): """ Place here your code to determine the maximum likelihood solution returning the solution room name and likelihood use probability.elimination_ask() to perform probabilistic inference""" likelihood = 0 highest_p_room = None # calculates P(room_fire | sensor_readings) for room in self.building.keys(): res = probability.elimination_ask(room + '_' + str(self.meas_cnt), self.evidence, self.net)[True] if likelihood <= res: highest_p_room = room likelihood = res return highest_p_room, likelihood
def solve(self): # Build Evidence of measurements for elimination_ask = ev_dict ev_dict = {} # for the elimination ask for m in self.measurement_list: s_name = m.sensors + '_' + str(m.time_step) ev_dict[s_name] = m.meas_value # Get likelihood for each room and store value in dictionary for room in self.room_list: r_name = room.name + '_' + str(self.time_step) # get likelihood of room being on fire = True likelihood = elimination_ask(r_name, ev_dict, self.bayes)[True] # Save values self.p_dict[r_name] = likelihood # Get max value room_name = max(self.p_dict, key=self.p_dict.get) max_likelihood = self.p_dict[room_name] return (room_name, max_likelihood)
def solve(self): """ Returns the room with higher probability of being on fire and that same probability using elimination_ask(). """ # Joins all measurements to a single one all_measures = {} for k in range(len(self.measure)): for key in self.measure[k]: all_measures[key + "_t_" + str(k)] = self.measure[k][key] # Calculates the probability of each room to be on fire current = {} for room in self.rooms.values(): room_name = room.name + "_t_" + str(k) current[room.name] = elimination_ask( room_name, all_measures, self.network_template).prob[True] room = max(current, key=current.get) likelihood = current[room] return (room, likelihood)
def solve(self): # Place here your code to determine the maximum likelihood solution # returning the solution room name and likelihood values={} prob=[] for room2 in self.rooms: id = self.rooms[room2] var = "r" + str(id)+ "_" + str(self.T) aux = pb.elimination_ask(var, self.evidence, self.network).show_approx(numfmt='{:.20g}') prob.append((aux, room2)) for i in range(len(prob)): false_comp, true_comp = prob[i][0].split(',') booleano, prob_true = true_comp.split(':') values[prob[i][1]]=float(prob_true) comp = 0 for room2 in values.keys(): if values[room2] > comp: comp = values[room2] likelihood = values[room2] room = room2 return (room, likelihood)
T: 0.10, F: 0.50 }), ('Rain', 'Cloudy', { T: 0.80, F: 0.20 }), ('WetGrass', 'Sprinkler Rain', { (T, T): 0.99, (T, F): 0.90, (F, T): 0.90, (F, F): 0.00 })]) print("P(Cloudy)") print(enumeration_ask('Cloudy', dict(), exercises).show_approx()) print(elimination_ask('Cloudy', dict(), exercises).show_approx()) print("P(Sprinker | cloudy)") print(enumeration_ask('Sprinkler', dict(Cloudy=T), exercises).show_approx()) print(elimination_ask('Sprinkler', dict(Cloudy=T), exercises).show_approx()) print("P(Cloudy| the sprinkler is running and it’s not raining)") print( enumeration_ask('Cloudy', dict(Sprinkler=T, Rain=F), exercises).show_approx()) print( elimination_ask('Cloudy', dict(Sprinkler=T, Rain=F), exercises).show_approx()) print("P(WetGrass | it’s cloudy, the sprinkler is running and it’s raining)") print( enumeration_ask('WetGrass', dict(Cloudy=T, Sprinkler=T, Rain=T), exercises).show_approx()) print(
(F, T): 0.90, (F, F): 0.1 })]) print("P(Raise | sunny)") ''' P(R | s) = alpha * P(R, s) = alpha * <P(R | s), P(-R | s)> = alpha * <0.01 * 0.7, 0.99 * 0.7> = alpha * <0.007, 0.693> = <0.01, 0.99> Raise and sunny are independent; therefore, 0.7, sunny, doesn't affect the result. ''' print(enumeration_ask('Raise', dict(Sunny=T), raise_ex).show_approx()) print(elimination_ask('Raise', dict(Sunny=T), raise_ex).show_approx()) print("P(Raise | happy ∧ sunny)") ''' P(R | h ^ s) = alpha * P(R, h, s) = alpha * P(R) * P(s) * P(h | R, s) = alpha * P(s) * <P(R) * P(h | R, s), P(-R) * P(h | -R, s)> = alpha * 0.7 * <0.01 * 1.0, 0.99 * 0.7> = alpha * 0.7 * <0.01, 0.693> = alpha * <0.007, 0.4851> = <0.0142, 0.986> Because of the relationship between Happy and Sunny affects Raise, it makes sense. ''' print(enumeration_ask('Raise', dict(Happy=T, Sunny=T), raise_ex).show_approx()) print(elimination_ask('Raise', dict(Happy=T, Sunny=T), raise_ex).show_approx())
# Utility variables T, F = True, False # From AIMA code (probability.py) - Fig. 14.2 - burglary example happy = BayesNet([('Sunny', '', 0.7), ('Raise', '', 0.01), ('Happy', 'Sunny Raise', { (T, T): 1, (T, F): 0.7, (F, T): 0.9, (F, F): 0.1 })]) # 5.3.a.i print('P(Raise | Sunny)=', elimination_ask('Raise', dict(Sunny=T), happy).show_approx()) # R and S are independent of each other, so the distribution is <0.01, 0.99> from the table # 5.3.a.ii print('P(Raise | happy ^ sunny)=', elimination_ask('Raise', dict(Happy=T, Sunny=T), happy).show_approx()) # because its always sunny we dont have to sum over sunny # = α P(R)P(h|R,s)P(s) # = α <P(s)P(R)P(h|R,s), P(s)P(¬R)P(h|¬R, s)> # = <0.01*0.7*1/(0.01*0.7*1+0.99*0.7*0.7), 0.99*0.7*0.7/(0.01*0.7*1+0.99*0.7*0.7)> # 5.b.i print('P(Raise | happy)=', elimination_ask('Raise', dict(Happy=T), happy).show_approx()) # in this case it could be sunny or not sunny which could effect the happiness # = α ∑_s P(R)P(h|R,s)P(s)
def solve(self): # Place here your code to determine the maximum likelihood solution # returning the solution room name and likelihood # use probability.elimination_ask() to perform probabilistic inference #Run elimination and print results T = True F = False results = {} a = [] c = [] evidence = [] it = 0 for j in self.M: if it == 0: b = ''.join(j) c.append(b) else: f = j.split(' ') #print(f) for k in f: h = k.split(':')[0] + '_t+' + str(it) + ':' + k.split( ':')[1] c.append(h) it = it + 1 d = ' '.join(c) a = d.split(' ') paird = {} for i in a: s = i.split(':') if s[1] == 'T': paird[s[0]] = T if s[1] == 'F': paird[s[0]] = F evidence = dict(paird) for i in self.vars: #print(i) if len(self.M) > 1: results.update({ i + '_t+' + str(len(self.M) - 1): probability.elimination_ask( i + '_t+' + str(len(self.M) - 1), evidence, self.BN).show_approx() }) else: results.update({ i: probability.elimination_ask(i, evidence, self.BN).show_approx() }) trues = {} ml = 0 for i in results: trues[i] = (results[i].split(',')[1].split(':')[1]) if float(trues[i]) > ml: maxtuple = (i, trues[i]) ml = max(ml, float(trues[i])) room = maxtuple[0].split('_t')[0] likelihood = float(maxtuple[1]) return (room, likelihood)
def Q1_1_2(): print("=" * 80) print("ANSWER 1.1.2") T, F = True, False bayes_net = BayesNet([('AI', '', 0.8), ('FossilFuel', '', 0.4), ('RenewableEnergy', 'AI FossilFuel', { (T, T): 0.2, (T, F): 0.7, (F, T): 0.02, (F, F): 0.5 }), ('Traffic', 'FossilFuel', { T: 0.95, F: 0.1 }), ('GlobalWarming', 'RenewableEnergy Traffic', { (T, T): 0.6, (T, F): 0.4, (F, T): 0.95, (F, F): 0.55 }), ('Employed', 'AI GlobalWarming', { (T, T): 0.01, (T, F): 0.03, (F, T): 0.03, (F, F): 0.95 })]) #print(bayes_net.variable_node('GlobalWarming').cpt) p_employed = enumeration_ask(X='Employed', e={ 'AI': True, 'FossilFuel': True }, bn=bayes_net) print('-' * 80) print(f"given AI=true and FossilFuel=True:", f"\n\t\tP(Employed)\t\t=\t\t{p_employed.show_approx()}") print('-' * 80) p_global_warming = elimination_ask(X='GlobalWarming', e={ 'Employed': False, 'Traffic': False }, bn=bayes_net) print('-' * 80) print(f"Given Employed=False and Traffic=False, \n\t\tP(GlobalWarming)\t=", f"\t\t{p_global_warming.show_approx()}") print('-' * 80) p_ai = elimination_ask(X='AI', e={ 'RenewableEnergy': True, 'GlobalWarming': True, 'Employed': True, 'Traffic': True, 'FossilFuel': True }, bn=bayes_net) print('-' * 80) print( f"Given RenewableEnergy=T, GlobalWarming=T", f"Employed=T, Traffic=T, FossilFuel=T, \n\t\tP(AI)\t\t\t=\t\t{p_ai.show_approx()}" ) print('-' * 80)
T, F = True, False # From AIMA code (probability.py) - Fig. 14.2 - burglary example burglary = BayesNet([ ('Burglary', '', 0.001), ('Earthquake', '', 0.002), ('Alarm', 'Burglary Earthquake', {(T, T): 0.95, (T, F): 0.94, (F, T): 0.29, (F, F): 0.001}), ('JohnCalls', 'Alarm', {T: 0.90, F: 0.05}), ('MaryCalls', 'Alarm', {T: 0.70, F: 0.01}) ]) # P(Alarm | burglary ∧ ¬earthquake) # From the table: < .04, .96 > print(enumeration_ask('Alarm', dict(Burglary=T, Earthquake=F), burglary).show_approx()) # P(John | burglary ∧ ¬earthquake) # a * [ P( J | A ) * P( A | B, -E ) + P( J | -A ) * P( -A | B, -E) ] # = a * (0.9 * 0.94 + 0.05 * 0.06) # = < .151, .849 > print(elimination_ask('JohnCalls', dict(Burglary=T, Earthquake=F), burglary).show_approx()) # P(Burglary | alarm) = # a * [ P(B) * P(E) * P( A | B, E ) + P(B) * P(-E) * P( A | B, -E) ] # = a * (0.001 * 0.002 * 0.95 + 0.001 * 0.998 * 0.94) # = <0.374, 0.626> print(elimination_ask('Burglary', dict(Alarm=T), burglary).show_approx()) # P(Burglary | john ∧ mary) # = <.284, .716> print(elimination_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary).show_approx())
from probability import BayesNet, enumeration_ask, elimination_ask # Utility variables T, F = True, False cancer = BayesNet([ ('Cancer', '', 0.01), ('Test1', 'Cancer', {T: 0.9, F: 0.2}), ('Test2', 'Cancer', {T: 0.9, F: 0.2}), ]) # a. P(Cancer | Test1 ^ Test2) # This calculates the probability of cancer given that test1 and test2 were positive print(enumeration_ask('Cancer', dict(Test1=T, Test2=T), cancer).show_approx()) print(elimination_ask('Cancer', dict(Test1=T, Test2=T), cancer).show_approx()) # b. P(Cancer | Test1 ^ -Test2) # This calculates the probability of cancer given that test1 was positive and test2 was negative print(enumeration_ask('Cancer', dict(Test1=T, Test2=F), cancer).show_approx()) print(elimination_ask('Cancer', dict(Test1=T, Test2=F), cancer).show_approx()) # These results make sense. One failed test reduces the likelihood of having cancer by two orders of magnitude # Here is P(Cancer | Test1 ^ Test2) worked out by hand # = alpha * <P(cancer) * P(test1 | cancer) * P(test2 | cancer), # P(-cancer) * P(test1 | -cancer) * P(test2 | -cancer)> # = alpha * <0.01 * 0.9 * 0.9, 0.99 * 0.2 * 0.2> # = alpha * <0.0081, 0.0396> # = <0.17, 0.83> # This one is low, but still still a scary number because the probability of both test results returning true
('Sunny', '', 0.7), ('Raise', '', 0.01), ('Happy', 'Sunny Raise', {(T, T): 1.0, (T, F): 0.7, (F, T): 0.9, (F, F): 0.1}), ]) ''' Inference. Refer to screen capture and/or turned in paper copy for mathematical explanation. The probability that you obtain a raise given that it is sunny. ''' # Compute P(Raise | sunny) print("\nP(Raise | sunny)") print(enumeration_ask('Raise', dict(Sunny=T), happiness).show_approx()) # elimination_ask() is a dynamic programming version of enumeration_ask(). print(elimination_ask('Raise', dict(Sunny=T), happiness).show_approx()) # gibbs_ask() is an approximation algorithm helps Bayesian Networks scale up. print(gibbs_ask('Raise', dict(Sunny=T), happiness).show_approx()) # See the explanation of the algorithms in AIMA Section 14.4. print(rejection_sampling('Raise', dict(Sunny=T), happiness).show_approx()) print(likelihood_weighting('Raise', dict(Sunny=T), happiness).show_approx()) ''' Diagnostic inference. Refer to screen capture and/or turned in paper copy for mathematical explanation. The probability that you obtain a raise given that you are happy and it is sunny. ''' # Compute P(Raise | happy ∧ sunny) print("\nP(Raise | happy ∧ sunny)") print(enumeration_ask('Raise', dict(Happy=T, Sunny=T), happiness).show_approx())
# Utility variables T, F = True, False # From AIMA code (probability.py) - Fig. 14.2 - burglary example burglary = BayesNet([ ('Burglary', '', 0.001), ('Earthquake', '', 0.002), ('Alarm', 'Burglary Earthquake', {(T, T): 0.95, (T, F): 0.94, (F, T): 0.29, (F, F): 0.001}), ('JohnCalls', 'Alarm', {T: 0.90, F: 0.05}), ('MaryCalls', 'Alarm', {T: 0.70, F: 0.01}) ]) # Compute P(Burglary | John and Mary both call). print(enumeration_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary).show_approx()) # elimination_ask() is a dynamic programming version of enumeration_ask(). print(elimination_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary).show_approx()) # gibbs_ask() is an approximation algorithm helps Bayesian Networks scale up. print(gibbs_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary).show_approx()) # See the explanation of the algorithms in AIMA Section 14.4. # rejection_sampling() and likelihood_weighting() are also approximation algorithms. print(rejection_sampling('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary).show_approx()) print(likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary).show_approx()) # P(Alarm | burglary ∧ ¬earthquake) print('5.1 i: \t' + enumeration_ask('Alarm', dict(Burglary=T, Earthquake=F), burglary).show_approx()) # P(John | burglary ∧ ¬earthquake) print('5.1 ii: \t' + enumeration_ask('John', dict(Burglary=T, Earthquake=F), burglary).show_approx()) # P(Burglary | alarm) print('5.1 iii:\t' + enumeration_ask('Burglary', dict(Alarm=T), burglary).show_approx())
fire = probability.BayesNet([ ('R02_0', '', 0.5000000000000000), ('R03_0', '', 0.5000000000000000), ('R03_1', 'R02_0 R03_0', {(T, T): 1, (T, F): 0.07549526619046759, (F, T): 1, (F, F): 0}), ('R02_1', 'R02_0 R03_0', {(T, T): 1, (T, F): 1, (F, T): 0.07549526619046759, (F, F): 0}), ('S01_1', 'R03_1', {T: 0.9423140000000000, F: 0.1215520000000000}), ('R03_2', 'R02_1 R03_1', {(T, T): 1, (T, F): 0.07549526619046759, (F, T): 1, (F, F): 0}), ('R02_2', 'R02_1 R03_1', {(T, T): 1, (T, F): 1, (F, T): 0.07549526619046759, (F, F): 0}), ('S01_2', 'R03_2', {T: 0.9423140000000000, F: 0.1215520000000000}), ('R03_3', 'R02_2 R03_2', {(T, T): 1, (T, F): 0.07549526619046759, (F, T): 1, (F, F): 0}), ('R02_3', 'R02_2 R03_2', {(T, T): 1, (T, F): 1, (F, T): 0.07549526619046759, (F, F): 0}), ('S01_3', 'R03_3', {T: 0.9423140000000000, F: 0.1215520000000000}), ('R03_4', 'R02_3 R03_3', {(T, T): 1, (T, F): 0.07549526619046759, (F, T): 1, (F, F): 0}), ('R02_4', 'R02_3 R03_3', {(T, T): 1, (T, F): 1, (F, T): 0.07549526619046759, (F, F): 0}), ('S01_4', 'R03_3', {T: 0.9423140000000000, F: 0.1215520000000000})]) print(probability.elimination_ask('R03_4', dict(S01_1=F, S01_2=T, S01_3=T, S01_4=T), fire).show_approx())