comparison toolboxes/FullBNT-1.0.7/bnt/examples/static/learn1.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e9a9cd732c1e
1 % Lawn sprinker example from Russell and Norvig p454
2 % See www.cs.berkeley.edu/~murphyk/Bayes/usage.html for details.
3
4 N = 4;
5 dag = zeros(N,N);
6 C = 1; S = 2; R = 3; W = 4;
7 dag(C,[R S]) = 1;
8 dag(R,W) = 1;
9 dag(S,W)=1;
10
11 false = 1; true = 2;
12 ns = 2*ones(1,N); % binary nodes
13
14 bnet = mk_bnet(dag, ns);
15 bnet.CPD{C} = tabular_CPD(bnet, C, [0.5 0.5]);
16 bnet.CPD{R} = tabular_CPD(bnet, R, [0.8 0.2 0.2 0.8]);
17 bnet.CPD{S} = tabular_CPD(bnet, S, [0.5 0.9 0.5 0.1]);
18 bnet.CPD{W} = tabular_CPD(bnet, W, [1 0.1 0.1 0.01 0 0.9 0.9 0.99]);
19
20 CPT = cell(1,N);
21 for i=1:N
22 s=struct(bnet.CPD{i}); % violate object privacy
23 CPT{i}=s.CPT;
24 end
25
26 % Generate training data
27 nsamples = 50;
28 samples = cell(N, nsamples);
29 for i=1:nsamples
30 samples(:,i) = sample_bnet(bnet);
31 end
32 data = cell2num(samples);
33
34 % Make a tabula rasa
35 bnet2 = mk_bnet(dag, ns);
36 seed = 0;
37 rand('state', seed);
38 bnet2.CPD{C} = tabular_CPD(bnet2, C, 'clamped', 1, 'CPT', [0.5 0.5], ...
39 'prior_type', 'dirichlet', 'dirichlet_weight', 0);
40 bnet2.CPD{R} = tabular_CPD(bnet2, R, 'prior_type', 'dirichlet', 'dirichlet_weight', 0);
41 bnet2.CPD{S} = tabular_CPD(bnet2, S, 'prior_type', 'dirichlet', 'dirichlet_weight', 0);
42 bnet2.CPD{W} = tabular_CPD(bnet2, W, 'prior_type', 'dirichlet', 'dirichlet_weight', 0);
43
44
45 % Find MLEs from fully observed data
46 bnet4 = learn_params(bnet2, samples);
47
48 % Bayesian updating with 0 prior is equivalent to ML estimation
49 bnet5 = bayes_update_params(bnet2, samples);
50
51 CPT4 = cell(1,N);
52 for i=1:N
53 s=struct(bnet4.CPD{i}); % violate object privacy
54 CPT4{i}=s.CPT;
55 end
56
57 CPT5 = cell(1,N);
58 for i=1:N
59 s=struct(bnet5.CPD{i}); % violate object privacy
60 CPT5{i}=s.CPT;
61 assert(approxeq(CPT5{i}, CPT4{i}))
62 end
63
64
65 if 1
66 % Find MLEs from partially observed data
67
68 % hide 50% of the nodes
69 samplesH = samples;
70 hide = rand(N, nsamples) > 0.5;
71 [I,J]=find(hide);
72 for k=1:length(I)
73 samplesH{I(k), J(k)} = [];
74 end
75
76 engine = jtree_inf_engine(bnet2);
77 max_iter = 5;
78 [bnet6, LL] = learn_params_em(engine, samplesH, max_iter);
79
80 CPT6 = cell(1,N);
81 for i=1:N
82 s=struct(bnet6.CPD{i}); % violate object privacy
83 CPT6{i}=s.CPT;
84 end
85
86 end