Newer
Older
"source": [
"# Probability \n",
"\n",
"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."
]
},
"execution_count": 3,
"from probability import *\n",
"from notebook import *"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Probability Distribution\n",
"\n",
"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 **_ _setitem_ _** which store the probabilities in the prob dict of the object. You can keep the source window open alongside while playing with the rest of the code to get a better understanding."
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%psource ProbDist"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.75"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"p = ProbDist('Flip')\n",
"p['H'], p['T'] = 0.25, 0.75\n",
"p['T']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first parameter of the constructor **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."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'?'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"p = ProbDist(freqs={'low': 125, 'medium': 375, 'high': 500})\n",
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(0.125, 0.375, 0.5)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(p['low'], p['medium'], p['high'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Besides the **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."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['high', 'medium', 'low']"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"p.values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The distribution by default is not normalized if values are added incremently. We can still force normalization by invoking the **normalize** method."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(50, 114, 64)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"p = ProbDist('Y')\n",
"p['Cat'] = 50\n",
"p['Dog'] = 114\n",
"p['Mice'] = 64\n",
"(p['Cat'], p['Dog'], p['Mice'])"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(0.21929824561403508, 0.5, 0.2807017543859649)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"p.normalize()\n",
"(p['Cat'], p['Dog'], p['Mice'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is also possible to display the approximate values upto decimals using the **show_approx** method."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Cat: 0.219, Dog: 0.5, Mice: 0.281'"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"p.show_approx()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Joint Probability Distribution\n",
"\n",
"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.\n",
"\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(8, 10)"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"event = {'A': 10, 'B': 9, 'C': 8}\n",
"variables = ['C', 'A']\n",
"event_values(event, variables)"
]
},
{
"cell_type": "markdown",
"metadata": {},
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"source": [
"_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. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%psource JointProbDist"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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).\n",
"\n",
"To specify a Joint distribution we first need an ordered list of variables."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"P(['X', 'Y'])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"variables = ['X', 'Y']\n",
"j = JointProbDist(variables)\n",
"j"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Like the **ProbDist** class **JointProbDist** also employes magic methods to assign probability to different values.\n",
"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 **_ _setitem_ _** does the required processing to make this work."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(0.2, 0.5)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"j[1,1] = 0.2\n",
"j[dict(X=0, Y=1)] = 0.5\n",
"\n",
"(j[1,1], j[0,1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is also possible to list all the values for a particular variable using the **values** method."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 0]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference Using Full Joint Distributions\n",
"\n",
"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.\n",
"\n",
"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.\n",
"\n",
"$$\\textbf{P}(X | \\textbf{e}) = α \\textbf{P}(X, \\textbf{e}) = α \\sum_{y} \\textbf{P}(X, \\textbf{e}, \\textbf{y})$$\n",
"\n",
"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**\n",
"\n",
"We will be using the same example as the book. Let us create the full joint distribution from **Figure 13.3**. "
]
},
{
"cell_type": "code",
"metadata": {
},
"outputs": [],
"source": [
"full_joint = JointProbDist(['Cavity', 'Toothache', 'Catch'])\n",
"full_joint[dict(Cavity=True, Toothache=True, Catch=True)] = 0.108\n",
"full_joint[dict(Cavity=True, Toothache=True, Catch=False)] = 0.012\n",
"full_joint[dict(Cavity=True, Toothache=False, Catch=True)] = 0.016\n",
"full_joint[dict(Cavity=True, Toothache=False, Catch=False)] = 0.064\n",
"full_joint[dict(Cavity=False, Toothache=True, Catch=True)] = 0.072\n",
"full_joint[dict(Cavity=False, Toothache=False, Catch=True)] = 0.144\n",
"full_joint[dict(Cavity=False, Toothache=True, Catch=False)] = 0.008\n",
"full_joint[dict(Cavity=False, Toothache=False, Catch=False)] = 0.576"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us now look at the **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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(enumerate_joint)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us assume we want to find **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."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.19999999999999998"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"evidence = dict(Toothache=True)\n",
"variables = ['Cavity', 'Catch'] # variables not part of evidence\n",
"ans1 = enumerate_joint(variables, evidence, full_joint)\n",
"ans1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can verify the result from our definition of the full joint distribution. We can use the same function to find more complex probabilities like **P(Cavity=True and Toothache=True)** "
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.12"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"evidence = dict(Cavity=True, Toothache=True)\n",
"variables = ['Catch'] # variables not part of evidence\n",
"ans2 = enumerate_joint(variables, evidence, full_joint)\n",
"ans2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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)}$$\n",
"\n",
"We have already calculated both the numerator and denominator."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.6"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ans2/ans1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We might be interested in the probability distribution of a particular variable conditioned on some evidence. This can involve doing calculations like above for each possible value of the variable. This has been implemented slightly differently using normalization in the function **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<sub>i</sub>**. This is followed by normalization of the obtained distribution."
]
},
{
"cell_type": "code",
"execution_count": 5,
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">enumerate_joint_ask</span><span class=\"p\">(</span><span class=\"n\">X</span><span class=\"p\">,</span> <span class=\"n\">e</span><span class=\"p\">,</span> <span class=\"n\">P</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Return a probability distribution over the values of the variable X,</span>\n",
"<span class=\"sd\"> given the {var:val} observations e, in the JointProbDist P. [Section 13.3]</span>\n",
"<span class=\"sd\"> >>> P = JointProbDist(['X', 'Y'])</span>\n",
"<span class=\"sd\"> >>> P[0,0] = 0.25; P[0,1] = 0.5; P[1,1] = P[2,1] = 0.125</span>\n",
"<span class=\"sd\"> >>> enumerate_joint_ask('X', dict(Y=1), P).show_approx()</span>\n",
"<span class=\"sd\"> '0: 0.667, 1: 0.167, 2: 0.167'</span>\n",
"<span class=\"sd\"> """</span>\n",
" <span class=\"k\">assert</span> <span class=\"n\">X</span> <span class=\"ow\">not</span> <span class=\"ow\">in</span> <span class=\"n\">e</span><span class=\"p\">,</span> <span class=\"s2\">"Query variable must be distinct from evidence"</span>\n",
" <span class=\"n\">Q</span> <span class=\"o\">=</span> <span class=\"n\">ProbDist</span><span class=\"p\">(</span><span class=\"n\">X</span><span class=\"p\">)</span> <span class=\"c1\"># probability distribution for X, initially empty</span>\n",
" <span class=\"n\">Y</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"n\">v</span> <span class=\"k\">for</span> <span class=\"n\">v</span> <span class=\"ow\">in</span> <span class=\"n\">P</span><span class=\"o\">.</span><span class=\"n\">variables</span> <span class=\"k\">if</span> <span class=\"n\">v</span> <span class=\"o\">!=</span> <span class=\"n\">X</span> <span class=\"ow\">and</span> <span class=\"n\">v</span> <span class=\"ow\">not</span> <span class=\"ow\">in</span> <span class=\"n\">e</span><span class=\"p\">]</span> <span class=\"c1\"># hidden variables.</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">xi</span> <span class=\"ow\">in</span> <span class=\"n\">P</span><span class=\"o\">.</span><span class=\"n\">values</span><span class=\"p\">(</span><span class=\"n\">X</span><span class=\"p\">):</span>\n",
" <span class=\"n\">Q</span><span class=\"p\">[</span><span class=\"n\">xi</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"n\">enumerate_joint</span><span class=\"p\">(</span><span class=\"n\">Y</span><span class=\"p\">,</span> <span class=\"n\">extend</span><span class=\"p\">(</span><span class=\"n\">e</span><span class=\"p\">,</span> <span class=\"n\">X</span><span class=\"p\">,</span> <span class=\"n\">xi</span><span class=\"p\">),</span> <span class=\"n\">P</span><span class=\"p\">)</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">Q</span><span class=\"o\">.</span><span class=\"n\">normalize</span><span class=\"p\">()</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"psource(enumerate_joint_ask)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us find **P(Cavity | Toothache=True)** using **enumerate_joint_ask**."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(0.6, 0.39999999999999997)"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"query_variable = 'Cavity'\n",
"evidence = dict(Toothache=True)\n",
"ans = enumerate_joint_ask(query_variable, evidence, full_joint)\n",
"(ans[True], ans[False])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can verify that the first value is the same as we obtained earlier by manual calculation."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Bayesian Networks\n",
"\n",
"A Bayesian network is a representation of the joint probability distribution encoding a collection of conditional independence statements.\n",
"\n",
"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)**.\n",
"\n",
"Let us dive into the **BayesNode** implementation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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).\n",
"\n",
"The example below where we implement the network shown in **Figure 14.3** of the book will make this more clear.\n",
"\n",
"<img src=\"files/images/bayesnet.png\">\n",
"\n",
"The alarm node can be made as follows: "
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"alarm_node = BayesNode('Alarm', ['Burglary', 'Earthquake'], \n",
" {(True, True): 0.95,(True, False): 0.94, (False, True): 0.29, (False, False): 0.001})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is possible to avoid using a tuple when there is only a single parent. So an alternative format for the **cpt** is"
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"john_node = BayesNode('JohnCalls', ['Alarm'], {True: 0.90, False: 0.05})\n",
"mary_node = BayesNode('MaryCalls', 'Alarm', {(True, ): 0.70, (False, ): 0.01}) # Using string for parents.\n",
"# Equivalant to john_node definition."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The general format used for the alarm node always holds. For nodes with no parents we can also use. "
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"burglary_node = BayesNode('Burglary', '', 0.001)\n",
"earthquake_node = BayesNode('Earthquake', '', 0.002)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is possible to use the node for lookup function using the **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.)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.09999999999999998"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"john_node.p(False, {'Alarm': True, 'Burglary': True}) # P(JohnCalls=False | Alarm=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With all the information about nodes present it is possible to construct a Bayes Network using **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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"**burglary** global is an instance of **BayesNet** corresponding to the above example.\n",
"\n",
" T, F = True, False\n",
"\n",
" burglary = BayesNet([\n",
" ('Burglary', '', 0.001),\n",
" ('Earthquake', '', 0.002),\n",
" ('Alarm', 'Burglary Earthquake',\n",
" {(T, T): 0.95, (T, F): 0.94, (F, T): 0.29, (F, F): 0.001}),\n",
" ('JohnCalls', 'Alarm', {T: 0.90, F: 0.05}),\n",
" ('MaryCalls', 'Alarm', {T: 0.70, F: 0.01})\n",
" ])"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"BayesNet([('Burglary', ''), ('Earthquake', ''), ('Alarm', 'Burglary Earthquake'), ('JohnCalls', 'Alarm'), ('MaryCalls', 'Alarm')])"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"burglary"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**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."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"probability.BayesNode"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(burglary.variable_node('Alarm'))"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{(False, False): 0.001,\n",
" (False, True): 0.29,\n",
" (True, False): 0.94,\n",
" (True, True): 0.95}"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"burglary.variable_node('Alarm').cpt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exact Inference in Bayesian Networks\n",
"\n",
"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.\n",
"\n",
"Exact algorithms don't scale well for larger networks. Approximate algorithms are explained in the next section.\n",
"\n",
"### Inference by Enumeration\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": true
},
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**enumerate__all** recursively evaluates a general form of the **Equation 14.4** in the book.\n",
"\n",
"$$\\textbf{P}(X | \\textbf{e}) = α \\textbf{P}(X, \\textbf{e}) = α \\sum_{y} \\textbf{P}(X, \\textbf{e}, \\textbf{y})$$ \n",
"\n",
"such that **P(X, e, y)** is written in the form of product of conditional probabilities **P(variable | parents(variable))** from the Bayesian Network.\n",
"\n",
"**enumeration_ask** calls **enumerate_all** on each value of query variable **X** and finally normalizes them. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(enumeration_ask)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us solve the problem of finding out **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."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.2841718353643929"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ans_dist = enumeration_ask('Burglary', {'JohnCalls': True, 'MaryCalls': True}, burglary)\n",
"ans_dist[True]"
]
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Variable Elimination\n",
"\n",
"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.\n",
"\n",
"Before we look into the implementation of Variable Elimination we must first familiarize ourselves with Factors. \n",
"\n",
"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**. \n",
"\n",
"\n",
"#### Helper Functions\n",
"\n",
"There are certain helper functions that help creating the **cpt** for the Factor given the evidence. Let us explore them one by one."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**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.\n",
"\n",
"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.\n",
"\n",
"The **cpt** created is the one similar to the original **cpt** of the node with only rows that agree with the evidence."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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. \n",
"\n",
"We can try this out using the example on **Page 524** of the book. We will make **f**<sub>5</sub>(A) = P(m | A)"
]
},
{
"cell_type": "code",
},
"outputs": [],
"source": [
"f5 = make_factor('MaryCalls', {'JohnCalls': True, 'MaryCalls': True}, burglary)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<probability.Factor at 0x7f4b1a69b080>"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f5"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{(False,): 0.01, (True,): 0.7}"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f5.cpt"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Alarm']"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f5.variables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here **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"
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"new_factor = make_factor('MaryCalls', {'Alarm': True}, burglary)"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{(False,): 0.30000000000000004, (True,): 0.7}"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"new_factor.cpt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"#### Operations on Factors\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(Factor.pointwise_product)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(pointwise_product)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**pointwise_product** extends this operation to more than two operands where it is done sequentially in pairs of two."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(Factor.sum_out)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**sum_out** uses both **Factor.sum_out** and **pointwise_product** to finally eliminate a particular variable from all factors by summing over its values."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Elimination Ask\n",
"\n",
"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. \n",
"\n",
"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 \n",
"\n",
"**P(Burglary=True | JohnCalls=True, MaryCalls=True)** using variable elimination."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(elimination_ask)"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'False: 0.716, True: 0.284'"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"elimination_ask('Burglary', dict(JohnCalls=True, MaryCalls=True), burglary).show_approx()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Approximate Inference in Bayesian Networks\n",
"\n",
"Exact inference fails to scale for very large and complex Bayesian Networks. This section covers implementation of randomized sampling algorithms, also called Monte Carlo algorithms."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
},
"outputs": [],
"source": [
"psource(BayesNode.sample)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"### Prior Sampling\n",
"\n",
"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<sub>i</sub> | parents(X<sub>i</sub>)** 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."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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**\n",
"\n",
"<img src=\"files/images/sprinklernet.jpg\" height=\"500\" width=\"500\">\n",
"\n",
"We store the samples on the observations. Let us find **P(Rain=True)**"
]
},
{
"cell_type": "code",
},
"outputs": [],
"source": [
"N = 1000\n",
"all_observations = [prior_sample(sprinkler) for x in range(N)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we filter to get the observations where Rain = True"
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"rain_true = [observation for observation in all_observations if observation['Rain'] == True]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, we can find **P(Rain=True)**"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.508\n"
]
}
],
"source": [
"answer = len(rain_true) / N\n",
"print(answer)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To evaluate a conditional distribution. We can use a two-step filtering process. We first separate out the variables that are consistent with the evidence. Then for each value of query variable, we can find probabilities. For example to find **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)**"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.7755905511811023\n"
]
}
],
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
"source": [
"rain_and_cloudy = [observation for observation in rain_true if observation['Cloudy'] == True]\n",
"answer = len(rain_and_cloudy) / len(rain_true)\n",
"print(answer)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Rejection Sampling\n",
"\n",
"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**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(rejection_sampling)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"**consistent_with** is used to check consistency."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(consistent_with)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To answer **P(Cloudy=True | Rain=True)**"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.7835249042145593"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
"source": [
"p = rejection_sampling('Cloudy', dict(Rain=True), sprinkler, 1000)\n",
"p[True]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Likelihood Weighting\n",
"\n",
"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.\n",
"\n",
"The pseudocode in **Figure 14.15** is implemented as **likelihood_weighting** and **weighted_sample**."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(weighted_sample)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**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.\n",
"\n",
"The weight is obtained by multiplying **P(x<sub>i</sub> | parents(x<sub>i</sub>))** for each node in evidence. We set the values of **event = evidence** at the start of the function."
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"({'Cloudy': True, 'Rain': True, 'Sprinkler': False, 'WetGrass': True}, 0.8)"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"weighted_sample(sprinkler, dict(Rain=True))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(likelihood_weighting)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**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**."
]
},
{
"cell_type": "markdown",
"source": [
"likelihood_weighting('Cloudy', dict(Rain=True), sprinkler, 200).show_approx()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Gibbs Sampling\n",
"\n",
"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.\n",
"\n",
"Gibbs Sampling solves this. The implementation of **Figure 14.16** is provided in the function **gibbs_ask** "
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In **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**"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'False: 0.17, True: 0.83'"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gibbs_ask('Cloudy', dict(Rain=True), sprinkler, 200).show_approx()"
]
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference in Temporal Models"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before we start, it will be helpful to understand the structure of a temporal model. We will use the example of the book with the guard and the umbrella. In this example, the state $\\textbf{X}$ is whether it is a rainy day (`X = True`) or not (`X = False`) at Day $\\textbf{t}$. In the sensor or observation model, the observation or evidence $\\textbf{U}$ is whether the professor holds an umbrella (`U = True`) or not (`U = False`) on **Day** $\\textbf{t}$. Based on that, the transition model is \n",
"\n",
"| $X_{t-1}$ | $X_{t}$ | **P**$(X_{t}| X_{t-1})$| \n",
"| ------------- |------------- | ----------------------------------|\n",
"| ***${False}$*** | ***${False}$*** | 0.7 |\n",
"| ***${False}$*** | ***${True}$*** | 0.3 |\n",
"| ***${True}$*** | ***${False}$*** | 0.3 |\n",
"| ***${True}$*** | ***${True}$*** | 0.7 |\n",
"\n",
"And the the sensor model will be,\n",
"\n",
"| $X_{t}$ | $U_{t}$ | **P**$(U_{t}|X_{t})$| \n",
"| :-------------: |:-------------: | :------------------------:|\n",
"| ***${False}$*** | ***${True}$*** | 0.2 |\n",
"| ***${False}$*** | ***${False}$*** | 0.8 |\n",
"| ***${True}$*** | ***${True}$*** | 0.9 |\n",
"| ***${True}$*** | ***${False}$*** | 0.1 |\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the filtering task we are given evidence **U** in each time **t** and we want to compute the belief $B_{t}(x)= P(X_{t}|U_{1:t})$. \n",
"We can think of it as a three step process:\n",
"1. In every step we start with the current belief $P(X_{t}|e_{1:t})$\n",
"2. We update it for time\n",
"3. We update it for evidence\n",
"\n",
"The forward algorithm performs the step 2 and 3 at once. It updates, or better say reweights, the initial belief using the transition and the sensor model. Let's see the umbrella example. On **Day 0** no observation is available, and for that reason we will assume that we have equal possibilities to rain or not. In the **`HiddenMarkovModel`** class, the prior probabilities for **Day 0** are by default [0.5, 0.5]. "
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%psource HiddenMarkovModel"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We instantiate the object **`hmm`** of the class using a list of lists for both the transition and the sensor model."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
"outputs": [],
"source": [
"umbrella_transition_model = [[0.7, 0.3], [0.3, 0.7]]\n",
"umbrella_sensor_model = [[0.9, 0.2], [0.1, 0.8]]\n",
"hmm = HiddenMarkovModel(umbrella_transition_model, umbrella_sensor_model)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **`sensor_dist()`** method returns a list with the conditional probabilities of the sensor model."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0.9, 0.2]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"hmm.sensor_dist(ev=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The observation update is calculated with the **`forward()`** function. Basically, we update our belief using the observation model. The function returns a list with the probabilities of **raining or not** on **Day 1**."
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": true
},
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
"outputs": [],
"source": [
"psource(forward)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The probability of raining on day 1 is 0.82\n"
]
}
],
"source": [
"belief_day_1 = forward(hmm, umbrella_prior, ev=True)\n",
"print ('The probability of raining on day 1 is {:.2f}'.format(belief_day_1[0]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In **Day 2** our initial belief is the updated belief of **Day 1**. Again using the **`forward()`** function we can compute the probability of raining in **Day 2**"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The probability of raining in day 2 is 0.88\n"
]
}
],
"source": [
"belief_day_2 = forward(hmm, belief_day_1, ev=True)\n",
"print ('The probability of raining in day 2 is {:.2f}'.format(belief_day_2[0]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the smoothing part we are interested in computing the distribution over past states given evidence up to the present. Assume that we want to compute the distribution for the time **k**, for $0\\leq k<t $, the computation can be divided in two parts: \n",
"1. The forward message will be computed till and by filtering forward from 1 to **k**.\n",
"2. The backward message can be computed by a recusive process that runs from **k** to **t**. \n",
"\n",
"Rather than starting at time 1, the algorithm starts at time **t**. In the umbrella example, we can compute the backward message from **Day 2** to **Day 1** by using the `backward` function. The `backward` function has as parameters the object created by the **`HiddenMarkovModel`** class, the evidence in **Day 2** (in our case is **True**), and the initial probabilities of being in state in time t+1. Since no observation is available then it will be [1, 1]. The `backward` function will return a list with the conditional probabilities."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": true
},
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
"outputs": [],
"source": [
"psource(backward)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0.6272727272727272, 0.37272727272727274]"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b = [1, 1]\n",
"backward(hmm, b, ev=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some may notice that the result is not the same as in the book. The main reason is that in the book the normalization step is not used. If we want to normalize the result, one can use the **`normalize()`** helper function.\n",
"\n",
"In order to find the smoothed estimate for raining in **Day k**, we will use the **`forward_backward()`** function. As in the example in the book, the umbrella is observed in both days and the prior distribution is [0.5, 0.5]"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"collapsed": true
},
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
"outputs": [],
"source": [
"pseudocode('Forward-Backward')"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The probability of raining in Day 0 is 0.65 and in Day 1 is 0.88\n"
]
}
],
"source": [
"umbrella_prior = [0.5, 0.5]\n",
"prob = forward_backward(hmm, ev=[T, T], prior=umbrella_prior)\n",
"print ('The probability of raining in Day 0 is {:.2f} and in Day 1 is {:.2f}'.format(prob[0][0], prob[1][0]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
}
},
"nbformat": 4,
"nbformat_minor": 2