matthiasm@43: function path = viterbi_path(prior, transmat, obslik) matthiasm@43: % VITERBI Find the most-probable (Viterbi) path through the HMM state trellis. matthiasm@43: % path = viterbi(prior, transmat, obslik) matthiasm@43: % matthiasm@43: % Inputs: matthiasm@43: % prior(i) = Pr(Q(1) = i) matthiasm@43: % transmat(i,j) = Pr(Q(t+1)=j | Q(t)=i) matthiasm@43: % obslik(i,t) = Pr(y(t) | Q(t)=i) matthiasm@43: % matthiasm@43: % Outputs: matthiasm@43: % path(t) = q(t), where q1 ... qT is the argmax of the above expression. matthiasm@43: matthiasm@43: matthiasm@43: % delta(j,t) = prob. of the best sequence of length t-1 and then going to state j, and O(1:t) matthiasm@43: % psi(j,t) = the best predecessor state, given that we ended up in state j at t matthiasm@43: matthiasm@43: scaled = 1; matthiasm@43: matthiasm@43: T = size(obslik, 2); matthiasm@43: prior = prior(:); matthiasm@43: Q = length(prior); matthiasm@43: matthiasm@43: delta = zeros(Q,T); matthiasm@43: psi = zeros(Q,T); matthiasm@43: path = zeros(1,T); matthiasm@43: scale = ones(1,T); matthiasm@43: matthiasm@43: matthiasm@43: t=1; matthiasm@43: delta(:,t) = prior .* obslik(:,t); matthiasm@43: if scaled matthiasm@43: [delta(:,t), n] = normalise(delta(:,t)); matthiasm@43: scale(t) = 1/n; matthiasm@43: end matthiasm@43: psi(:,t) = 0; % arbitrary value, since there is no predecessor to t=1 matthiasm@43: for t=2:T matthiasm@43: for j=1:Q matthiasm@43: [delta(j,t), psi(j,t)] = max(delta(:,t-1) .* transmat(:,j)); matthiasm@43: delta(j,t) = delta(j,t) * obslik(j,t); matthiasm@43: end matthiasm@43: if scaled matthiasm@43: [delta(:,t), n] = normalise(delta(:,t)); matthiasm@43: scale(t) = 1/n; matthiasm@43: end matthiasm@43: end matthiasm@43: [p, path(T)] = max(delta(:,T)); matthiasm@43: for t=T-1:-1:1 matthiasm@43: path(t) = psi(path(t+1),t+1); matthiasm@43: end matthiasm@43: matthiasm@43: % If scaled==0, p = prob_path(best_path) matthiasm@43: % If scaled==1, p = Pr(replace sum with max and proceed as in the scaled forwards algo) matthiasm@43: % Both are different from p(data) as computed using the sum-product (forwards) algorithm matthiasm@43: matthiasm@43: if 0 matthiasm@43: if scaled matthiasm@43: loglik = -sum(log(scale)); matthiasm@43: %loglik = prob_path(prior, transmat, obslik, path); matthiasm@43: else matthiasm@43: loglik = log(p); matthiasm@43: end matthiasm@43: end