wolffd@0
|
1 function marginal = marginal_nodes(engine, nodes)
|
wolffd@0
|
2 % MARGINAL_NODES Compute the marginal on the specified query nodes (likelihood_weighting)
|
wolffd@0
|
3 % marginal = marginal_nodes(engine, nodes)
|
wolffd@0
|
4
|
wolffd@0
|
5 bnet = bnet_from_engine(engine);
|
wolffd@0
|
6 ddom = myintersect(nodes, bnet.dnodes);
|
wolffd@0
|
7 cdom = myintersect(nodes, bnet.cnodes);
|
wolffd@0
|
8 nsamples = size(engine.samples, 1);
|
wolffd@0
|
9 ns = bnet.node_sizes;
|
wolffd@0
|
10
|
wolffd@0
|
11 %w = normalise(engine.weights);
|
wolffd@0
|
12 w = engine.weights;
|
wolffd@0
|
13 if mysubset(nodes, ddom)
|
wolffd@0
|
14 T = 0*myones(ns(nodes));
|
wolffd@0
|
15 P = prod(ns(nodes));
|
wolffd@0
|
16 indices = ind2subv(ns(nodes), 1:P);
|
wolffd@0
|
17 samples = reshape(cat(1, engine.samples{:,nodes}), nsamples, length(nodes));
|
wolffd@0
|
18 for j = 1:P
|
wolffd@0
|
19 rows = find_rows(samples, indices(j,:));
|
wolffd@0
|
20 T(j) = sum(w(rows));
|
wolffd@0
|
21 end
|
wolffd@0
|
22 T = normalise(T);
|
wolffd@0
|
23 marginal.T = T;
|
wolffd@0
|
24 elseif subset(nodes, cdom)
|
wolffd@0
|
25 samples = reshape(cat(1, engine.samples{:,nodes}), nsamples*sum(ns(nodes)), length(nodes));
|
wolffd@0
|
26 [marginal.mu, marginal.Sigma] = wstats(samples', normalise(w));
|
wolffd@0
|
27 else
|
wolffd@0
|
28 error('can''t handle mixed marginals yet');
|
wolffd@0
|
29 end
|
wolffd@0
|
30
|
wolffd@0
|
31 marginal.domain = nodes;
|
wolffd@0
|
32
|
wolffd@0
|
33 %%%%%%%%%
|
wolffd@0
|
34
|
wolffd@0
|
35 function rows = find_rows(M, v)
|
wolffd@0
|
36 % FINDROWS Find rows which are equal to a specified vector
|
wolffd@0
|
37 % rows = findrows(M, v)
|
wolffd@0
|
38 % Each row of M is a sample
|
wolffd@0
|
39
|
wolffd@0
|
40 temp = abs(M - repmat(v, size(M, 1), 1));
|
wolffd@0
|
41 rows = find(sum(temp,2) == 0);
|
wolffd@0
|
42
|
wolffd@0
|
43 %%%%%%%%
|
wolffd@0
|
44
|
wolffd@0
|
45 function [mu, Sigma] = wstats(X, w)
|
wolffd@0
|
46
|
wolffd@0
|
47 % Computes the weighted mean and weighted covariance matrix for a given
|
wolffd@0
|
48 % set of observations X(:,i), and a set of normalised weights w(i).
|
wolffd@0
|
49 % Each column of X is a sample.
|
wolffd@0
|
50
|
wolffd@0
|
51 d = X - repmat(X * w', 1, size(X, 2));
|
wolffd@0
|
52 mu = sum(X .* repmat(w, size(X, 1), 1), 2);
|
wolffd@0
|
53 Sigma = d * diag(w) * d';
|