File size: 11,951 Bytes
93d7919
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inference in Discrete Bayesian Network"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook, we show a simple example for doing Exact inference in Bayesian Networks using pgmpy. We will be using the Asia network (http://www.bnlearn.com/bnrepository/#asia) for this example."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 1: Define the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Fetch the asia model from the bnlearn repository\n",
    "\n",
    "from pgmpy.utils import get_example_model\n",
    "\n",
    "asia_model = get_example_model(\"asia\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Nodes:  ['asia', 'tub', 'smoke', 'lung', 'bronc', 'either', 'xray', 'dysp']\n",
      "Edges:  [('asia', 'tub'), ('tub', 'either'), ('smoke', 'lung'), ('smoke', 'bronc'), ('lung', 'either'), ('bronc', 'dysp'), ('either', 'xray'), ('either', 'dysp')]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[<TabularCPD representing P(asia:2) at 0x7f08a40e6a90>,\n",
       " <TabularCPD representing P(bronc:2 | smoke:2) at 0x7f08a40e6dc0>,\n",
       " <TabularCPD representing P(dysp:2 | bronc:2, either:2) at 0x7f08a40fa730>,\n",
       " <TabularCPD representing P(either:2 | lung:2, tub:2) at 0x7f08a40fa100>,\n",
       " <TabularCPD representing P(lung:2 | smoke:2) at 0x7f08a40fa790>,\n",
       " <TabularCPD representing P(smoke:2) at 0x7f08a40fa5e0>,\n",
       " <TabularCPD representing P(tub:2 | asia:2) at 0x7f08a40fac40>,\n",
       " <TabularCPD representing P(xray:2 | either:2) at 0x7f08a40fab80>]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(\"Nodes: \", asia_model.nodes())\n",
    "print(\"Edges: \", asia_model.edges())\n",
    "asia_model.get_cpds()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you would like to create a model from scratch, please refer to the Creating Bayesian Networks notebook: https://github.com/pgmpy/pgmpy/blob/dev/examples/Creating%20a%20Bayesian%20Network.ipynb"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 2: Initialize the inference class"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Currently, pgmpy support two algorithms for inference: 1. Variable Elimination and, 2. Belief Propagation. Both of these are exact inference algorithms. The following example uses `VariableElimination` but `BeliefPropagation` has an identifcal API, so all the methods show below would also work for `BeliefPropagation`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initializing the VariableElimination class\n",
    "\n",
    "from pgmpy.inference import VariableElimination\n",
    "\n",
    "asia_infer = VariableElimination(asia_model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 3: Doing Inference using hard evidence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Finding Elimination Order: : : 0it [00:00, ?it/s]\n",
      "0it [00:00, ?it/s]\u001b[A\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\n",
      "Finding Elimination Order: : : 0it [00:00, ?it/s]\u001b[A\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\u001b[A\n",
      "\n",
      "Finding Elimination Order: : : 0it [00:00, ?it/s]\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+------------+--------------+\n",
      "| bronc      |   phi(bronc) |\n",
      "+============+==============+\n",
      "| bronc(yes) |       0.3000 |\n",
      "+------------+--------------+\n",
      "| bronc(no)  |       0.7000 |\n",
      "+------------+--------------+\n",
      "+------------+-----------+-------------------+\n",
      "| bronc      | asia      |   phi(bronc,asia) |\n",
      "+============+===========+===================+\n",
      "| bronc(yes) | asia(yes) |            0.0060 |\n",
      "+------------+-----------+-------------------+\n",
      "| bronc(yes) | asia(no)  |            0.5940 |\n",
      "+------------+-----------+-------------------+\n",
      "| bronc(no)  | asia(yes) |            0.0040 |\n",
      "+------------+-----------+-------------------+\n",
      "| bronc(no)  | asia(no)  |            0.3960 |\n",
      "+------------+-----------+-------------------+\n",
      "+------------+--------------+\n",
      "| bronc      |   phi(bronc) |\n",
      "+============+==============+\n",
      "| bronc(yes) |       0.3000 |\n",
      "+------------+--------------+\n",
      "| bronc(no)  |       0.7000 |\n",
      "+------------+--------------+\n",
      "+-----------+-------------+\n",
      "| asia      |   phi(asia) |\n",
      "+===========+=============+\n",
      "| asia(yes) |      0.0100 |\n",
      "+-----------+-------------+\n",
      "| asia(no)  |      0.9900 |\n",
      "+-----------+-------------+\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "# Computing the probability of bronc given smoke=no.\n",
    "q = asia_infer.query(variables=[\"bronc\"], evidence={\"smoke\": \"no\"})\n",
    "print(q)\n",
    "\n",
    "# Computing the joint probability of bronc and asia given smoke=yes\n",
    "q = asia_infer.query(variables=[\"bronc\", \"asia\"], evidence={\"smoke\": \"yes\"})\n",
    "print(q)\n",
    "\n",
    "# Computing the probabilities (not joint) of bronc and asia given smoke=no\n",
    "q = asia_infer.query(variables=[\"bronc\", \"asia\"], evidence={\"smoke\": \"no\"}, joint=False)\n",
    "for factor in q.values():\n",
    "    print(factor)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "Finding Elimination Order: : : 0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "\n",
      "Finding Elimination Order: : : 0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'bronc': 'no'}\n",
      "{'bronc': 'yes', 'asia': 'no'}\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "# Computing the MAP of bronc given smoke=no.\n",
    "q = asia_infer.map_query(variables=[\"bronc\"], evidence={\"smoke\": \"no\"})\n",
    "print(q)\n",
    "\n",
    "# Computing the MAP of bronc and asia given smoke=yes\n",
    "q = asia_infer.map_query(variables=[\"bronc\", \"asia\"], evidence={\"smoke\": \"yes\"})\n",
    "print(q)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 5: Inference using virtual evidence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Finding Elimination Order: : : 0it [00:04, ?it/s]\n",
      "Finding Elimination Order: : : 0it [00:04, ?it/s]\n",
      "Finding Elimination Order: : : 0it [00:02, ?it/s]\n",
      "Finding Elimination Order: : : 0it [00:02, ?it/s]\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\n",
      "Finding Elimination Order: : : 0it [00:00, ?it/s]\u001b[A\n",
      "\n",
      "0it [00:00, ?it/s]\u001b[A\u001b[A"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+------------+--------------+\n",
      "| bronc      |   phi(bronc) |\n",
      "+============+==============+\n",
      "| bronc(yes) |       0.3000 |\n",
      "+------------+--------------+\n",
      "| bronc(no)  |       0.7000 |\n",
      "+------------+--------------+\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from pgmpy.factors.discrete import TabularCPD\n",
    "\n",
    "# Get state name, which ensure lung evidence has same state names as asia_model\n",
    "state_names = asia_model.get_cpds('lung').state_names\n",
    "\n",
    "lung_virt_evidence = TabularCPD(variable=\"lung\", variable_card=2, values=[[0.4], [0.6]],state_names=state_names)\n",
    "\n",
    "# Query with hard evidence smoke = no and virtual evidence lung = [0.4, 0.6]\n",
    "q = asia_infer.query(\n",
    "    variables=[\"bronc\"], evidence={\"smoke\": \"no\"}, virtual_evidence=[lung_virt_evidence]\n",
    ")\n",
    "print(q)\n",
    "\n",
    "# Query with hard evidence smoke = no and virtual evidences lung = [0.4, 0.6] and bronc = [0.3, 0.7]\n",
    "lung_virt_evidence = TabularCPD(variable=\"lung\", variable_card=2, values=[[0.4], [0.7]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+-----------+------------+-----------+\n",
      "| smoke     | smoke(yes) | smoke(no) |\n",
      "+-----------+------------+-----------+\n",
      "| lung(yes) | 0.1        | 0.01      |\n",
      "+-----------+------------+-----------+\n",
      "| lung(no)  | 0.9        | 0.99      |\n",
      "+-----------+------------+-----------+\n"
     ]
    }
   ],
   "source": [
    "print(asia_model.get_cpds(\"lung\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 4: Troubleshooting for slow inference"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the case of large models, or models in which variables have a lot of states, inference can be quite slow. Some of the ways to deal with it are:\n",
    "\n",
    "1. Reduce the number of states of variables by combining states together.\n",
    "2. Try a different elimination order by specifying `elimination_order` argument. Possible options are: MinFill, MinNeighbors, MinWeight, WeightedMinFill. \n",
    "3. Try a custom elimination order: The implemented heuristics for computing the elimination order might not be efficient in every case. If you can think of a more efficient order, you can also pass it as a list to the `elimination_order` argument.\n",
    "4. If it is still too slow, try using approximate inference using sampling algorithms."
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "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",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}