annotate toolboxes/FullBNT-1.0.7/HMM/viterbi_path.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1 function path = viterbi_path(prior, transmat, obslik)
Daniel@0 2 % VITERBI Find the most-probable (Viterbi) path through the HMM state trellis.
Daniel@0 3 % path = viterbi(prior, transmat, obslik)
Daniel@0 4 %
Daniel@0 5 % Inputs:
Daniel@0 6 % prior(i) = Pr(Q(1) = i)
Daniel@0 7 % transmat(i,j) = Pr(Q(t+1)=j | Q(t)=i)
Daniel@0 8 % obslik(i,t) = Pr(y(t) | Q(t)=i)
Daniel@0 9 %
Daniel@0 10 % Outputs:
Daniel@0 11 % path(t) = q(t), where q1 ... qT is the argmax of the above expression.
Daniel@0 12
Daniel@0 13
Daniel@0 14 % delta(j,t) = prob. of the best sequence of length t-1 and then going to state j, and O(1:t)
Daniel@0 15 % psi(j,t) = the best predecessor state, given that we ended up in state j at t
Daniel@0 16
Daniel@0 17 scaled = 1;
Daniel@0 18
Daniel@0 19 T = size(obslik, 2);
Daniel@0 20 prior = prior(:);
Daniel@0 21 Q = length(prior);
Daniel@0 22
Daniel@0 23 delta = zeros(Q,T);
Daniel@0 24 psi = zeros(Q,T);
Daniel@0 25 path = zeros(1,T);
Daniel@0 26 scale = ones(1,T);
Daniel@0 27
Daniel@0 28
Daniel@0 29 t=1;
Daniel@0 30 delta(:,t) = prior .* obslik(:,t);
Daniel@0 31 if scaled
Daniel@0 32 [delta(:,t), n] = normalise(delta(:,t));
Daniel@0 33 scale(t) = 1/n;
Daniel@0 34 end
Daniel@0 35 psi(:,t) = 0; % arbitrary value, since there is no predecessor to t=1
Daniel@0 36 for t=2:T
Daniel@0 37 for j=1:Q
Daniel@0 38 [delta(j,t), psi(j,t)] = max(delta(:,t-1) .* transmat(:,j));
Daniel@0 39 delta(j,t) = delta(j,t) * obslik(j,t);
Daniel@0 40 end
Daniel@0 41 if scaled
Daniel@0 42 [delta(:,t), n] = normalise(delta(:,t));
Daniel@0 43 scale(t) = 1/n;
Daniel@0 44 end
Daniel@0 45 end
Daniel@0 46 [p, path(T)] = max(delta(:,T));
Daniel@0 47 for t=T-1:-1:1
Daniel@0 48 path(t) = psi(path(t+1),t+1);
Daniel@0 49 end
Daniel@0 50
Daniel@0 51 % If scaled==0, p = prob_path(best_path)
Daniel@0 52 % If scaled==1, p = Pr(replace sum with max and proceed as in the scaled forwards algo)
Daniel@0 53 % Both are different from p(data) as computed using the sum-product (forwards) algorithm
Daniel@0 54
Daniel@0 55 if 0
Daniel@0 56 if scaled
Daniel@0 57 loglik = -sum(log(scale));
Daniel@0 58 %loglik = prob_path(prior, transmat, obslik, path);
Daniel@0 59 else
Daniel@0 60 loglik = log(p);
Daniel@0 61 end
Daniel@0 62 end