This IPy notebook acts as supporting material for **Chapter 13 Quantifying Uncertainty**, **Chapter 14 Probabilistic Reasoning** and **Chapter 15 Probabilistic Reasoning over Time** of the book* Artificial Intelligence: A Modern Approach*. This notebook makes use of the implementations in probability.py module. Let us import everything from the probability module. It might be helpful to view the source of some of our implementations. Please refer to the Introductory IPy file for more details on how to do so.

```
In [ ]:
```from probability import *

Let us begin by specifying discrete probability distributions. The class **ProbDist** defines a discrete probability distribution. We name our random variable and then assign probabilities to the different values of the random variable. Assigning probabilities to the values works similar to that of using a dictionary with keys being the Value and we assign to it the probability. This is possible because of the magic methods **_ getitem _** and

```
In [ ]:
```%psource ProbDist

```
In [ ]:
```p = ProbDist('Flip')
p['H'], p['T'] = 0.25, 0.75
p['T']

**varname** has a default value of '?'. So if the name is not passed it defaults to ?. The keyword argument **freqs** can be a dictionary of values of random variable:probability. These are then normalized such that the probability values sum upto 1 using the **normalize** method.

```
In [ ]:
```p = ProbDist(freqs={'low': 125, 'medium': 375, 'high': 500})
p.varname

```
In [ ]:
```(p['low'], p['medium'], p['high'])

**prob** and **varname** the object also separately keeps track of all the values of the distribution in a list called **values**. Every time a new value is assigned a probability it is appended to this list, This is done inside the **_ setitem _** method.

```
In [ ]:
```p.values

**normalize** method.

```
In [ ]:
```p = ProbDist('Y')
p['Cat'] = 50
p['Dog'] = 114
p['Mice'] = 64
(p['Cat'], p['Dog'], p['Mice'])

```
In [ ]:
```p.normalize()
(p['Cat'], p['Dog'], p['Mice'])

It is also possible to display the approximate values upto decimals using the **show_approx** method.

```
In [ ]:
```p.show_approx()

The helper function **event_values** returns a tuple of the values of variables in event. An event is specified by a dict where the keys are the names of variables and the corresponding values are the value of the variable. Variables are specified with a list. The ordering of the returned tuple is same as those of the variables.

Alternatively if the event is specified by a list or tuple of equal length of the variables. Then the events tuple is returned as it is.

```
In [ ]:
```event = {'A': 10, 'B': 9, 'C': 8}
variables = ['C', 'A']
event_values (event, variables)

*A probability model is completely determined by the joint distribution for all of the random variables.* (**Section 13.3**) The probability module implements these as the class **JointProbDist** which inherits from the **ProbDist** class. This class specifies a discrete probability distribute over a set of variables.

```
In [ ]:
```%psource JointProbDist

Values for a Joint Distribution is a an ordered tuple in which each item corresponds to the value associate with a particular variable. For Joint Distribution of X, Y where X, Y take integer values this can be something like (18, 19).

To specify a Joint distribution we first need an ordered list of variables.

```
In [ ]:
```variables = ['X', 'Y']
j = JointProbDist(variables)
j

**ProbDist** class **JointProbDist** also employes magic methods to assign probability to different values.
The probability can be assigned in either of the two formats for all possible values of the distribution. The **event_values** call inside **_ getitem _** and

```
In [ ]:
```j[1,1] = 0.2
j[dict(X=0, Y=1)] = 0.5
(j[1,1], j[0,1])

It is also possible to list all the values for a particular variable using the **values** method.

```
In [ ]:
```j.values('X')

In this section we use Full Joint Distributions to calculate the posterior distribution given some evidence. We represent evidence by using a python dictionary with variables as dict keys and dict values representing the values.

This is illustrated in **Section 13.3** of the book. The functions **enumerate_joint** and **enumerate_joint_ask** implement this functionality. Under the hood they implement **Equation 13.9** from the book.

Here **α** is the normalizing factor. **X** is our query variable and **e** is the evidence. According to the equation we enumerate on the remaining variables **y** (not in evidence or query variable) i.e. all possible combinations of **y**

We will be using the same example as the book. Let us create the full joint distribution from **Figure 13.3**.

```
In [ ]:
```full_joint = JointProbDist(['Cavity', 'Toothache', 'Catch'])
full_joint[dict(Cavity=True, Toothache=True, Catch=True)] = 0.108
full_joint[dict(Cavity=True, Toothache=True, Catch=False)] = 0.012
full_joint[dict(Cavity=True, Toothache=False, Catch=True)] = 0.016
full_joint[dict(Cavity=True, Toothache=False, Catch=False)] = 0.064
full_joint[dict(Cavity=False, Toothache=True, Catch=True)] = 0.072
full_joint[dict(Cavity=False, Toothache=False, Catch=True)] = 0.144
full_joint[dict(Cavity=False, Toothache=True, Catch=False)] = 0.008
full_joint[dict(Cavity=False, Toothache=False, Catch=False)] = 0.576

**enumerate_joint** function returns the sum of those entries in P consistent with e,provided variables is P's remaining variables (the ones not in e). Here, P refers to the full joint distribution. The function uses a recursive call in its implementation. The first parameter **variables** refers to remaining variables. The function in each recursive call keeps on variable constant while varying others.

```
In [ ]:
```%psource enumerate_joint

**P(Toothache=True)**. This can be obtained by marginalization (**Equation 13.6**). We can use **enumerate_joint** to solve for this by taking Toothache=True as our evidence. **enumerate_joint** will return the sum of probabilities consistent with evidence i.e. Marginal Probability.

```
In [ ]:
```evidence = dict(Toothache=True)
variables = ['Cavity', 'Catch'] # variables not part of evidence
ans1 = enumerate_joint(variables, evidence, full_joint)
ans1

**P(Cavity=True and Toothache=True)**

```
In [ ]:
```evidence = dict(Cavity=True, Toothache=True)
variables = ['Catch'] # variables not part of evidence
ans2 = enumerate_joint(variables, evidence, full_joint)
ans2

Being able to find sum of probabilities satisfying given evidence allows us to compute conditional probabilities like **P(Cavity=True | Toothache=True)** as we can rewrite this as $$P(Cavity=True | Toothache = True) = \frac{P(Cavity=True \ and \ Toothache=True)}{P(Toothache=True)}$$

We have already calculated both the numerator and denominator.

```
In [ ]:
```ans2/ans1

**enumerate_joint_ask** which returns a probability distribution over the values of the variable **X**, given the {var:val} observations **e**, in the **JointProbDist P**. The implementation of this function calls **enumerate_joint** for each value of the query variable and passes **extended evidence** with the new evidence having **X = x _{i}**. This is followed by normalization of the obtained distribution.

```
In [ ]:
```%psource enumerate_joint_ask

Let us find **P(Cavity | Toothache=True)** using **enumerate_joint_ask**.

```
In [ ]:
```query_variable = 'Cavity'
evidence = dict(Toothache=True)
ans = enumerate_joint_ask(query_variable, evidence, full_joint)
(ans[True], ans[False])

You can verify that the first value is the same as we obtained earlier by manual calculation.

A Bayesian network is a representation of the joint probability distribution encoding a collection of conditional independence statements.

A Bayes Network is implemented as the class **BayesNet**. It consisits of a collection of nodes implemented by the class **BayesNode**. The implementation in the above mentioned classes focuses only on boolean variables. Each node is associated with a variable and it contains a **conditional probabilty table (cpt)**. The **cpt** represents the probability distribution of the variable conditioned on its parents **P(X | parents)**.

Let us dive into the **BayesNode** implementation.

```
In [ ]:
```%psource BayesNode

The constructor takes in the name of **variable**, **parents** and **cpt**. Here **variable** is a the name of the variable like 'Earthquake'. **parents** should a list or space separate string with variable names of parents. The conditional probability table is a dict {(v1, v2, ...): p, ...}, the distribution P(X=true | parent1=v1, parent2=v2, ...) = p. Here the keys are combination of boolean values that the parents take. The length and order of the values in keys should be same as the supplied **parent** list/string. In all cases the probability of X being false is left implicit, since it follows from P(X=true).

The example below where we implement the network shown in **Figure 14.3** of the book will make this more clear.

The alarm node can be made as follows:

```
In [ ]:
```alarm_node = BayesNode('Alarm', ['Burglary', 'Earthquake'],
{(True, True): 0.95,(True, False): 0.94, (False, True): 0.29, (False, False): 0.001})

**cpt** is

```
In [ ]:
```john_node = BayesNode('JohnCalls', ['Alarm'], {True: 0.90, False: 0.05})
mary_node = BayesNode('MaryCalls', 'Alarm', {(True, ): 0.70, (False, ): 0.01}) # Using string for parents.
# Equvivalant to john_node definition.

The general format used for the alarm node always holds. For nodes with no parents we can also use.

```
In [ ]:
```burglary_node = BayesNode('Burglary', '', 0.001)
earthquake_node = BayesNode('Earthquake', '', 0.002)

**p** method. The method takes in two arguments **value** and **event**. Event must be a dict of the type {variable:values, ..} The value corresponds to the value of the variable we are interested in (False or True).The method returns the conditional probability **P(X=value | parents=parent_values)**, where parent_values are the values of parents in event. (event must assign each parent a value.)

```
In [ ]:
```john_node.p(False, {'Alarm': True, 'Burglary': True}) # P(JohnCalls=False | Alarm=True)

**BayesNet**. The **BayesNet** class does not take in nodes as input but instead takes a list of **node_specs**. An entry in **node_specs** is a tuple of the parameters we use to construct a **BayesNode** namely **(X, parents, cpt)**. **node_specs** must be ordered with parents before children.

```
In [ ]:
```%psource BayesNet

The constructor of **BayesNet** takes each item in **node_specs** and adds a **BayesNode** to its **nodes** object variable by calling the **add** method. **add** in turn adds node to the net. Its parents must already be in the net, and its variable must not. Thus add allows us to grow a **BayesNet** given its parents are already present.

**burglary** global is an instance of **BayesNet** corresponding to the above example.

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

```
In [ ]:
``````
burglary
```

**BayesNet** method **variable_node** allows to reach **BayesNode** instances inside a Bayes Net. It is possible to modify the **cpt** of the nodes directly using this method.

```
In [ ]:
```type(burglary.variable_node('Alarm'))

```
In [ ]:
```burglary.variable_node('Alarm').cpt

A Bayes Network is a more compact representation of the full joint distribution and like full joint distributions allows us to do inference i.e. answer questions about probability distributions of random variables given some evidence.

Exact algorithms don't scale well for larger networks. Approximate algorithms are explained in the next section.

We apply techniques similar to those used for **enumerate_joint_ask** and **enumerate_joint** to draw inference from Bayesian Networks. **enumeration_ask** and **enumerate_all** implement the algorithm described in **Figure 14.9** of the book.

```
In [ ]:
```%psource enumerate_all

**enumerate__all** recursively evaluates a general form of the **Equation 14.4** in the book.

such that **P(X, e, y)** is written in the form of product of conditional probabilities **P(variable | parents(variable))** from the Bayesian Network.

**enumeration_ask** calls **enumerate_all** on each value of query variable **X** and finally normalizes them.

```
In [ ]:
```%psource enumeration_ask

**P(Burglary=True | JohnCalls=True, MaryCalls=True)** using the **burglary** network.**enumeration_ask** takes three arguments **X** = variable name, **e** = Evidence (in form a dict like previously explained), **bn** = The Bayes Net to do inference on.

```
In [ ]:
```ans_dist = enumeration_ask('Burglary', {'JohnCalls': True, 'MaryCalls': True}, burglary)
ans_dist[True]

The enumeration algorithm can be improved substantially by eliminating repeated calculations. In enumeration we join the joint of all hidden variables. This is of exponential size for the number of hidden variables. Variable elimination employes interleaving join and marginalization.

Before we look into the implementation of Variable Elimination we must first familiarize ourselves with Factors.

In general we call a multidimensional array of type P(Y1 ... Yn | X1 ... Xm) a factor where some of Xs and Ys maybe assigned values. Factors are implemented in the probability module as the class **Factor**. They take as input **variables** and **cpt**.

There are certain helper functions that help creating the **cpt** for the Factor given the evidence. Let us explore them one by one.

```
In [ ]:
```%psource make_factor

**make_factor** is used to create the **cpt** and **variables** that will be passed to the constructor of **Factor**. We use **make_factor** for each variable. It takes in the arguments **var** the particular variable, **e** the evidence we want to do inference on, **bn** the bayes network.

Here **variables** for each node refers to a list consisting of the variable itself and the parents minus any variables that are part of the evidence. This is created by finding the **node.parents** and filtering out those that are not part of the evidence.

The **cpt** created is the one similar to the original **cpt** of the node with only rows that agree with the evidence.

```
In [ ]:
```%psource all_events

The **all_events** function is a recursive generator function which yields a key for the orignal **cpt** which is part of the node. This works by extending evidence related to the node, thus all the output from **all_events** only includes events that support the evidence. Given **all_events** is a generator function one such event is returned on every call.

We can try this out using the example on **Page 524** of the book. We will make **f**_{5}(A) = P(m | A)

```
In [ ]:
```f5 = make_factor('MaryCalls', {'JohnCalls': True, 'MaryCalls': True}, burglary)

```
In [ ]:
``````
f5
```

```
In [ ]:
```f5.cpt

```
In [ ]:
```f5.variables

**f5.cpt** False key gives probability for **P(MaryCalls=True | Alarm = False)**. Due to our representation where we only store probabilities for only in cases where the node variable is True this is the same as the **cpt** of the BayesNode. Let us try a somewhat different example from the book where evidence is that the Alarm = True

```
In [ ]:
```new_factor = make_factor('MaryCalls', {'Alarm': True}, burglary)

```
In [ ]:
```new_factor.cpt

Here the **cpt** is for **P(MaryCalls | Alarm = True)**. Therefore the probabilities for True and False sum up to one. Note the difference between both the cases. Again the only rows included are those consistent with the evidence.

We are interested in two kinds of operations on factors. **Pointwise Product** which is used to created joint distributions and **Summing Out** which is used for marginalization.

```
In [ ]:
```%psource Factor.pointwise_product

**Factor.pointwise_product** implements a method of creating a joint via combining two factors. We take the union of **variables** of both the factors and then generate the **cpt** for the new factor using **all_events** function. Note that the given we have eliminated rows that are not consistent with the evidence. Pointwise product assigns new probabilities by multiplying rows similar to that in a database join.

```
In [ ]:
```%psource pointwise_product

**pointwise_product** extends this operation to more than two operands where it is done sequentially in pairs of two.

```
In [ ]:
```%psource Factor.sum_out

**Factor.sum_out** makes a factor eliminating a variable by summing over its values. Again **events_all** is used to generate combinations for the rest of the variables.

```
In [ ]:
```%psource sum_out

**sum_out** uses both **Factor.sum_out** and **pointwise_product** to finally eliminate a particular variable from all factors by summing over its values.

The algorithm described in **Figure 14.11** of the book is implemented by the function **elimination_ask**. We use this for inference. The key idea is that we eliminate the hidden variables by interleaving joining and marginalization. It takes in 3 arguments **X** the query variable, **e** the evidence variable and **bn** the Bayes network.

The algorithm creates factors out of Bayes Nodes in reverse order and eliminates hidden variables using **sum_out**. Finally it takes a point wise product of all factors and normalizes. Let us finally solve the problem of inferring

**P(Burglary=True | JohnCalls=True, MaryCalls=True)** using variable elimination.

```
In [ ]:
```%psource elimination_ask

```
In [ ]:
```elimination_ask('Burglary', dict(JohnCalls=True, MaryCalls=True), burglary).show_approx()

```
In [ ]:
```%psource BayesNode.sample

Before we consider the different algorithms in this section let us look at the **BayesNode.sample** method. It samples from the distribution for this variable conditioned on event's values for parent_variables. That is, return True/False at random according to with the conditional probability given the parents. The **probability** function is a simple helper from **utils** module which returns True with the probability passed to it.

The idea of Prior Sampling is to sample from the Bayesian Network in a topological order. We start at the top of the network and sample as per **P(X _{i} | parents(X_{i})** i.e. the probability distribution from which the value is sampled is conditioned on the values already assigned to the variable's parents. This can be thought of as a simulation.

```
In [ ]:
```%psource prior_sample

The function **prior_sample** implements the algorithm described in **Figure 14.13** of the book. Nodes are sampled in the topological order. The old value of the event is passed as evidence for parent values. We will use the Bayesian Network in **Figure 14.12** to try out the **prior_sample**

We store the samples on the observations. Let us find **P(Rain=True)**

```
In [ ]:
```N = 1000
all_observations = [prior_sample(sprinkler) for x in range(N)]

Now we filter to get the observations where Rain = True

```
In [ ]:
```rain_true = [observation for observation in all_observations if observation['Rain'] == True]

Finally, we can find **P(Rain=True)**

```
In [ ]:
```answer = len(rain_true) / N
print(answer)

**P(Cloudy=True | Rain=True)**. We have already filtered out the values consistent with our evidence in **rain_true**. Now we apply a second filtering step on **rain_true** to find **P(Rain=True and Cloudy=True)**

```
In [ ]:
```rain_and_cloudy = [observation for observation in rain_true if observation['Cloudy'] == True]
answer = len(rain_and_cloudy) / len(rain_true)
print(answer)

Rejection Sampling is based on an idea similar to what we did just now. First, it generates samples from the prior distribution specified by the network. Then, it rejects all those that do not match the evidence. The function **rejection_sampling** implements the algorithm described by **Figure 14.14**

```
In [ ]:
```%psource rejection_sampling

The function keeps counts of each of the possible values of the Query variable and increases the count when we see an observation consistent with the evidence. It takes in input parameters **X** - The Query Variable, **e** - evidence, **bn** - Bayes net and **N** - number of prior samples to generate.

**consistent_with** is used to check consistency.

```
In [ ]:
```%psource consistent_with

To answer **P(Cloudy=True | Rain=True)**

```
In [ ]:
```p = rejection_sampling('Cloudy', dict(Rain=True), sprinkler, 1000)
p[True]

Rejection sampling tends to reject a lot of samples if our evidence consists of a large number of variables. Likelihood Weighting solves this by fixing the evidence (i.e. not sampling it) and then using weights to make sure that our overall sampling is still consistent.

The pseudocode in **Figure 14.15** is implemented as **likelihood_weighting** and **weighted_sample**.

```
In [ ]:
```%psource weighted_sample

**weighted_sample** samples an event from Bayesian Network that's consistent with the evidence **e** and returns the event and its weight, the likelihood that the event accords to the evidence. It takes in two parameters **bn** the Bayesian Network and **e** the evidence.

The weight is obtained by multiplying **P(x _{i} | parents(x_{i}))** for each node in evidence. We set the values of

```
In [ ]:
```weighted_sample(sprinkler, dict(Rain=True))

```
In [ ]:
```%psource likelihood_weighting

**likelihood_weighting** implements the algorithm to solve our inference problem. The code is similar to **rejection_sampling** but instead of adding one for each sample we add the weight obtained from **weighted_sampling**.

```
In [ ]:
```likelihood_weighting('Cloudy', dict(Rain=True), sprinkler, 200).show_approx()

In likelihood sampling, it is possible to obtain low weights in cases where the evidence variables reside at the bottom of the Bayesian Network. This can happen because influence only propagates downwards in likelihood sampling.

Gibbs Sampling solves this. The implementation of **Figure 14.16** is provided in the function **gibbs_ask**

```
In [ ]:
```%psource gibbs_ask

**gibbs_ask** we initialize the non-evidence variables to random values. And then select non-evidence variables and sample it from **P(Variable | value in the current state of all remaining vars) ** repeatedly sample. In practice, we speed this up by using **markov_blanket_sample** instead. This works because terms not involving the variable get canceled in the calculation. The arguments for **gibbs_ask** are similar to **likelihood_weighting**

```
In [ ]:
```gibbs_ask('Cloudy', dict(Rain=True), sprinkler, 200).show_approx()