comparison toolboxes/FullBNT-1.0.7/bnt/examples/static/mfa1.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 % Factor analysis
2 % Z -> X, Z in R^k, X in R^D, k << D (high dimensional observations explained by small source)
3 % Z ~ N(0,I), X|Z ~ N(L z, Psi), where Psi is diagonal.
4 %
5 % Mixtures of FA
6 % Now X|Z,W=i ~ N(mu(i) + L(i) Z, Psi(i))
7 %
8 % We compare to Zoubin Ghahramani's code.
9
10 randn('state', 0);
11 max_iter = 3;
12 M = 2;
13 k = 3;
14 D = 5;
15
16 n = 5;
17 X1 = randn(n, D);
18 X2 = randn(n, D) + 2; % move the mean to (2,2,2...)
19 X = [X1; X2];
20 N = size(X, 1);
21
22 % initialise as in mfa
23 tiny=exp(-700);
24 mX = mean(X);
25 cX=cov(X);
26 scale=det(cX)^(1/D);
27 randn('state',0); % must reset seed here so initial params are identical to mfa
28 L0=randn(D*M,k)*sqrt(scale/k);
29 W0 = permute(reshape(L0, [D M k]), [1 3 2]); % use D,K,M
30 Psi0=diag(cX)+tiny;
31 Pi0=ones(M,1)/M;
32 Mu0=randn(M,D)*sqrtm(cX)+ones(M,1)*mX;
33
34 [Lh1, Ph1, Mu1, Pi1, LL1] = mfa(X,M,k,max_iter);
35 Lh1 = permute(reshape(Lh1, [D M k]), [1 3 2]); % use D,K,M
36
37
38 ns = [M k D];
39 dag = zeros(3);
40 dag(1,3) = 1;
41 dag(2,3) = 1;
42 dnodes = 1;
43 onodes = 3;
44
45 bnet = mk_bnet(dag, ns, 'discrete', dnodes, 'observed', onodes);
46 bnet.CPD{1} = tabular_CPD(bnet, 1, Pi0);
47
48 %bnet.CPD{2} = gaussian_CPD(bnet, 2, zeros(k, 1), eye(k), [], 'diag', 'untied', 'clamp_mean', 'clamp_cov');
49
50 bnet.CPD{2} = gaussian_CPD(bnet, 2, 'mean', zeros(k, 1), 'cov', eye(k), 'cov_type', 'diag', ...
51 'cov_prior_weight', 0, 'clamp_mean', 1, 'clamp_cov', 1);
52
53 %bnet.CPD{3} = gaussian_CPD(bnet, 3, Mu0', repmat(diag(Psi0), [1 1 M]), W0, 'diag', 'tied');
54
55 bnet.CPD{3} = gaussian_CPD(bnet, 3, 'mean', Mu0', 'cov', repmat(diag(Psi0), [1 1 M]), ...
56 'weights', W0, 'cov_type', 'diag', 'cov_prior_weight', 0, 'tied_cov', 1);
57
58 engine = jtree_inf_engine(bnet);
59 evidence = cell(3, N);
60 evidence(3,:) = num2cell(X', 1);
61
62 [bnet2, LL2, engine2] = learn_params_em(engine, evidence, max_iter);
63
64 s = struct(bnet2.CPD{1});
65 Pi2 = s.CPT(:);
66 s = struct(bnet2.CPD{3});
67 Mu2 = s.mean;
68 W2 = s.weights;
69 Sigma2 = s.cov;
70
71
72 % Compare to Zoubin's code
73 assert(approxeq(LL1,LL2));
74 for i=1:M
75 assert(approxeq(W2(:,:,i), Lh1(:,:,i)));
76 assert(approxeq(Sigma2(:,:,i), diag(Ph1)));
77 assert(approxeq(Mu2(:,i), Mu1(i,:)));
78 assert(approxeq(Pi2(:), Pi1(:)));
79 end
80