Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
"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"
],
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
"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": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(0.6, 0.39999999999999997)"
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"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",
"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",
"A Bayesian network is a representation of the joint probability distribution encoding a collection of conditional independence statements.\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",
"Let us dive into the **BayesNode** implementation."
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
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
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
"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\">class</span> <span class=\"nc\">BayesNode</span><span class=\"p\">:</span>\n",
" <span class=\"sd\">"""A conditional probability distribution for a boolean variable,</span>\n",
"<span class=\"sd\"> P(X | parents). Part of a BayesNet."""</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">X</span><span class=\"p\">,</span> <span class=\"n\">parents</span><span class=\"p\">,</span> <span class=\"n\">cpt</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""X is a variable name, and parents a sequence of variable</span>\n",
"<span class=\"sd\"> names or a space-separated string. cpt, the conditional</span>\n",
"<span class=\"sd\"> probability table, takes one of these forms:</span>\n",
"\n",
"<span class=\"sd\"> * A number, the unconditional probability P(X=true). You can</span>\n",
"<span class=\"sd\"> use this form when there are no parents.</span>\n",
"\n",
"<span class=\"sd\"> * A dict {v: p, ...}, the conditional probability distribution</span>\n",
"<span class=\"sd\"> P(X=true | parent=v) = p. When there's just one parent.</span>\n",
"\n",
"<span class=\"sd\"> * A dict {(v1, v2, ...): p, ...}, the distribution P(X=true |</span>\n",
"<span class=\"sd\"> parent1=v1, parent2=v2, ...) = p. Each key must have as many</span>\n",
"<span class=\"sd\"> values as there are parents. You can use this form always;</span>\n",
"<span class=\"sd\"> the first two are just conveniences.</span>\n",
"\n",
"<span class=\"sd\"> In all cases the probability of X being false is left implicit,</span>\n",
"<span class=\"sd\"> since it follows from P(X=true).</span>\n",
"\n",
"<span class=\"sd\"> >>> X = BayesNode('X', '', 0.2)</span>\n",
"<span class=\"sd\"> >>> Y = BayesNode('Y', 'P', {T: 0.2, F: 0.7})</span>\n",
"<span class=\"sd\"> >>> Z = BayesNode('Z', 'P Q',</span>\n",
"<span class=\"sd\"> ... {(T, T): 0.2, (T, F): 0.3, (F, T): 0.5, (F, F): 0.7})</span>\n",
"<span class=\"sd\"> """</span>\n",
" <span class=\"k\">if</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">parents</span><span class=\"p\">,</span> <span class=\"nb\">str</span><span class=\"p\">):</span>\n",
" <span class=\"n\">parents</span> <span class=\"o\">=</span> <span class=\"n\">parents</span><span class=\"o\">.</span><span class=\"n\">split</span><span class=\"p\">()</span>\n",
"\n",
" <span class=\"c1\"># We store the table always in the third form above.</span>\n",
" <span class=\"k\">if</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">cpt</span><span class=\"p\">,</span> <span class=\"p\">(</span><span class=\"nb\">float</span><span class=\"p\">,</span> <span class=\"nb\">int</span><span class=\"p\">)):</span> <span class=\"c1\"># no parents, 0-tuple</span>\n",
" <span class=\"n\">cpt</span> <span class=\"o\">=</span> <span class=\"p\">{():</span> <span class=\"n\">cpt</span><span class=\"p\">}</span>\n",
" <span class=\"k\">elif</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">cpt</span><span class=\"p\">,</span> <span class=\"nb\">dict</span><span class=\"p\">):</span>\n",
" <span class=\"c1\"># one parent, 1-tuple</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">cpt</span> <span class=\"ow\">and</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"n\">cpt</span><span class=\"o\">.</span><span class=\"n\">keys</span><span class=\"p\">())[</span><span class=\"mi\">0</span><span class=\"p\">],</span> <span class=\"nb\">bool</span><span class=\"p\">):</span>\n",
" <span class=\"n\">cpt</span> <span class=\"o\">=</span> <span class=\"p\">{(</span><span class=\"n\">v</span><span class=\"p\">,):</span> <span class=\"n\">p</span> <span class=\"k\">for</span> <span class=\"n\">v</span><span class=\"p\">,</span> <span class=\"n\">p</span> <span class=\"ow\">in</span> <span class=\"n\">cpt</span><span class=\"o\">.</span><span class=\"n\">items</span><span class=\"p\">()}</span>\n",
"\n",
" <span class=\"k\">assert</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">cpt</span><span class=\"p\">,</span> <span class=\"nb\">dict</span><span class=\"p\">)</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">vs</span><span class=\"p\">,</span> <span class=\"n\">p</span> <span class=\"ow\">in</span> <span class=\"n\">cpt</span><span class=\"o\">.</span><span class=\"n\">items</span><span class=\"p\">():</span>\n",
" <span class=\"k\">assert</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">vs</span><span class=\"p\">,</span> <span class=\"nb\">tuple</span><span class=\"p\">)</span> <span class=\"ow\">and</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">vs</span><span class=\"p\">)</span> <span class=\"o\">==</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">parents</span><span class=\"p\">)</span>\n",
" <span class=\"k\">assert</span> <span class=\"nb\">all</span><span class=\"p\">(</span><span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">v</span><span class=\"p\">,</span> <span class=\"nb\">bool</span><span class=\"p\">)</span> <span class=\"k\">for</span> <span class=\"n\">v</span> <span class=\"ow\">in</span> <span class=\"n\">vs</span><span class=\"p\">)</span>\n",
" <span class=\"k\">assert</span> <span class=\"mi\">0</span> <span class=\"o\"><=</span> <span class=\"n\">p</span> <span class=\"o\"><=</span> <span class=\"mi\">1</span>\n",
"\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">variable</span> <span class=\"o\">=</span> <span class=\"n\">X</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">parents</span> <span class=\"o\">=</span> <span class=\"n\">parents</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">cpt</span> <span class=\"o\">=</span> <span class=\"n\">cpt</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">children</span> <span class=\"o\">=</span> <span class=\"p\">[]</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">p</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">value</span><span class=\"p\">,</span> <span class=\"n\">event</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Return the conditional probability</span>\n",
"<span class=\"sd\"> P(X=value | parents=parent_values), where parent_values</span>\n",
"<span class=\"sd\"> are the values of parents in event. (event must assign each</span>\n",
"<span class=\"sd\"> parent a value.)</span>\n",
"<span class=\"sd\"> >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625})</span>\n",
"<span class=\"sd\"> >>> bn.p(False, {'Burglary': False, 'Earthquake': True})</span>\n",
"<span class=\"sd\"> 0.375"""</span>\n",
" <span class=\"k\">assert</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">value</span><span class=\"p\">,</span> <span class=\"nb\">bool</span><span class=\"p\">)</span>\n",
" <span class=\"n\">ptrue</span> <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">cpt</span><span class=\"p\">[</span><span class=\"n\">event_values</span><span class=\"p\">(</span><span class=\"n\">event</span><span class=\"p\">,</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">parents</span><span class=\"p\">)]</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">ptrue</span> <span class=\"k\">if</span> <span class=\"n\">value</span> <span class=\"k\">else</span> <span class=\"mi\">1</span> <span class=\"o\">-</span> <span class=\"n\">ptrue</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">sample</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">event</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Sample from the distribution for this variable conditioned</span>\n",
"<span class=\"sd\"> on event's values for parent_variables. That is, return True/False</span>\n",
"<span class=\"sd\"> at random according with the conditional probability given the</span>\n",
"<span class=\"sd\"> parents."""</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">probability</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">p</span><span class=\"p\">(</span><span class=\"bp\">True</span><span class=\"p\">,</span> <span class=\"n\">event</span><span class=\"p\">))</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"fm\">__repr__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"nb\">repr</span><span class=\"p\">((</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">variable</span><span class=\"p\">,</span> <span class=\"s1\">' '</span><span class=\"o\">.</span><span class=\"n\">join</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">parents</span><span class=\"p\">)))</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
"psource(BayesNode)"
},
{
"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",
"The example below where we implement the network shown in **Figure 14.3** of the book will make this more clear.\n",
"<img src=\"files/images/bayesnet.png\">\n",
"The alarm node can be made as follows: "
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"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",
"execution_count": 24,
"metadata": {},
"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",
"execution_count": 25,
"outputs": [],
"burglary_node = BayesNode('Burglary', '', 0.001)\n",
"earthquake_node = BayesNode('Earthquake', '', 0.002)"
"cell_type": "markdown",
"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": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.09999999999999998"
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"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": 27,
"metadata": {},
"outputs": [
{
"data": {
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
"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\">class</span> <span class=\"nc\">BayesNet</span><span class=\"p\">:</span>\n",
" <span class=\"sd\">"""Bayesian network containing only boolean-variable nodes."""</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">node_specs</span><span class=\"o\">=</span><span class=\"bp\">None</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Nodes must be ordered with parents before children."""</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">nodes</span> <span class=\"o\">=</span> <span class=\"p\">[]</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">variables</span> <span class=\"o\">=</span> <span class=\"p\">[]</span>\n",
" <span class=\"n\">node_specs</span> <span class=\"o\">=</span> <span class=\"n\">node_specs</span> <span class=\"ow\">or</span> <span class=\"p\">[]</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">node_spec</span> <span class=\"ow\">in</span> <span class=\"n\">node_specs</span><span class=\"p\">:</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">add</span><span class=\"p\">(</span><span class=\"n\">node_spec</span><span class=\"p\">)</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">add</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">node_spec</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Add a node to the net. Its parents must already be in the</span>\n",
"<span class=\"sd\"> net, and its variable must not."""</span>\n",
" <span class=\"n\">node</span> <span class=\"o\">=</span> <span class=\"n\">BayesNode</span><span class=\"p\">(</span><span class=\"o\">*</span><span class=\"n\">node_spec</span><span class=\"p\">)</span>\n",
" <span class=\"k\">assert</span> <span class=\"n\">node</span><span class=\"o\">.</span><span class=\"n\">variable</span> <span class=\"ow\">not</span> <span class=\"ow\">in</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">variables</span>\n",
" <span class=\"k\">assert</span> <span class=\"nb\">all</span><span class=\"p\">((</span><span class=\"n\">parent</span> <span class=\"ow\">in</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">variables</span><span class=\"p\">)</span> <span class=\"k\">for</span> <span class=\"n\">parent</span> <span class=\"ow\">in</span> <span class=\"n\">node</span><span class=\"o\">.</span><span class=\"n\">parents</span><span class=\"p\">)</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">nodes</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">node</span><span class=\"p\">)</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">variables</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">node</span><span class=\"o\">.</span><span class=\"n\">variable</span><span class=\"p\">)</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">parent</span> <span class=\"ow\">in</span> <span class=\"n\">node</span><span class=\"o\">.</span><span class=\"n\">parents</span><span class=\"p\">:</span>\n",
" <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">variable_node</span><span class=\"p\">(</span><span class=\"n\">parent</span><span class=\"p\">)</span><span class=\"o\">.</span><span class=\"n\">children</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">node</span><span class=\"p\">)</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">variable_node</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">var</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Return the node for the variable named var.</span>\n",
"<span class=\"sd\"> >>> burglary.variable_node('Burglary').variable</span>\n",
"<span class=\"sd\"> 'Burglary'"""</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">n</span> <span class=\"ow\">in</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">nodes</span><span class=\"p\">:</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">n</span><span class=\"o\">.</span><span class=\"n\">variable</span> <span class=\"o\">==</span> <span class=\"n\">var</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">n</span>\n",
" <span class=\"k\">raise</span> <span class=\"ne\">Exception</span><span class=\"p\">(</span><span class=\"s2\">"No such variable: {}"</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"n\">var</span><span class=\"p\">))</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">variable_values</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">var</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Return the domain of var."""</span>\n",
" <span class=\"k\">return</span> <span class=\"p\">[</span><span class=\"bp\">True</span><span class=\"p\">,</span> <span class=\"bp\">False</span><span class=\"p\">]</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"fm\">__repr__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"s1\">'BayesNet({0!r})'</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">nodes</span><span class=\"p\">)</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
"psource(BayesNet)"
]
},
{
"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",
"**burglary** global is an instance of **BayesNet** corresponding to the above example.\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": 28,
"outputs": [
{
"data": {
"text/plain": [
"BayesNet([('Burglary', ''), ('Earthquake', ''), ('Alarm', 'Burglary Earthquake'), ('JohnCalls', 'Alarm'), ('MaryCalls', 'Alarm')])"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"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": 29,
"outputs": [
{
"data": {
"text/plain": [
"probability.BayesNode"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"type(burglary.variable_node('Alarm'))"
]
},
{
"cell_type": "code",
"execution_count": 30,
"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": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"burglary.variable_node('Alarm').cpt"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exact Inference in Bayesian Networks\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": 31,
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
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
1709
1710
1711
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
1774
1775
1776
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
1815
1816
1817
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
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
"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_all</span><span class=\"p\">(</span><span class=\"n\">variables</span><span class=\"p\">,</span> <span class=\"n\">e</span><span class=\"p\">,</span> <span class=\"n\">bn</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Return the sum of those entries in P(variables | e{others})</span>\n",
"<span class=\"sd\"> consistent with e, where P is the joint distribution represented</span>\n",
"<span class=\"sd\"> by bn, and e{others} means e restricted to bn's other variables</span>\n",
"<span class=\"sd\"> (the ones other than variables). Parents must precede children in variables."""</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">variables</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"mf\">1.0</span>\n",
" <span class=\"n\">Y</span><span class=\"p\">,</span> <span class=\"n\">rest</span> <span class=\"o\">=</span> <span class=\"n\">variables</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">],</span> <span class=\"n\">variables</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">:]</span>\n",
" <span class=\"n\">Ynode</span> <span class=\"o\">=</span> <span class=\"n\">bn</span><span class=\"o\">.</span><span class=\"n\">variable_node</span><span class=\"p\">(</span><span class=\"n\">Y</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">Y</span> <span class=\"ow\">in</span> <span class=\"n\">e</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">Ynode</span><span class=\"o\">.</span><span class=\"n\">p</span><span class=\"p\">(</span><span class=\"n\">e</span><span class=\"p\">[</span><span class=\"n\">Y</span><span class=\"p\">],</span> <span class=\"n\">e</span><span class=\"p\">)</span> <span class=\"o\">*</span> <span class=\"n\">enumerate_all</span><span class=\"p\">(</span><span class=\"n\">rest</span><span class=\"p\">,</span> <span class=\"n\">e</span><span class=\"p\">,</span> <span class=\"n\">bn</span><span class=\"p\">)</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"nb\">sum</span><span class=\"p\">(</span><span class=\"n\">Ynode</span><span class=\"o\">.</span><span class=\"n\">p</span><span class=\"p\">(</span><span class=\"n\">y</span><span class=\"p\">,</span> <span class=\"n\">e</span><span class=\"p\">)</span> <span class=\"o\">*</span> <span class=\"n\">enumerate_all</span><span class=\"p\">(</span><span class=\"n\">rest</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\">Y</span><span class=\"p\">,</span> <span class=\"n\">y</span><span class=\"p\">),</span> <span class=\"n\">bn</span><span class=\"p\">)</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">y</span> <span class=\"ow\">in</span> <span class=\"n\">bn</span><span class=\"o\">.</span><span class=\"n\">variable_values</span><span class=\"p\">(</span><span class=\"n\">Y</span><span class=\"p\">))</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(enumerate_all)"
]
},
{
"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": 32,
"metadata": {},
"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\">enumeration_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\">bn</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Return the conditional probability distribution of variable X</span>\n",
"<span class=\"sd\"> given evidence e, from BayesNet bn. [Figure 14.9]</span>\n",
"<span class=\"sd\"> >>> enumeration_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary</span>\n",
"<span class=\"sd\"> ... ).show_approx()</span>\n",
"<span class=\"sd\"> 'False: 0.716, True: 0.284'"""</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>\n",
" <span class=\"k\">for</span> <span class=\"n\">xi</span> <span class=\"ow\">in</span> <span class=\"n\">bn</span><span class=\"o\">.</span><span class=\"n\">variable_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_all</span><span class=\"p\">(</span><span class=\"n\">bn</span><span class=\"o\">.</span><span class=\"n\">variables</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\">bn</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": "display_data"
}
],
"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": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.2841718353643929"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ans_dist = enumeration_ask('Burglary', {'JohnCalls': True, 'MaryCalls': True}, burglary)\n",
"ans_dist[True]"
]
},
{
"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": 34,
"metadata": {},
"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",