comparison toolboxes/FullBNT-1.0.7/bnt/examples/static/Belprop/gmux1.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 % Test gmux.
2 % The following model, where Y is a gmux node,
3 % and M is set to 1, should be equivalent to X1 -> Y
4 %
5 % X1 Xn M
6 % \ | /
7 % Y
8
9 n = 3;
10 N = n+2;
11 Xs = 1:n;
12 M = n+1;
13 Y = n+2;
14 dag = zeros(N,N);
15 dag([Xs M], Y)=1;
16
17 dnodes = M;
18 ns = zeros(1, N);
19 sz = 2;
20 ns(Xs) = sz;
21 ns(M) = n;
22 ns(Y) = sz;
23
24 bnet = mk_bnet(dag, ns, 'discrete', M, 'observed', [M Y]);
25
26 psz = ns(Xs(1));
27 selfsz = ns(Y);
28
29 W = randn(selfsz, psz);
30 mu = randn(selfsz, 1);
31 Sigma = eye(selfsz, selfsz);
32
33 bnet.CPD{M} = root_CPD(bnet, M);
34 for i=Xs(:)'
35 bnet.CPD{i} = gaussian_CPD(bnet, i, 'mean', zeros(psz, 1), 'cov', eye(psz, psz));
36 end
37 bnet.CPD{Y} = gmux_CPD(bnet, Y, 'mean', mu, 'weights', W, 'cov', Sigma);
38
39 evidence = cell(1,N);
40 yval = randn(selfsz, 1);
41 evidence{Y} = yval;
42 m = 2;
43 %notm = not(m-1)+1; % only valid for n=2
44 notm = mysetdiff(1:n, m);
45 evidence{M} = m;
46
47 engines = {};
48 engines{end+1} = jtree_inf_engine(bnet);
49 engines{end+1} = pearl_inf_engine(bnet, 'protocol', 'parallel');
50
51 for e=1:length(engines)
52 engines{e} = enter_evidence(engines{e}, evidence);
53 mXm{e} = marginal_nodes(engines{e}, Xs(m));
54
55 % Since M=m, only Xm was updated.
56 % Hence the posterior on Xnotm should equal the prior.
57 for i=notm(:)'
58 mXnotm = marginal_nodes(engines{e}, Xs(i));
59 assert(approxeq(mXnotm.mu, zeros(psz,1)))
60 assert(approxeq(mXnotm.Sigma, eye(psz, psz)))
61 end
62 end
63
64 % Check that all engines give the same posterior
65 for e=2:length(engines)
66 assert(approxeq(mXm{e}.mu, mXm{1}.mu))
67 assert(approxeq(mXm{e}.Sigma, mXm{1}.Sigma))
68 end
69
70
71 % Compute the correct posterior by building Xm -> Y
72
73 N = 2;
74 dag = zeros(N,N);
75 dag(1, 2)=1;
76 ns = [psz selfsz];
77 bnet = mk_bnet(dag, ns, 'discrete', [], 'observed', 2);
78
79 bnet.CPD{1} = gaussian_CPD(bnet, 1, 'mean', zeros(psz, 1), 'cov', eye(psz, psz));
80 bnet.CPD{2} = gaussian_CPD(bnet, 2, 'mean', mu, 'cov', Sigma, 'weights', W);
81
82 jengine = jtree_inf_engine(bnet);
83 evidence = {[], yval};
84 jengine = enter_evidence(jengine, evidence); % apply Bayes rule to invert the arc
85 mX = marginal_nodes(jengine, 1);
86
87 for e=1:length(engines)
88 assert(approxeq(mX.mu, mXm{e}.mu))
89 assert(approxeq(mX.Sigma, mXm{e}.Sigma))
90 end