Пример #1
0
    def __init__(self, file):

        self.rooms = {}
        self.sensors = {}
        self.P = 0
        self.measure = []

        # Fill problem
        self.read_file(file)

        bayes_template = []
        for room in self.rooms.values():
            bayes_template.append((room.name + "_p", '', 0.5))

        for room in self.rooms.values():

            aux_str = room.name + "_p"
            for parent in room.adj_rooms:
                aux_str += " " + parent + "_p"

            truth_table = self.create_truth_table(len(room.adj_rooms) +
                                                  1) if room.adj_rooms else {
                                                      True: 1,
                                                      False: 0
                                                  }
            bayes_template.append((room.name, aux_str, truth_table))

        for sensor in self.sensors.values():
            bayes_template.append((sensor.id, sensor.room, {
                True: sensor.TPR,
                False: sensor.FPR
            }))
            bayes_template.append((sensor.id + "_p", sensor.room + "_p", {
                True: sensor.TPR,
                False: sensor.FPR
            }))

        for node in bayes_template:
            print(node)

        self.network_template = BayesNet(bayes_template)
Пример #2
0
def generate_bayesnet():
    """
    Generates a BayesNet object representing the Bayesian network in Part 2
    returns the BayesNet object
    """
    bayes_net = BayesNet()
    # load the dataset, a list of DataPoint objects
    data = pickle.load(open("data/bn_data.p", "rb"))
    # BEGIN_YOUR_CODE ######################################################
    raise NotImplementedError

    # END_YOUR_CODE ########################################################
    return bayes_net
Пример #3
0
    def create(self):
        baye = []
        for step in range(self.time_step + 1):
            for room in self.room_list:
                # Create parents at t=0
                if step == 0:
                    baye.append((room.name + '_' + str(step), '', 0.5))
                    if room.sensor:
                        s_name = room.sensor.name + '_' + str(step)
                        r_name = room.name + '_' + str(step)
                        baye.append((s_name, r_name,
                                     self.get_prob(sensor=room.sensor)))
                elif step != self.time_step and step != 0:
                    # Start building the child nodes
                    parent = None
                    parent = room.name + '_' + str(step - 1)
                    # Add parents of current node
                    for neighboor in room.neighbours:
                        parent = parent + ' ' + neighboor + '_' + str(step - 1)
                    # Append to list, a tuple witt all the info of the current node
                    r_name = room.name + '_' + str(step)
                    baye.append((r_name, parent, self.get_prob(room=room)))
                    # Do sensors now
                    if room.sensor:  #and any(item == step for item in room.sensor.time):
                        s_name = room.sensor.name + '_' + str(step)
                        r_name = room.name + '_' + str(step)
                        baye.append((s_name, r_name,
                                     self.get_prob(sensor=room.sensor)))

                    # if step == self.time_step:
                    #     parent = None
                    #     parent = room.name + '_' + str(step)
                    #     for neighboor in room.neighbours:
                    #         parent = parent + ' ' + neighboor + '_' + str(step)

                    #     r_name = room.name + '_' + str(step+1)
                    #     baye.append((r_name, parent, self.get_prob(room = room)))
                else:
                    parent = None
                    parent = room.name + '_' + str(step - 1)
                    for neighboor in room.neighbours:
                        parent = parent + ' ' + neighboor + '_' + str(step - 1)
                    # Append to list, a tuple witt all the info of the current node
                    r_name = room.name + '_' + str(step)
                    baye.append((r_name, parent, self.get_prob(room=room)))
        print(baye)
        return BayesNet(baye)
Пример #4
0
 def create(self):
     baye = []
     # Step in this case goes only until T-1
     for step in range(self.time_step):
         for room in self.room_list:
             # Create parents at t=0
             if step == 0:
                 # Add initial probability
                 baye.append((room.name + '_' + str(step), '', 0.5))
                 # Add respective sensors if any
                 if room.sensor:
                     for s in room.sensor:
                         s_name = s.name + '_' + str(step)
                         r_name = room.name + '_' + str(step)
                         baye.append(
                             (s_name, r_name, self.get_prob(sensor=s)))
             else:
                 # Start building the child nodes
                 parent = None
                 ax = 1
                 # Add parents of current node
                 parent = room.name + '_' + str(step - 1)
                 for neighboor in room.neighbours:
                     parent = parent + ' ' + neighboor + '_' + str(step - 1)
                     ax += 1
                 # Append to list, a tuple witt all the info of the current node
                 r_name = room.name + '_' + str(step)
                 baye.append((r_name, parent, self.get_prob(room=room)))
                 # Add respective sensors of the room if any
                 if room.sensor:
                     for s in room.sensor:
                         s_name = s.name + '_' + str(step)
                         r_name = room.name + '_' + str(step)
                         baye.append(
                             (s_name, r_name, self.get_prob(sensor=s)))
     # Uncomment to see bayes net
     #print(baye)
     return BayesNet(baye)
Пример #5
0
print(spam_filter.filter(["i", "am", "spam", "spam", "i", "am"])) # spam list
print(spam_filter.filter(["do", "i", "like", "green", "eggs", "and", "ham"])) # ham list
print(spam_filter.filter(["i", "do", "not", "like", "that", "spamiam"]))


# Problem 2a
# TODO: copy into Jupyter notebook

from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

grass = BayesNet([
    ('Cloudy', '', 0.5),
    ('Sprinkler', 'Cloudy', {T:0.1, F:0.5}),
    ('Rain', 'Cloudy', {T:0.8, F:0.2}),
    ('WetGrass', 'Sprinkler Rain', {(T, T):0.99, (T,F):0.9, (F,T):0.9, (F,F):0.0}),
    ])

print("\n\nProblem 2")
print("i. " + enumeration_ask('Cloudy', dict(), grass).show_approx())

print("ii. " + enumeration_ask('Sprinkler', dict(Cloudy=T), grass).show_approx())

print("iii. " + enumeration_ask('Cloudy', dict(Sprinkler=T, Rain=F), grass).show_approx())

print("iv. " + enumeration_ask('WetGrass', dict(Cloudy=T, Sprinkler=T, Rain=T), grass).show_approx())

print("v. " + enumeration_ask('Cloudy', dict(WetGrass=F), grass).show_approx())
Пример #6
0
# Burglary example [Figure 14.2]
from probability import BayesNet

T, F = True, False

death = BayesNet([('Overweight', '', 0.339), ('HighStress', '', 0.72),
                  ('HeartAttack', 'Overweight HighStress', {
                      (T, T): 0.72,
                      (T, F): 0.15,
                      (F, T): 0.12,
                      (F, F): 0.003
                  }), ('OldAge', '', 0.147),
                  ('Death', 'HeartAttack OldAge', {
                      (T, T): 0.749,
                      (T, F): 0.25,
                      (F, T): 0.0009,
                      (F, F): 0.001
                  })])
death.label = 'Death and Heart Attacks'

examples = {
    death: [
        {
            'variable': 'Overweight',
            'evidence': {
                'Death': T,
            },
        },
        {
            'variable': 'Death',
            'evidence': {
Пример #7
0
from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

# From AIMA code (probability.py) - Fig. 14.2 - burglary example
happy = BayesNet([
    ('Sunny', '', .7),
    ('Raise', '', .01),
    ('Happy', 'Sunny Raise', {
        (T, T): 1.0,
        (T, F): 0.7,
        (F, T): 0.9,
        (F, F): .1
    }),
])

print("\nP(Raise | Sunny)")
print(enumeration_ask('Raise', dict(Sunny=T), happy).show_approx())

#   P(Raise | sunny) = alpha * <P(Raise) * P(Sunny | Raise), P(Not raise) * P(Sunny | not raise)>
#   = alpha * <.01 * .7, .99 * .7>
#   = alpha * <.007, .693>
#   = <.01, .99> -independent events so they don't affect eachother.
#
#

print("\nP(Raise | Happy and Sunny)")
print(enumeration_ask('Raise', dict(Happy=T, Sunny=T), happy).show_approx())

#   P(Raise | Happy and Sunny) = alpha * <P(Happy | Sunny and Raise) * P(Sunny) * P(Raise), P(Happy | Sunny and Not raise) * P(Sunny) * P( No raise)
Пример #8
0
# Cancer example
from probability import BayesNet

T, F = True, False

cancer = BayesNet([
    ('Pollution', '', 0.10),
    ('Smoker', '', 0.90),
    ('LungCancer', 'Pollution Smoker', {
        (T, T): 0.987,
        (T, F): 0.10,
        (F, T): 0.87,
        (F, F): 0.09
    }),
    ('XRay', 'LungCancer', {
        T: 0.90,
        F: 0.10
    }),
    ('Dyspnoea', 'LungCancer', {
        T: 0.70,
        F: 0.30
    }),
    ('Death', 'LungCancer', {
        T: 0.87,
        F: 0.13
    }),
])
cancer.label = 'Lung Cancer Example'

examples = {
    cancer: [{
        'variable': 'LungCancer',
Пример #9
0
T, F = True, False

depressedStudent = BayesNet([
    ('Sad', '', 0.45),
    ('Homework', '', 0.32),
    ('Tired', '', 0.7),
    ('Sleeping', 'Sad Homework Tired',
     {(T, T, T): 0.12,
      (T, T, F): 0.05,
      (T, F, T): 0.65,
      (T, F, F): 0.33,
      (F, T, T): 0.10,
      (F, T, F): 0.03,
      (F, F, T): 0.89,
      (F, F, F): 0.01}),
    ('Moving', 'Sleeping', {T: 0.5, F: 0.87}),
    ('Drooling', 'Sleeping', {T: 0.56, F: 0.05}),
    ('Outside', 'Sleeping Sad',
     {(T, T): 0.005,
      (T, F): 0.01,
      (F, T): 0.28,
      (F, F): 0.43}),
    ('Exercise', 'Outside Moving',
     {(T, T): 0.6,
      (T, F): 0.0,
      (F, T): 0.34,
      (F, F): 0.0}),
])
depressedStudent.label = 'Depressed Student: is he sleeping, moving, drooling or outside?'

examples = {
Пример #10
0
    D1 = Decision()
    D1.addChildren(C1)
    D1.addChildren(C2)

    return 'Value for D1 is ' + str(D1.value()) + ' and ' + 'Action from D1 is ' + D1.action


T, F = True, False
chatbot = BayesNet([
    ('Accurate', '', 0.9),
    ('ProblemSize', '', 0.9),   # 0.9 is probabililty that problem size is small
    ('ConversationLength', 'ProblemSize', {T: (0.40, 0.40, 0.20), F: (0.20, 0.30, 0.50)}, 3),
    ('Frustrated', 'Accurate ProblemSize ConversationLength',
     {(T, T, 0): 0.20, (T, T, 1): 0.30, (T, T, 2): 0.60,
      (T, F, 0): 0.30, (T, F, 1): 0.60, (T, F, 2): 0.70,
      (F, T, 0): 0.40, (F, T, 1): 0.50, (F, T, 2): 0.80,
      (F, F, 0): 0.50, (F, F, 1): 0.80, (F, F, 2): 0.90}),
    ('Resolved', 'Accurate ConversationLength',
     {(T, 0): 0.30, (T, 1): 0.50, (T, 2): 0.70,
      (F, 0): 0.20, (F, 1): 0.30, (F, 2): 0.40})
])
psize_dict = {True: 'Small', False: 'Big'}
clength_dict = {0: 'Short', 1: 'Medium', 2: 'Long'}


def q8(variable, conditions, value):

    # Do enumeration ask
    probdist = enumeration_ask(variable, conditions, chatbot)
Пример #11
0
from probability import BayesNet

T, F = True, False

test = BayesNet([
    ('Study', '', 0.3),
    ('Sleep', '', 0.6),
    ('PlayGames', '', 0.1),
    ('Pass', 'Study Sleep PlayGames',
     {(T, T, T): 0.85,
      (T, T, F): 0.98,
      (F, T, T): 0.1,
      (F, F, T): 0.001,
      (F, F, F): 0.01,
      (T, F, T): 0.51,
      (F, T, F): 0.21,
      (T, F, F): 0.78}),
    ('BadDream', 'Pass', {T: 0.4, F: 0.6}),
    ('BeatGame', 'Pass', {T: 0.01, F: 0.2}),
    ('GoodDream', 'Pass', {T: 0.70, F: 0.1})
])
test.label = 'Pass Test'

examples = {
    test: [
        {'variable': 'Study',
         'evidence': {'BadDream':T, 'GoodDream':T},
         },
        {'variable': 'Study',
         'evidence': {'BadDream':F, 'GoodDream':T},
Пример #12
0
# Cancer example
from probability import BayesNet

T, F = True, False

cancer = BayesNet([
    ('Pollution', '', 0.10),
    ('Smoker','', 0.90),
    ('LungCancer', 'Pollution Smoker',
     {(T, T): 0.987,
      (T, F): 0.10,
      (F, T): 0.87,
      (F, F): 0.09}),
    ('XRay', 'LungCancer', {T: 0.90, F: 0.10}),
    ('Dyspnoea', 'LungCancer', {T: 0.70, F: 0.30}),
    ('Death', 'LungCancer', {T: 0.87, F: 0.13}),
])
cancer.label = 'Lung Cancer Example'

examples = {
    cancer: [
        {'variable': 'LungCancer',
         'evidence': {'Death':T, 'Pollution':T},
         },
        {'variable': 'Death',
         'evidence': {'LungCancer':F, 'Smoker':T},
         },
        {'variable': 'Smoker',
         'evidence': {'LungCancer':T, 'Pollution':T},
         },
        {'variable': 'Pollution',
Пример #13
0
from probability import BayesNet

T, F = True, False

snowDay = BayesNet([
    ('snow', '', 0.022),
    ('windChill', '', 0.017),
    ('advisory', 'snow windChill',
     {(T, T): 0.62,
      (T, F): 0.48,
      (F, T): 0.41,
      (F, F): 0.0001}),
    ('noSchool', 'advisory', {T: 0.70, F: 0.005}),
    ('extremeWarning', 'advisory', {T: 0.16, F: 0.002})
])
snowDay.label = 'snowDay shows various weather probabilities that effect the chances of a snow day in Buffalo, New York.'

examples = {
    snowDay: [
        {'variable': 'snow',
         'evidence': {'noSchool':T, 'extremeWarning':T},
         },
        {'variable': 'windChill',
         'evidence': {'noSchool': F, 'advisory': T},
         },
        {'variable': 'advisory',
         'evidence': {'noSchool': T, 'windChill': F},
         },
        {'variable': 'extremeWarning',
         'evidence': {'snow': T, 'windChill': T},
         },
Пример #14
0
    def __init__(self, file):
        """ Initializes the problem with an opened file.

        Creates the bayesian network onwhich every room is a child of itself 
        and the adjacent rooms at timestep t-1 and is parent of sensors that
        exist on the room and make measures at time t.  
        """

        self.rooms = {}
        self.sensors = {}
        self.P = 0
        self.measure = []

        # Fills the problem variables
        self.read_file(file)

        # Constructs the bayesian network
        str_temp = "{}_t_{}"
        bayes_template = []

        # First constructs the base network at time 0
        for room in self.rooms.values():
            bayes_template.append((str_temp.format(room.name, 0), '', 0.5))

        for sensor_id in self.measure[0]:

            sensor = self.sensors[sensor_id]
            bayes_template.append(
                (str_temp.format(sensor.id,
                                 0), str_temp.format(sensor.room, 0), {
                                     True: sensor.TPR,
                                     False: sensor.FPR
                                 }))

        # Then adds every timestep connecting rooms from the timestep before and sensors needed
        for k in range(1, len(self.measure)):

            for room in self.rooms.values():
                aux_str = str_temp.format(room.name, k - 1)
                for parent in room.adj_rooms:
                    aux_str += " " + str_temp.format(parent, k - 1)

                truth_table = self.create_truth_table(
                    len(room.adj_rooms) + 1) if room.adj_rooms else {
                        True: 1,
                        False: 0
                    }
                bayes_template.append(
                    (str_temp.format(room.name, k), aux_str, truth_table))

            for sensor_id in self.measure[k]:

                sensor = self.sensors[sensor_id]
                bayes_template.append(
                    (str_temp.format(sensor.id,
                                     k), str_temp.format(sensor.room, k), {
                                         True: sensor.TPR,
                                         False: sensor.FPR
                                     }))

        self.network_template = BayesNet(bayes_template)
Пример #15
0
# Burglary example [Figure 14.2]
from probability import BayesNet

T, F = True, False

nashvilleWeather = BayesNet([
    ('Rain', '', 0.36),
    ('Freezing', '', 0.27),
    ('CarAccident', 'Rain Freezing',
     {(T, T): 0.95,
      (T, F): 0.79,
      (F, T): 0.29,
      (F, F): 0.001}),
    ('InjuriesReported', 'CarAccident', {T: 0.89, F: 0.09}),
    ('DeathReported', 'CarAccident', {T: 0.95, F: 0.02})
])
nashvilleWeather.label = 'Nashville Weather Correlation With Accidents (Hypothetical)'

examples = {
    nashvilleWeather: [
        {'variable': 'Rain',
         'evidence': {'InjuriesReported': T, 'DeathReported': T},
         },
        {'variable': 'Freezing',
         'evidence': {'InjuriesReported': T, 'DeathReported': T},
         },
        {'variable': 'CarAccident',
         'evidence': {'InjuriesReported': T, 'Rain': F},
         },
        {'variable': 'DeathReported',
         'evidence': {'Rain': T, 'Freezing': T}
Пример #16
0
@author: kvlinden
@edited: Quentin Barnes
@version Jan 2, 2013
'''

from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

# From lab 05 - Cs 344
burglary = BayesNet([('Sunny', '', 0.70), ('Raise', '', 0.01),
                     ('Happy', 'Sunny Raise', {
                         (T, T): 1.0,
                         (T, F): 0.7,
                         (F, T): 0.9,
                         (F, F): 0.1
                     })])

print('P(Raise | sunny): ')
print(enumeration_ask('Raise', dict(Sunny=T), burglary).show_approx())

print('\nP(Raise | happy ∧ sunny): ')
print(enumeration_ask('Raise', dict(Happy=T, Sunny=T), burglary).show_approx())

print('\nP(Raise | happy): ')
print(enumeration_ask('Raise', dict(Happy=T), burglary).show_approx())

print('\nP(Raise | happy ∧ ¬sunny): ')
print(enumeration_ask('Raise', dict(Happy=T, Sunny=F), burglary).show_approx())
Пример #17
0
@version March 6, 2020
'''
import sys
sys.path.append('/home/neg6/cs344/cs344-code/tools/aima')
sys.path.append(
    'D:\\School\\2019-20 Spring\\CS 344 AI\\cs344-code\\tools\\aima')
from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

# From AIMA code (probability.py) - Fig. 14.2 - burglary example
happy = BayesNet([('Sunny', '', 0.7), ('Raise', '', .01),
                  ('Happy', 'Sunny Raise', {
                      (T, T): 1,
                      (T, F): .7,
                      (F, T): .9,
                      (F, F): .1
                  })])

# P(Raise | sunny)
# <.01, .99>
print("P(Raise | sunny):")
print(enumeration_ask('Raise', dict(Sunny=T), happy).show_approx())
# P(Raise | happy ^ sunny)
# x * <P(raise | happy) * P(raise | sunny) * P(raise), P(!raise | happy) * P(!raise | sunny) * P(!raise)>
# x * <(.9 * .01 * .01), (.07 * .99 * .99)>
# x * <.00009, .06861>
# <.00009/.0687, .06861/.0687>
# <.00131, .99869>
print("P(Raise | happy, sunny):")
Пример #18
0
from probability import BayesNet

T, F = True, False

test = BayesNet([('Study', '', 0.3), ('Sleep', '', 0.6),
                 ('PlayGames', '', 0.1),
                 ('Pass', 'Study Sleep PlayGames', {
                     (T, T, T): 0.85,
                     (T, T, F): 0.98,
                     (F, T, T): 0.1,
                     (F, F, T): 0.001,
                     (F, F, F): 0.01,
                     (T, F, T): 0.51,
                     (F, T, F): 0.21,
                     (T, F, F): 0.78
                 }), ('BadDream', 'Pass', {
                     T: 0.4,
                     F: 0.6
                 }), ('BeatGame', 'Pass', {
                     T: 0.01,
                     F: 0.2
                 }), ('GoodDream', 'Pass', {
                     T: 0.70,
                     F: 0.1
                 })])
test.label = 'Pass Test'

examples = {
    test: [
        {
            'variable': 'Study',
Пример #19
0
@author: Sarah Hendriksen (srh34)
@startedby: kvlinden
@version Jan 2, 2013
'''

from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

# From AIMA code (probability.py) - Fig. 14.2 - burglary example
happiness = BayesNet([
    ('Sunny', '', 0.70),
    ('Raise', '', 0.01),
    ('Happy', 'Sunny Raise', {
        (T, T): 1.0,
        (T, F): 0.70,
        (F, T): 0.90,
        (F, F): 0.10
    }),
])

# Exercise 5.3
# a)
# i)
print(enumeration_ask('Raise', dict(Sunny=T), happiness).show_approx())
# Output - False: .99, True: .01
# Hand-computed -
#   P(R | s) = < .01, .99 > --> they are independent events so it is just P(R)

# ii)
print(
Пример #20
0
from probability import BayesNet

T, F = True, False

grass = BayesNet([('Raining', '', 0.1), ('Sprinklers', '', 0.4),
                  ('GrassWet', 'Raining Sprinklers', {
                      (T, T): 0.99,
                      (T, F): 0.82,
                      (F, T): 0.94,
                      (F, F): 0.001
                  }), ('DadIsHappy', 'GrassWet', {
                      T: 0.90,
                      F: 0.05
                  }),
                  ('AquaphobicNeighborIsNotHappy', 'GrassWet', {
                      T: 0.70,
                      F: 0.01
                  })])
grass.label = 'WetGrass'

examples = {
    grass: [
        {
            'variable': 'Raining',
            'evidence': {
                'DadIsHappy': T,
                'AquaphobicNeighborIsNotHappy': T
            },
        },
        {
            'variable': 'Sprinklers',
Пример #21
0
# Burglary example [Figure 14.2]
from probability import BayesNet

T, F = True, False

coffee = BayesNet([
    ('Tired', '', 0.24),
    ('Working', '', 0.45),
    ('Coffee', 'Tired Working',
     {(T, T): 0.97,
      (T, F): 0.38,
      (F, T): 0.29,
      (F, F): 0.05}),
    ('Energy', 'Coffee', {T: 0.83, F: 0.21}),
    ('Jitters', 'Coffee', {T: 0.19, F: 0.01})
])
coffee.label = 'Probability of getting coffee'

examples = {
    coffee: [
        {'variable': 'Tired',
         'evidence': {'Energy':T, 'Jitters':T},
         },
        {'variable': 'Tired',
         'evidence': {'Energy':F, 'Jitters':T},
         },
        {'variable': 'Working',
         'evidence': {'Energy':T, 'Jitters':T},
         },
    ],
}
Пример #22
0
from probability import BayesNet

T, F = True, False

compile_error = BayesNet([
    ('MissingSemicolon', '', 0.5),
    ('ExtraSemicolon', '', 0.2),
    ('IndexOutOfRange', '', 0.1),
    ('CompileError', 'MissingSemicolon ExtraSemicolon IndexOutOfRange',
     {
         (T, T, T): 0.2,
         (T, T, F): 0.5,
         (T, F, T): 0.1,
         (T, F, F): 0.7,
         (F, T, T): 0.1,
         (F, T, F): 0.4,
         (F, F, T): 0.75,
         (F, F, F): 0.09
     }),
    ('CantFindSemiColon', 'CompileError', {T: 0.7, F: 0.3}),
    ('ArrayIsNull', 'CompileError', {T: 0.3, F: 0.85}),
    ('OhYeahForgotThat', 'CompileError', {T: 0.8, F: 0.1})
])

compile_error.label = 'Programming Compile Error Correlation With Cause (Hypothetical)'

examples = {
    compile_error: [
        {'variable': 'ExtraSemicolon',
         'evidence': {'CantFindSemiColon': T, 'OhYeahForgotThat': T}
         },
Пример #23
0
@author: Sarah Hendriksen (srh34)
@startedby: kvlinden
@version Jan 2, 2013
'''

from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

# From AIMA code (probability.py) - Fig. 14.2 - burglary example
cancer = BayesNet([('Cancer', '', 0.01), ('Test1', 'Cancer', {
    T: 0.90,
    F: 0.20
}), ('Test2', 'Cancer', {
    T: 0.90,
    F: 0.20
})])

# Exercise 5.2
# a)
print(enumeration_ask('Cancer', dict(Test1=T, Test2=T), cancer).show_approx())
# Output - False: 0.83, True: 0.17
# Hand-coding -
# P(C | t1 = T, t2 = T) = alpha P(C, t1 = T, t2 = T)
#                       = alpha < P(C) * P(t1 = T | C) * P(t2 = T | C),
#                                   P(not C) * P(t1 = T | not C) * P(t2 = T | not C)>
#                       = alpha < .01 * .9 * .9, .99 * .2 * .2 >
#                       = alpha < .0081, .0396 >
#                       = < .170, .830 >
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)
Пример #25
0
# Burglary example [Figure 14.2]
from probability import BayesNet

T, F = True, False

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})
])
burglary.label = 'Burglary Example, Fig. 14.2'

examples = {
    burglary: [
        {'variable': 'Burglary',
         'evidence': {'JohnCalls':T, 'MaryCalls':T},
         },
        {'variable': 'Burglary',
         'evidence': {'JohnCalls':F, 'MaryCalls':T},
         },
        {'variable': 'Earthquake',
         'evidence': {'JohnCalls':T, 'MaryCalls':T},
         },
    ],
}
Пример #26
0
@date: 03/08/2019
"""

from probability import BayesNet, enumeration_ask, elimination_ask

# Utility variables
T, F = True, False

# From AIMA code (probability.py) - Fig. 14.12 -  A multiply connected network with conditional probability tables
exercises = BayesNet([('Cloudy', '', 0.5),
                      ('Sprinkler', 'Cloudy', {
                          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(
Пример #27
0
#       (T, F): 0.02,
#       (F, T): 0.0368,
#       (F, F): 0.04}),
#     ('RedOnTop', 'RedKing', {T: 0.03846, F: 0.076923}),
#     # ('MaryCalls', 'Alarm', {T: 0.70, F: 0.01})
# ])
# cards.label = 'Cards'

smoking = BayesNet([
    ('Female', '', 0.51),
    ('LGB', '', 0.054),
    ('Smoker', 'LGB Female',
     {(T, T): 0.3047,
      (T, F): 0.3046,
      (F, T): 0.1885,
      (F, F): 0.2202}),
    ('LungCancer', 'Smoker Female',
     {(T, T): 0.095,
      (T, F): 0.159,
      (F, T): 0.004,
      (F, F): 0.002}),
    ('PrematureDeath', 'LungCancer', {T: 0.86, F: 0.0134}),
    # ('Smoker', 'LGB', {T: 0.205, F: 0.153})
])
smoking.label = 'Smoking Example'

examples = {
    smoking: [
        {'variable': 'LungCancer',
         'evidence': {'LGB':T},
         },
        {'variable': 'LGB',
Пример #28
0
from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

# From AIMA code (probability.py) - Fig. 14.2 - burglary example
cancer = BayesNet([('Cancer', '', .01), ('Test1', 'Cancer', {
    T: .9,
    F: .2
}), ('Test2', 'Cancer', {
    T: .9,
    F: .2
})])

print("\nP(Cancer | Test1 and Test2)")
print(enumeration_ask('Cancer', dict(Test1=T, Test2=T), cancer).show_approx())

print("\nP(Cancer | Test1 and negative Test2)")
print(enumeration_ask('Cancer', dict(Test1=T, Test2=F), cancer).show_approx())

#
# P(Cause | T1 And T2) = alpha * <P(C) * P(T1 | C) * P(T2 | C), P( not C) * P(T1 | not C) * P(T2 | not C)>
# = alpha * <.01 * .9 * .9, .99 * .2 * .2>
# = alpha * <.0081, .0396>
# = <.17, .83> (after normalization)

#   P(C | T1 and T2) = alpha * <P(C) * P(T1 | C) * P(not T2 | C), P(not C) * P(T1 | not C) * P(not T2 | Not C)>
#   = alpha * <.01 * .9 * .1, .99 * .2 * .8>
#   = alpha * <.0009, .1584>
#   = <.00565, .994> (after normalization)
#
Пример #29
0
CarAccidents = BayesNet([
    ('Texting', '', 0.002),
    ('Speeding', '', 0.002),
    ('Weather', '', 0.001),
    ('Alcohol', '', 0.003),
    ('AccidentA', 'Texting Speeding Weather Alcohol', {
        (T, T, T, T): 0.90,
        (F, T, T, T): 0.74,
        (T, F, T, T): 0.59,
        (T, T, F, T): 0.79,
        (T, T, T, F): 0.58,
        (F, F, T, T): 0.43,
        (F, T, F, T): 0.63,
        (F, T, T, F): 0.48,
        (T, F, F, T): 0.42,
        (T, F, T, F): 0.27,
        (T, T, F, F): 0.47,
        (T, F, F, F): 0.16,
        (F, T, F, F): 0.31,
        (F, F, T, F): 0.11,
        (F, F, F, T): 0.32,
        (F, F, F, F): 0.005
    }),

    # Attempt to try separating each kind of accident
    # ('AccidentB', 'Texting Weather',
    #  {(T, T): 0.37,
    #   (T, F): 0.16,
    #   (F, T): 0.11,
    #   (F, F): 0.05}),
    # ('AccidentC', 'Texting Alcohol',
    #  {(T, T): 0.58,
    #   (T, F): 0.16,
    #   (F, T): 0.32,
    #   (F, F): 0.05}),
    # ('AccidentD', 'Speeding Weather',
    #  {(T, T): 0.52,
    #   (T, F): 0.31,
    #   (F, T): 0.11,
    #   (F, F): 0.05}),
    # ('AccidentE', 'Speeding Alcohol',
    #  {(T, T): 0.73,
    #   (T, F): 0.31,
    #   (F, T): 0.32,
    #   (F, F): 0.05}),
    # ('AccidentF', 'Weather Alcohol',
    #  {(T, T): 0.53,
    #   (T, F): 0.11,
    #   (F, T): 0.32,
    #   (F, F): 0.05}),
    ('HitCar', 'AccidentA', {
        T: 0.40,
        F: 0.04
    }),
    ('HitGuardRail', 'AccidentA', {
        T: 0.50,
        F: 0.02
    }),

    # Attempt for each of the aforementioned to have their own probabilities
    # ('HitCar', 'AccidentB', {T: 0.60, F: 0.40}),
    # ('HitGuardRail', 'AccidentB', {T: 0.80, F: 0.20}),
    #
    # # ('HitCar', 'AccidentC', {T: 0.60, F: 0.40}),
    # ('HitGuardRail', 'AccidentC', {T: 0.80, F: 0.20}),
    #
    # ('HitCar', 'AccidentD', {T: 0.60, F: 0.40}),
    # ('HitGuardRail', 'AccidentD', {T: 0.80, F: 0.20}),
    #
    # ('HitCar', 'AccidentE', {T: 0.60, F: 0.40}),
    # ('HitGuardRail', 'AccidentE', {T: 0.80, F: 0.20}),
    #
    # ('HitCar', 'AccidentF', {T: 0.60, F: 0.40}),
    # ('HitGuardRail', 'AccidentF', {T: 0.80, F: 0.20})
])
Пример #30
0
depressedStudent = BayesNet([
    ('Sad', '', 0.45),
    ('Homework', '', 0.32),
    ('Tired', '', 0.7),
    ('Sleeping', 'Sad Homework Tired', {
        (T, T, T): 0.12,
        (T, T, F): 0.05,
        (T, F, T): 0.65,
        (T, F, F): 0.33,
        (F, T, T): 0.10,
        (F, T, F): 0.03,
        (F, F, T): 0.89,
        (F, F, F): 0.01
    }),
    ('Moving', 'Sleeping', {
        T: 0.5,
        F: 0.87
    }),
    ('Drooling', 'Sleeping', {
        T: 0.56,
        F: 0.05
    }),
    ('Outside', 'Sleeping Sad', {
        (T, T): 0.005,
        (T, F): 0.01,
        (F, T): 0.28,
        (F, F): 0.43
    }),
    ('Exercise', 'Outside Moving', {
        (T, T): 0.6,
        (T, F): 0.0,
        (F, T): 0.34,
        (F, F): 0.0
    }),
])
Пример #31
0
'''
This module implements the Bayesian network for exercise 5.2 in lab05 of CS344

@author: brentritzema
@version Mar 1, 2019
'''

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
Пример #32
0
# Burglary example [Figure 14.2]
from probability import BayesNet

T, F = True, False

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
                     })])

burglary.label = 'Burglary Example, Fig. 14.2'

famous = BayesNet([
    # will you get famous?
    # statistics recevied from https://nypost.com/2009/07/25/you-are-not-going-to-be-famous/ and
    ('liveInAmerica', '', 0.04),
    ('liveInNashville', '', 0.002),
    ('Famous', 'liveInAmerica liveInNashville', {
        (T, T): 0.000000024,
        (T, F): 0.000000024,
        (F, T): 0.0000000012,
        (F, F): 0.0000006
Пример #33
0
from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

happyNetwork = BayesNet([('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
                         })])

# a.i
print(enumeration_ask('Raise', dict(Sunny=T), happyNetwork).show_approx())
# This is really a depressingly low probability, sitting at an even 0.01, which is just straight up the probability
# of getting a raise. Which is really low.

# a.ii
print(
    enumeration_ask('Raise', dict(Happy=T, Sunny=T),
                    happyNetwork).show_approx())
# This is not very much more likely, sitting at .0142. The fact that you are happy does eliminate the times when
# you are not happy despite it being sunny from the equation.

# b.i
print(enumeration_ask('Raise', dict(Happy=T), happyNetwork).show_approx())
# This is yet slightly more likely again, since you aren't always happy when it is sunny, but you are almost always
# happy when you have gotten a raise. So the fact that you are happy makes it more likely that you got a raise than
# the fact that it is sunny does, even though the probability of having gotten a raise is still pretty miniscule.
Пример #34
0
# Burglary example [Figure 14.2]
from probability import BayesNet

T, F = True, False

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
                     })])
burglary.label = 'Burglary Example, Fig. 14.2'

storm = BayesNet([
    ('Thunderstorm', '', 0.005),
    ('Earthquake', '', 0.002),
    ('Rain', '', 0.02),
    ('Loud', 'Thunderstorm Earthquake Rain', {
        (T, T, T): 0.99,
        (T, F, T): 0.65,
        (T, T, F): 0.95,
        (T, F, F): 0.85,
        (F, T, T): 0.80,
        (F, T, F): 0.50,
Пример #35
0
# Accidents on the Nigerian Road
from probability import BayesNet

T, F = True, False

Aids = BayesNet([
    ('HIV', '', 0.1),
    ('Aids', '', 0.000982),
    ('Over30', '', 0.9),
    ('Dead', 'HIV Aids Over30',
     {
         (T, T, T): 0.90,
         (T, T, F): 0.13,
         (T, F, T): 0.85,
         (T, F, F): 0.07,
         (F, T, T): 0.0,
         (F, T, F): 0.0,
         (F, F, T): 0.99,
         (F, F, F): 0.95


     }),
    ('Jason', 'Dead', {T: 0.01, F: 0.90}),
    ('Lauren', 'Dead', {T: 0.20, F: 0.50}),
    ('Zach', 'Dead', {T: 0.49, F: 0.11})
])
Aids.label = 'Probability of Death with HIV/AIDS'

examples = {
    Aids: [
        {'variable': 'HIV',
Пример #36
0
It's taken from the AIMA Python code.

@author: kvlinden
@version Jan 2, 2013
'''

from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask

# Utility variables
T, F = True, False

happiness = 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
    }),
])

# Exercise 5.3
# The Bayesian network shown on the right represents a happiness domain in which either the sun or a raise in pay can
# increase the happiness of an agent.
#
# a. Implement this network shown and use it to compute the following probabilities:
#
#     i. P(Raise | sunny)
print("P(Raise | sunny): ",
      enumeration_ask('Raise', dict(Sunny=T), happiness).show_approx())
#     ii. P(Raise | happy ∧ sunny)
Пример #37
0
@version Jan 2, 2013

Updated by: Tyler Poel, for lab05 in CS 344, at Calvin University
Date: March 6, 2020
'''

from probability import BayesNet, enumeration_ask, elimination_ask, gibbs_ask, likelihood_weighting, rejection_sampling

# 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())
Пример #38
0
# Burglary example [Figure 14.2]
from probability import BayesNet

T, F = True, False

death = BayesNet([
    ('Overweight', '', 0.339),
    ('HighStress', '', 0.72),
    ('HeartAttack', 'Overweight HighStress',
     {(T, T): 0.72,
      (T, F): 0.15,
      (F, T): 0.12,
      (F, F): 0.003}),
    ('OldAge', '', 0.147),
    ('Death', 'HeartAttack OldAge',
     {(T, T): 0.749,
      (T, F): 0.25,
      (F, T): 0.0009,
      (F, F): 0.001})
])
death.label = 'Death and Heart Attacks'

examples = {
    death: [
        {'variable': 'Overweight',
         'evidence': {'Death':T,},
         },
        {'variable': 'Death',
         'evidence': {'HeartAttack':T, 'OldAge':F},
         },
        {'variable': 'HighStress',