comparison toolboxes/FullBNT-1.0.7/bnt/examples/static/StructLearn/model_select2.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 % Online Bayesian model selection demo.
2
3 % We generate data from the model A->B
4 % and compute the posterior prob of all 3 dags on 2 nodes:
5 % (1) A B, (2) A <- B , (3) A -> B
6 % Models 2 and 3 are Markov equivalent, and therefore indistinguishable from
7 % observational data alone.
8
9 % We control the dependence of B on A by setting
10 % P(B|A) = 0.5 - epislon and vary epsilon
11 % as in Koller & Friedman book p512
12
13 % ground truth
14 N = 2;
15 dag = zeros(N);
16 A = 1; B = 2;
17 dag(A,B) = 1;
18
19 ntrials = 100;
20 ns = 2*ones(1,N);
21 true_bnet = mk_bnet(dag, ns);
22 true_bnet.CPD{1} = tabular_CPD(true_bnet, 1, [0.5 0.5]);
23
24 % hypothesis space
25 G = mk_all_dags(N);
26 nhyp = length(G);
27 hyp_bnet = cell(1, nhyp);
28 for h=1:nhyp
29 hyp_bnet{h} = mk_bnet(G{h}, ns);
30 for i=1:N
31 % We must set the CPTs to the mean of the prior for sequential log_marg_lik to be correct
32 % The BDeu prior is score equivalent, so models 2,3 will be indistinguishable.
33 % The uniform Dirichlet prior is not score equivalent...
34 fam = family(G{h}, i);
35 hyp_bnet{h}.CPD{i}= tabular_CPD(hyp_bnet{h}, i, 'prior_type', 'dirichlet', ...
36 'CPT', 'unif');
37 end
38 end
39
40 clf
41 seeds = 1:3;
42 expt = 1;
43 for seedi=1:length(seeds)
44 seed = seeds(seedi);
45 rand('state', seed);
46 randn('state', seed);
47
48 es = [0.05 0.1 0.15 0.2];
49 for ei=1:length(es)
50 e = es(ei);
51 true_bnet.CPD{2} = tabular_CPD(true_bnet, 2, [0.5+e 0.5-e; 0.5-e 0.5+e]);
52
53 prior = normalise(ones(1, nhyp));
54 hyp_w = zeros(ntrials+1, nhyp);
55 hyp_w(1,:) = prior(:)';
56 LL = zeros(1, nhyp);
57 ll = zeros(1, nhyp);
58 for t=1:ntrials
59 ev = cell2num(sample_bnet(true_bnet));
60 for i=1:nhyp
61 ll(i) = log_marg_lik_complete(hyp_bnet{i}, ev);
62 hyp_bnet{i} = bayes_update_params(hyp_bnet{i}, ev);
63 end
64 prior = normalise(prior .* exp(ll));
65 LL = LL + ll;
66 hyp_w(t+1,:) = prior;
67 end
68
69 % Plot posterior model probabilities
70 % Red = model 1 (no arcs), blue/green = models 2/3 (1 arc)
71 % Blue = model 2 (2->1)
72 % Green = model 3 (1->2, "ground truth")
73
74 subplot2(length(seeds), length(es), seedi, ei);
75 m = size(hyp_w,1);
76 h=plot(1:m, hyp_w(:,1), 'r-', 1:m, hyp_w(:,2), 'b-.', 1:m, hyp_w(:,3), 'g:');
77 axis([0 m 0 1])
78 %title('model posterior vs. time')
79 title(sprintf('e=%3.2f, seed=%d', e, seed));
80 drawnow
81 expt = expt + 1;
82 end
83 end