-
Notifications
You must be signed in to change notification settings - Fork 2
/
forward_viterbi.m
53 lines (51 loc) · 1.6 KB
/
forward_viterbi.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function [total,argmax,valmax] = forward_viterbi(obs,states,start_p,trans_p,emit_p)
%Translated from Python code available at:
% http://en.wikipedia.org/wiki/Viterbi_algorithm
class(obs)
class(states)
class(start_p)
class(trans_p)
size(trans_p)
class(emit_p)
size(emit_p)
T = {};
for state = 1:length(states)
%% prob. V. path V. prob.
T{state} = {start_p(state),states(state),start_p(state)};
end
for output = 1:length(obs)
U = {};
for next_state = 1:length(states)
total = 0;
argmax = [];
valmax = 0;
for source_state = 1:length(states)
Ti = T{source_state};
prob = Ti{1}; v_path = Ti{2}; v_prob = Ti{3};
p = emit_p(source_state,obs(output)) * trans_p(source_state,next_state);
prob = prob*p;
v_prob = v_prob*p;
total = total + prob;
if v_prob > valmax
argmax = [v_path, states(next_state)];
valmax = v_prob;
end
end
U{next_state} = {total,argmax,valmax};
end
T = U;
end
%% apply sum/max to the final states:
total = 0;
argmax = [];
valmax = 0;
for state = 1:length(states)
Ti = T{state};
prob = Ti{1}; v_path = Ti{2}; v_prob = Ti{3};
total = total + prob;
if v_prob > valmax
argmax = v_path;
valmax = v_prob;
end
end
end