annotate toolboxes/FullBNT-1.0.7/bnt/examples/dynamic/kalman1.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
rev   line source
wolffd@0 1 % Make a linear dynamical system
wolffd@0 2 % X1 -> X2
wolffd@0 3 % | |
wolffd@0 4 % v v
wolffd@0 5 % Y1 Y2
wolffd@0 6
wolffd@0 7 intra = zeros(2);
wolffd@0 8 intra(1,2) = 1;
wolffd@0 9 inter = zeros(2);
wolffd@0 10 inter(1,1) = 1;
wolffd@0 11 n = 2;
wolffd@0 12
wolffd@0 13 X = 2; % size of hidden state
wolffd@0 14 Y = 2; % size of observable state
wolffd@0 15 ns = [X Y];
wolffd@0 16 bnet = mk_dbn(intra, inter, ns, 'discrete', [], 'observed', 2);
wolffd@0 17
wolffd@0 18 x0 = rand(X,1);
wolffd@0 19 V0 = eye(X);
wolffd@0 20 C0 = rand(Y,X);
wolffd@0 21 R0 = eye(Y);
wolffd@0 22 A0 = rand(X,X);
wolffd@0 23 Q0 = eye(X);
wolffd@0 24
wolffd@0 25 bnet.CPD{1} = gaussian_CPD(bnet, 1, 'mean', x0, 'cov', V0, 'cov_prior_weight', 0);
wolffd@0 26 bnet.CPD{2} = gaussian_CPD(bnet, 2, 'mean', zeros(Y,1), 'cov', R0, 'weights', C0, ...
wolffd@0 27 'clamp_mean', 1, 'cov_prior_weight', 0);
wolffd@0 28 bnet.CPD{3} = gaussian_CPD(bnet, 3, 'mean', zeros(X,1), 'cov', Q0, 'weights', A0, ...
wolffd@0 29 'clamp_mean', 1, 'cov_prior_weight', 0);
wolffd@0 30
wolffd@0 31
wolffd@0 32 T = 5; % fixed length sequences
wolffd@0 33
wolffd@0 34 clear engine;
wolffd@0 35 engine{1} = kalman_inf_engine(bnet);
wolffd@0 36 engine{2} = jtree_unrolled_dbn_inf_engine(bnet, T);
wolffd@0 37 engine{3} = jtree_dbn_inf_engine(bnet);
wolffd@0 38 engine{end+1} = smoother_engine(jtree_2TBN_inf_engine(bnet));
wolffd@0 39 N = length(engine);
wolffd@0 40
wolffd@0 41
wolffd@0 42 inf_time = cmp_inference_dbn(bnet, engine, T);
wolffd@0 43
wolffd@0 44 ncases = 2;
wolffd@0 45 max_iter = 2;
wolffd@0 46 [learning_time, CPD, LL, cases] = cmp_learning_dbn(bnet, engine, T, 'ncases', ncases, 'max_iter', max_iter);
wolffd@0 47
wolffd@0 48
wolffd@0 49 % Compare to KF toolbox
wolffd@0 50
wolffd@0 51 data = zeros(Y, T, ncases);
wolffd@0 52 for i=1:ncases
wolffd@0 53 data(:,:,i) = cell2num(cases{i}(onodes, :));
wolffd@0 54 end
wolffd@0 55 [A2, C2, Q2, R2, x2, V2, LL2trace] = learn_kalman(data, A0, C0, Q0, R0, x0, V0, max_iter);
wolffd@0 56
wolffd@0 57
wolffd@0 58 e = 1;
wolffd@0 59 assert(approxeq(x2, CPD{e,1}.mean))
wolffd@0 60 assert(approxeq(V2, CPD{e,1}.cov))
wolffd@0 61 assert(approxeq(C2, CPD{e,2}.weights))
wolffd@0 62 assert(approxeq(R2, CPD{e,2}.cov));
wolffd@0 63 assert(approxeq(A2, CPD{e,3}.weights))
wolffd@0 64 assert(approxeq(Q2, CPD{e,3}.cov));
wolffd@0 65 assert(approxeq(LL2trace, LL{1}))
wolffd@0 66