Repository navigation
Expand file tree
/
Copy pathtest_probability.py
More file actions
655 lines (536 loc) · 25.5 KB
/
Copy pathtest_probability.py
File metadata and controls
655 lines (536 loc) · 25.5 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import pytest
from aima.probability import *
from aima.utils import rounder
random.seed("aima-python")
def tests():
cpt = burglary.variable_node('Alarm')
event = {'Burglary': True, 'Earthquake': True}
assert cpt.p(True, event) == 0.95
event = {'Burglary': False, 'Earthquake': True}
assert cpt.p(False, event) == 0.71
# enumeration_ask('Earthquake', {}, burglary)
s = {'A': True, 'B': False, 'C': True, 'D': False}
assert consistent_with(s, {})
assert consistent_with(s, s)
assert not consistent_with(s, {'A': False})
assert not consistent_with(s, {'D': True})
random.seed(21)
p = rejection_sampling('Earthquake', {}, burglary, 1000)
assert p[True], p[False] == (0.001, 0.999)
random.seed(71)
p = likelihood_weighting('Earthquake', {}, burglary, 1000)
assert p[True], p[False] == (0.002, 0.998)
def test_probdist_basic():
P = ProbDist('Flip')
P['H'], P['T'] = 0.25, 0.75
assert P['H'] == 0.25
assert P['T'] == 0.75
assert P['X'] == 0.00
P = ProbDist('BiasedDie')
P['1'], P['2'], P['3'], P['4'], P['5'], P['6'] = 10, 15, 25, 30, 40, 80
P.normalize()
assert P['2'] == 0.075
assert P['4'] == 0.15
assert P['6'] == 0.4
def test_probdist_frequency():
P = ProbDist('X', {'lo': 125, 'med': 375, 'hi': 500})
assert (P['lo'], P['med'], P['hi']) == (0.125, 0.375, 0.5)
P = ProbDist('Pascal-5', {'x1': 1, 'x2': 5, 'x3': 10, 'x4': 10, 'x5': 5, 'x6': 1})
assert (P['x1'], P['x2'], P['x3'], P['x4'], P['x5'], P['x6']) == (
0.03125, 0.15625, 0.3125, 0.3125, 0.15625, 0.03125)
def test_probdist_normalize():
P = ProbDist('Flip')
P['H'], P['T'] = 35, 65
P = P.normalize()
assert (P.prob['H'], P.prob['T']) == (0.350, 0.650)
P = ProbDist('BiasedDie')
P['1'], P['2'], P['3'], P['4'], P['5'], P['6'] = 10, 15, 25, 30, 40, 80
P = P.normalize()
assert (P.prob['1'], P.prob['2'], P.prob['3'], P.prob['4'], P.prob['5'], P.prob['6']) == (
0.05, 0.075, 0.125, 0.15, 0.2, 0.4)
def test_jointprob():
P = JointProbDist(['X', 'Y'])
P[1, 1] = 0.25
assert P[1, 1] == 0.25
P[dict(X=0, Y=1)] = 0.5
assert P[dict(X=0, Y=1)] == 0.5
def test_event_values():
assert event_values({'A': 10, 'B': 9, 'C': 8}, ['C', 'A']) == (8, 10)
assert event_values((1, 2), ['C', 'A']) == (1, 2)
def test_enumerate_joint():
P = JointProbDist(['X', 'Y'])
P[0, 0] = 0.25
P[0, 1] = 0.5
P[1, 1] = P[2, 1] = 0.125
assert enumerate_joint(['Y'], dict(X=0), P) == 0.75
assert enumerate_joint(['X'], dict(Y=2), P) == 0
assert enumerate_joint(['X'], dict(Y=1), P) == 0.75
Q = JointProbDist(['W', 'X', 'Y', 'Z'])
Q[0, 1, 1, 0] = 0.12
Q[1, 0, 1, 1] = 0.4
Q[0, 0, 1, 1] = 0.5
Q[0, 0, 1, 0] = 0.05
Q[0, 0, 0, 0] = 0.675
Q[1, 1, 1, 0] = 0.3
assert enumerate_joint(['W'], dict(X=0, Y=0, Z=1), Q) == 0
assert enumerate_joint(['W'], dict(X=0, Y=0, Z=0), Q) == 0.675
assert enumerate_joint(['W'], dict(X=0, Y=1, Z=1), Q) == 0.9
assert enumerate_joint(['Y'], dict(W=1, X=0, Z=1), Q) == 0.4
assert enumerate_joint(['Z'], dict(W=0, X=0, Y=0), Q) == 0.675
assert enumerate_joint(['Z'], dict(W=1, X=1, Y=1), Q) == 0.3
def test_enumerate_joint_ask():
P = JointProbDist(['X', 'Y'])
P[0, 0] = 0.25
P[0, 1] = 0.5
P[1, 1] = P[2, 1] = 0.125
assert enumerate_joint_ask(
'X', dict(Y=1), P).show_approx() == '0: 0.667, 1: 0.167, 2: 0.167'
def test_is_independent():
P = JointProbDist(['X', 'Y'])
P[0, 0] = P[0, 1] = P[1, 1] = P[1, 0] = 0.25
assert enumerate_joint_ask(
'X', dict(Y=1), P).show_approx() == '0: 0.5, 1: 0.5'
assert is_independent(['X', 'Y'], P)
def test_gaussian_probability():
param = {'sigma': 0.5, 'b': 1, 'a': {'h': 0.5}}
event = {'h': 0.6}
assert gaussian_probability(param, event, 1) == 0.6664492057835993
def test_logistic_probability():
param = {'mu': 0.5, 'sigma': 0.1}
event = {'h': 0.6}
assert logistic_probability(param, event, True) == 0.16857376940725355
assert logistic_probability(param, event, False) == 0.8314262305927465
def test_bayesnode_p():
bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625})
assert bn.p(True, {'Burglary': True, 'Earthquake': False}) == 0.2
assert bn.p(False, {'Burglary': False, 'Earthquake': True}) == 0.375
assert BayesNode('W', '', 0.75).p(False, {'Random': True}) == 0.25
def test_bayesnode_sample():
X = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625})
assert X.sample({'Burglary': False, 'Earthquake': True}) in [True, False]
Z = BayesNode('Z', 'P Q', {(True, True): 0.2, (True, False): 0.3,
(False, True): 0.5, (False, False): 0.7})
assert Z.sample({'P': True, 'Q': False}) in [True, False]
def test_enumeration_ask():
assert enumeration_ask(
'Burglary', dict(JohnCalls=T, MaryCalls=T),
burglary).show_approx() == 'False: 0.716, True: 0.284'
assert enumeration_ask(
'Burglary', dict(JohnCalls=T, MaryCalls=F),
burglary).show_approx() == 'False: 0.995, True: 0.00513'
assert enumeration_ask(
'Burglary', dict(JohnCalls=F, MaryCalls=T),
burglary).show_approx() == 'False: 0.993, True: 0.00688'
assert enumeration_ask(
'Burglary', dict(JohnCalls=T),
burglary).show_approx() == 'False: 0.984, True: 0.0163'
assert enumeration_ask(
'Burglary', dict(MaryCalls=T),
burglary).show_approx() == 'False: 0.944, True: 0.0561'
def test_elimination_ask():
assert elimination_ask(
'Burglary', dict(JohnCalls=T, MaryCalls=T),
burglary).show_approx() == 'False: 0.716, True: 0.284'
assert elimination_ask(
'Burglary', dict(JohnCalls=T, MaryCalls=F),
burglary).show_approx() == 'False: 0.995, True: 0.00513'
assert elimination_ask(
'Burglary', dict(JohnCalls=F, MaryCalls=T),
burglary).show_approx() == 'False: 0.993, True: 0.00688'
assert elimination_ask(
'Burglary', dict(JohnCalls=T),
burglary).show_approx() == 'False: 0.984, True: 0.0163'
assert elimination_ask(
'Burglary', dict(MaryCalls=T),
burglary).show_approx() == 'False: 0.944, True: 0.0561'
def test_prior_sample():
random.seed(42)
all_obs = [prior_sample(burglary) for x in range(1000)]
john_calls_true = [observation for observation in all_obs if observation['JohnCalls']]
mary_calls_true = [observation for observation in all_obs if observation['MaryCalls']]
burglary_and_john = [observation for observation in john_calls_true if observation['Burglary']]
burglary_and_mary = [observation for observation in mary_calls_true if observation['Burglary']]
assert len(john_calls_true) / 1000 == 46 / 1000
assert len(mary_calls_true) / 1000 == 13 / 1000
assert len(burglary_and_john) / len(john_calls_true) == 1 / 46
assert len(burglary_and_mary) / len(mary_calls_true) == 1 / 13
def test_prior_sample2():
random.seed(128)
all_obs = [prior_sample(sprinkler) for x in range(1000)]
rain_true = [observation for observation in all_obs if observation['Rain']]
sprinkler_true = [observation for observation in all_obs if observation['Sprinkler']]
rain_and_cloudy = [observation for observation in rain_true if observation['Cloudy']]
sprinkler_and_cloudy = [observation for observation in sprinkler_true if observation['Cloudy']]
assert len(rain_true) / 1000 == 0.476
assert len(sprinkler_true) / 1000 == 0.291
assert len(rain_and_cloudy) / len(rain_true) == 376 / 476
assert len(sprinkler_and_cloudy) / len(sprinkler_true) == 39 / 291
def test_rejection_sampling():
random.seed(47)
assert rejection_sampling(
'Burglary', dict(JohnCalls=T, MaryCalls=T),
burglary, 10000).show_approx() == 'False: 0.7, True: 0.3'
assert rejection_sampling(
'Burglary', dict(JohnCalls=T, MaryCalls=F),
burglary, 10000).show_approx() == 'False: 1, True: 0'
assert rejection_sampling(
'Burglary', dict(JohnCalls=F, MaryCalls=T),
burglary, 10000).show_approx() == 'False: 0.987, True: 0.0128'
assert rejection_sampling(
'Burglary', dict(JohnCalls=T),
burglary, 10000).show_approx() == 'False: 0.982, True: 0.0183'
assert rejection_sampling(
'Burglary', dict(MaryCalls=T),
burglary, 10000).show_approx() == 'False: 0.965, True: 0.0348'
def test_rejection_sampling2():
random.seed(42)
assert rejection_sampling(
'Cloudy', dict(Rain=T, Sprinkler=T),
sprinkler, 10000).show_approx() == 'False: 0.56, True: 0.44'
assert rejection_sampling(
'Cloudy', dict(Rain=T, Sprinkler=F),
sprinkler, 10000).show_approx() == 'False: 0.119, True: 0.881'
assert rejection_sampling(
'Cloudy', dict(Rain=F, Sprinkler=T),
sprinkler, 10000).show_approx() == 'False: 0.951, True: 0.049'
assert rejection_sampling(
'Cloudy', dict(Rain=T),
sprinkler, 10000).show_approx() == 'False: 0.205, True: 0.795'
assert rejection_sampling(
'Cloudy', dict(Sprinkler=T),
sprinkler, 10000).show_approx() == 'False: 0.835, True: 0.165'
def test_likelihood_weighting():
random.seed(1017)
assert likelihood_weighting(
'Burglary', dict(JohnCalls=T, MaryCalls=T),
burglary, 10000).show_approx() == 'False: 0.702, True: 0.298'
assert likelihood_weighting(
'Burglary', dict(JohnCalls=T, MaryCalls=F),
burglary, 10000).show_approx() == 'False: 0.993, True: 0.00656'
assert likelihood_weighting(
'Burglary', dict(JohnCalls=F, MaryCalls=T),
burglary, 10000).show_approx() == 'False: 0.996, True: 0.00363'
assert likelihood_weighting(
'Burglary', dict(JohnCalls=F, MaryCalls=F),
burglary, 10000).show_approx() == 'False: 1, True: 0.000126'
assert likelihood_weighting(
'Burglary', dict(JohnCalls=T),
burglary, 10000).show_approx() == 'False: 0.979, True: 0.0205'
assert likelihood_weighting(
'Burglary', dict(MaryCalls=T),
burglary, 10000).show_approx() == 'False: 0.94, True: 0.0601'
def test_likelihood_weighting2():
random.seed(42)
assert likelihood_weighting(
'Cloudy', dict(Rain=T, Sprinkler=T),
sprinkler, 10000).show_approx() == 'False: 0.559, True: 0.441'
assert likelihood_weighting(
'Cloudy', dict(Rain=T, Sprinkler=F),
sprinkler, 10000).show_approx() == 'False: 0.12, True: 0.88'
assert likelihood_weighting(
'Cloudy', dict(Rain=F, Sprinkler=T),
sprinkler, 10000).show_approx() == 'False: 0.951, True: 0.0486'
assert likelihood_weighting(
'Cloudy', dict(Rain=T),
sprinkler, 10000).show_approx() == 'False: 0.198, True: 0.802'
assert likelihood_weighting(
'Cloudy', dict(Sprinkler=T),
sprinkler, 10000).show_approx() == 'False: 0.833, True: 0.167'
def test_forward_backward():
umbrella_transition = [[0.7, 0.3], [0.3, 0.7]]
umbrella_sensor = [[0.9, 0.2], [0.1, 0.8]]
umbrellaHMM = HiddenMarkovModel(umbrella_transition, umbrella_sensor)
umbrella_evidence = [T, T, F, T, T]
assert rounder(forward_backward(umbrellaHMM, umbrella_evidence)) == [
[0.6469, 0.3531], [0.8673, 0.1327], [0.8204, 0.1796], [0.3075, 0.6925], [0.8204, 0.1796], [0.8673, 0.1327]]
umbrella_evidence = [T, F, T, F, T]
assert rounder(forward_backward(umbrellaHMM, umbrella_evidence)) == [
[0.5871, 0.4129], [0.7177, 0.2823], [0.2324, 0.7676], [0.6072, 0.3928], [0.2324, 0.7676], [0.7177, 0.2823]]
def test_viterbi():
umbrella_transition = [[0.7, 0.3], [0.3, 0.7]]
umbrella_sensor = [[0.9, 0.2], [0.1, 0.8]]
umbrellaHMM = HiddenMarkovModel(umbrella_transition, umbrella_sensor)
umbrella_evidence = [T, T, F, T, T]
assert viterbi(umbrellaHMM, umbrella_evidence)[0] == [T, T, F, T, T]
assert rounder(viterbi(umbrellaHMM, umbrella_evidence)[1]) == [0.8182, 0.5155, 0.1237, 0.0334, 0.0210]
umbrella_evidence = [T, F, T, F, T]
assert viterbi(umbrellaHMM, umbrella_evidence)[0] == [T, F, F, F, T]
assert rounder(viterbi(umbrellaHMM, umbrella_evidence)[1]) == [0.8182, 0.1964, 0.0275, 0.0154, 0.0042]
def test_fixed_lag_smoothing():
umbrella_evidence = [T, F, T, F, T]
e_t = F
t = 4
umbrella_transition = [[0.7, 0.3], [0.3, 0.7]]
umbrella_sensor = [[0.9, 0.2], [0.1, 0.8]]
umbrellaHMM = HiddenMarkovModel(umbrella_transition, umbrella_sensor)
d = 2
assert rounder(fixed_lag_smoothing(e_t, umbrellaHMM, d, umbrella_evidence, t)) == [0.2259, 0.7741]
d = 5
assert fixed_lag_smoothing(e_t, umbrellaHMM, d, umbrella_evidence, t) is None
umbrella_evidence = [T, T, F, T, T]
# t = 4
e_t = T
d = 1
assert rounder(fixed_lag_smoothing(e_t, umbrellaHMM, d, umbrella_evidence, t)) == [0.2839, 0.7161]
def test_particle_filtering():
N = 10
umbrella_evidence = T
umbrella_transition = [[0.7, 0.3], [0.3, 0.7]]
umbrella_sensor = [[0.9, 0.2], [0.1, 0.8]]
umbrellaHMM = HiddenMarkovModel(umbrella_transition, umbrella_sensor)
s = particle_filtering(umbrella_evidence, N, umbrellaHMM)
assert len(s) == N
assert all(state in 'AB' for state in s)
# XXX 'A' and 'B' are really arbitrary names, but I'm letting it stand for now
def test_kalman_filter():
# one-dimensional random walk (Section 15.4 example): x_{t+1} = x_t + noise,
# z_t = x_t + noise. With prior N(0, 1), transition variance 2 and sensor
# variance 1, a single observation z = 2.5 has the closed-form posterior
# mean ((cov0 + Sigma_x) * z + Sigma_z * mean0) / (cov0 + Sigma_x + Sigma_z)
# and variance (cov0 + Sigma_x) * Sigma_z / (cov0 + Sigma_x + Sigma_z)
kf = KalmanFilter(transition_model=[[1]], sensor_model=[[1]],
transition_noise=[[2]], sensor_noise=[[1]])
(mean, cov), = kalman_filter(kf, mean0=[0], cov0=[[1]], observations=[2.5])
assert np.isclose(mean[0], 1.875)
assert np.isclose(cov[0, 0], 0.75)
# conditioning on the observation never increases the predicted uncertainty
assert cov[0, 0] < 1 + 2
# two-dimensional constant-velocity model: the state is [position, velocity]
# and only the position is observed; from a sequence of steadily increasing
# position measurements the filter should infer a positive velocity
kf = KalmanFilter(transition_model=[[1, 1], [0, 1]], sensor_model=[[1, 0]],
transition_noise=[[0.01, 0], [0, 0.01]], sensor_noise=[[1]])
estimates = kalman_filter(kf, mean0=[0, 0], cov0=[[1, 0], [0, 1]],
observations=[1, 2, 3, 4, 5])
assert len(estimates) == 5
final_mean, final_cov = estimates[-1]
assert final_mean[1] > 0 # inferred velocity is positive
assert final_cov.shape == (2, 2)
def test_kalman_filter_steady_state():
# [Section 15.4] for the 1-D random walk with unit transition and sensor
# variance the filtered variance converges to the fixed point of
# s = (s + 1) / (s + 2), i.e. s^2 + s - 1 = 0, so s = (sqrt(5) - 1) / 2
kf = KalmanFilter(transition_model=[[1]], sensor_model=[[1]],
transition_noise=[[1]], sensor_noise=[[1]])
estimates = kalman_filter(kf, mean0=[0], cov0=[[1]], observations=[0.0] * 60)
steady_state = (5 ** 0.5 - 1) / 2
assert estimates[-1][1][0, 0] == pytest.approx(steady_state, abs=1e-6)
def test_baum_welch():
def sequence_log_likelihood(hmm, obs):
"""Log probability of the observation sequence under hmm (scaled forward pass)."""
A = np.array(hmm.transition_model)
sensor = np.array(hmm.sensor_model)
B = np.array([sensor[0] if e else sensor[1] for e in obs])
alpha = np.array(hmm.prior) * B[0]
ll = np.log(alpha.sum())
alpha = alpha / alpha.sum()
for t in range(1, len(obs)):
alpha = B[t] * (alpha @ A)
ll += np.log(alpha.sum())
alpha = alpha / alpha.sum()
return ll
umbrella_transition = [[0.7, 0.3], [0.3, 0.7]]
umbrella_sensor = [[0.9, 0.2], [0.1, 0.8]]
umbrellaHMM = HiddenMarkovModel(umbrella_transition, umbrella_sensor)
observations = [T, T, F, T, T, F, F, F, T, F, T, T]
# Baum-Welch (EM) must never decrease the data log likelihood
log_likelihoods = [sequence_log_likelihood(baum_welch(umbrellaHMM, observations, iterations=k), observations)
for k in (1, 2, 5, 10, 20)]
assert all(later >= earlier - 1e-9 for earlier, later in zip(log_likelihoods, log_likelihoods[1:]))
assert log_likelihoods[-1] >= sequence_log_likelihood(umbrellaHMM, observations) - 1e-9
# the learned parameters are still valid probability distributions
learned = baum_welch(umbrellaHMM, observations, iterations=20)
assert np.allclose(np.sum(learned.transition_model, axis=1), 1)
assert np.isclose(sum(learned.prior), 1)
assert np.allclose(np.sum(learned.sensor_model, axis=0), 1)
def test_dynamic_bayes_net():
# the umbrella world as a DBN: hidden Rain with a 0.7 self-transition, observed
# through Umbrella with sensor probabilities 0.9 / 0.2
umbrella_dbn = DynamicBayesNet(prior=[('Rain', '', 0.5)],
transition=[('Rain', 'Rain_prev', {T: 0.7, F: 0.3})],
sensors=[('Umbrella', 'Rain', {T: 0.9, F: 0.2})])
# unrolling spans slices 0..steps with evidence variables at slices 1..steps
assert umbrella_dbn.unroll(2).variables == ['Rain_0', 'Rain_1', 'Umbrella_1', 'Rain_2', 'Umbrella_2']
# filtering by exact inference matches the canonical umbrella values, which in
# turn agree with the HMM forward algorithm
assert umbrella_dbn.filter([{'Umbrella': True}], 'Rain')[True] == pytest.approx(0.8182, abs=1e-4)
assert umbrella_dbn.filter([{'Umbrella': True}, {'Umbrella': True}], 'Rain')[True] == pytest.approx(0.8834,
abs=1e-4)
umbrellaHMM = HiddenMarkovModel([[0.7, 0.3], [0.3, 0.7]], [[0.9, 0.2], [0.1, 0.8]])
hmm_belief = forward(umbrellaHMM, umbrellaHMM.prior, True)
assert umbrella_dbn.filter([{'Umbrella': True}], 'Rain')[True] == pytest.approx(hmm_belief[0])
# over the book's umbrella evidence sequence [T, T, F, T, T], exact DBN
# filtering agrees step for step with the HMM forward algorithm
sequence = [T, T, F, T, T]
fv = umbrellaHMM.prior
for e in sequence:
fv = forward(umbrellaHMM, fv, e)
dbn_belief = umbrella_dbn.filter([{'Umbrella': e} for e in sequence], 'Rain')
assert dbn_belief[True] == pytest.approx(fv[0])
assert dbn_belief[True] == pytest.approx(0.8673, abs=1e-4)
def test_monte_carlo_localization():
# TODO: Add tests for random motion/inaccurate sensors
random.seed('aima-python')
m = MCLmap([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0]])
def P_motion_sample(kin_state, v, w):
"""Sample from possible kinematic states.
Returns from a single element distribution (no uncertainty in motion)"""
pos = kin_state[:2]
orient = kin_state[2]
# for simplicity the robot first rotates and then moves
orient = (orient + w) % 4
for _ in range(orient):
v = (v[1], -v[0])
pos = vector_add(pos, v)
return pos + (orient,)
def P_sensor(x, y):
"""Conditional probability for sensor reading"""
# Need not be exact probability. Can use a scaled value.
if x == y:
return 0.8
elif abs(x - y) <= 2:
return 0.05
else:
return 0
from aima.utils import print_table
a = {'v': (0, 0), 'w': 0}
z = (2, 4, 1, 6)
S = monte_carlo_localization(a, z, 1000, P_motion_sample, P_sensor, m)
grid = [[0] * 17 for _ in range(11)]
for x, y, _ in S:
if 0 <= x < 11 and 0 <= y < 17:
grid[x][y] += 1
print("GRID:")
print_table(grid)
a = {'v': (0, 1), 'w': 0}
z = (2, 3, 5, 7)
S = monte_carlo_localization(a, z, 1000, P_motion_sample, P_sensor, m, S)
grid = [[0] * 17 for _ in range(11)]
for x, y, _ in S:
if 0 <= x < 11 and 0 <= y < 17:
grid[x][y] += 1
print("GRID:")
print_table(grid)
assert grid[6][7] > 700
def test_continuous_mcl():
import math
from aima.probability import ContinuousMCLmap
# a 10 x 10 arena with a central 4x4..6x6 square obstacle (Fig 25.10 style)
m = ContinuousMCLmap(10, 10, obstacles=[(4, 4, 6, 6)])
# ray casting returns continuous distances, not grid steps
assert m.ray_cast(0, (2.0, 2.0, 0.0)) == 8.0 # +x -> right wall
assert m.ray_cast(1, (2.0, 2.0, 0.0)) == 8.0 # +y -> top wall
assert m.ray_cast(2, (2.0, 2.0, 0.0)) == 2.0 # -x -> left wall
assert m.ray_cast(3, (2.0, 2.0, 0.0)) == 2.0 # -y -> bottom wall
assert m.ray_cast(0, (1.0, 5.0, 0.0)) == 3.0 # +x -> obstacle left edge at x=4
assert m.in_free_space(2, 2) and not m.in_free_space(5, 5)
# sample() always lands in free space
random.seed('aima-python')
for _ in range(100):
x, y, _ = m.sample()
assert m.in_free_space(x, y)
# the particle filter localizes the robot on the continuous map
true = (2.0, 2.0, 0.0)
z = [m.ray_cast(s, true) for s in range(len(m.sensors))]
def P_motion_sample(kin_state, v, w):
"""Near-static motion with small Gaussian jitter to keep diversity."""
x, y, h = kin_state
return (x + random.gauss(0, 0.1), y + random.gauss(0, 0.1),
(h + random.gauss(0, 0.05)) % (2 * math.pi))
def P_sensor(observed, expected):
"""Gaussian range-sensor likelihood (need not be normalized)."""
if expected == math.inf:
return 1e-6
return math.exp(-((observed - expected) ** 2) / (2 * 0.5 ** 2)) + 1e-6
random.seed('aima-python')
a = {'v': 0, 'w': 0}
N, S = 2000, None
for _ in range(6):
S = monte_carlo_localization(a, z, N, P_motion_sample, P_sensor, m, S)
assert len(S) == N
near = sum(1 for x, y, _ in S if math.hypot(x - 2, y - 2) < 1.5)
assert near > N / 2 # most particles concentrate around the true pose
def test_gibbs_ask():
# exact posterior P(Cloudy | Rain=True) = 0.8; seed + tolerance keep this
# Monte Carlo test deterministic and independent of execution order
random.seed('aima-python')
p = gibbs_ask('Cloudy', dict(Rain=True), sprinkler, 2000)[True]
assert abs(p - 0.8) < 0.05
# The following should probably go in .ipynb:
"""
# We can build up a probability distribution like this (p. 469):
>>> P = ProbDist()
>>> P['sunny'] = 0.7
>>> P['rain'] = 0.2
>>> P['cloudy'] = 0.08
>>> P['snow'] = 0.02
# and query it like this: (Never mind this ELLIPSIS option
# added to make the doctest portable.)
>>> P['rain'] #doctest:+ELLIPSIS
0.2...
# A Joint Probability Distribution is dealt with like this [Figure 13.3]:
>>> P = JointProbDist(['Toothache', 'Cavity', 'Catch'])
>>> T, F = True, False
>>> P[T, T, T] = 0.108; P[T, T, F] = 0.012; P[F, T, T] = 0.072; P[F, T, F] = 0.008
>>> P[T, F, T] = 0.016; P[T, F, F] = 0.064; P[F, F, T] = 0.144; P[F, F, F] = 0.576
>>> P[T, T, T]
0.108
# Ask for P(Cavity|Toothache=T)
>>> PC = enumerate_joint_ask('Cavity', {'Toothache': T}, P)
>>> PC.show_approx()
'False: 0.4, True: 0.6'
>>> 0.6-epsilon < PC[T] < 0.6+epsilon
True
>>> 0.4-epsilon < PC[F] < 0.4+epsilon
True
"""
def test_discrete_bayes_net_inference():
# a small multi-valued net; both exact-inference engines must agree with the
# hand-computed posterior P(Rain | Traffic=high)
net = DiscreteBayesNet([
('Rain', '', ['none', 'light', 'heavy'], {(): [0.6, 0.3, 0.1]}),
('Traffic', 'Rain', ['low', 'high'],
{('none',): [0.9, 0.1], ('light',): [0.6, 0.4], ('heavy',): [0.2, 0.8]}),
])
expected = {'none': 0.06 / 0.26, 'light': 0.12 / 0.26, 'heavy': 0.08 / 0.26}
for ask in (enumeration_ask, elimination_ask):
q = ask('Rain', {'Traffic': 'high'}, net)
for value, p in expected.items():
assert abs(q[value] - p) < 1e-9
def test_read_bif():
bif = """
network n { }
variable A { type discrete [ 2 ] { yes, no }; }
variable B { type discrete [ 3 ] { lo, mid, hi }; }
probability ( A ) { table 0.3, 0.7; }
probability ( B | A ) {
(yes) 0.2, 0.3, 0.5;
(no) 0.1, 0.1, 0.8;
}
"""
net = read_bif(bif)
assert set(net.variables) == {'A', 'B'}
assert net.variable_values('B') == ['lo', 'mid', 'hi']
assert net.variable_node('B').parents == ['A']
assert net.variable_node('A').p('yes', {}) == 0.3
assert net.variable_node('B').p('hi', {'A': 'no'}) == 0.8
def test_insurance_bayes_net():
# the car-insurance ("Insurance") network loads from aima-data and supports
# exact inference (AIMA 4e §16 case study, issue #1285)
net = insurance()
assert len(net.variables) == 27
assert net.variable_values('Age') == ['Adolescent', 'Adult', 'Senior']
age = elimination_ask('Age', {}, net)
assert (round(age['Adolescent'], 3), round(age['Adult'], 3), round(age['Senior'], 3)) == (0.2, 0.6, 0.2)
if __name__ == '__main__':
pytest.main()