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