-
Notifications
You must be signed in to change notification settings - Fork 2
/
Forward.java
68 lines (55 loc) · 1.83 KB
/
Forward.java
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Implementation of Forward Algorithm which computes the likelihood of given input observation.
import static java.lang.System.*;
import java.util.Scanner;
public class Forward
{
@param obs ->Given observation for which likelihood has to be calculated.
@param states ->The various states HMM goes through.
@param start_prob ->The start probability of each state.
@param trans_prob ->The transition probability from state to state.
@param emiss_prob ->The emission probability assosciated with each observation.
@param prob ->The likelihood probability of the input observation sequence.
public static double compute(int obs[], int states[], double start_prob[], double trans_prob[][], double emiss_prob[][]) throws ArrayIndexOutOfBoundsException
{
double forward[][] = new double[obs.length][states.length];
out.println("The observation sequence - ");
for(int i=0; i<obs.length; i++)
{
out.print(obs[i]+" ");
}
out.println();
// Initializing the Forward Matrix
for(int state : states)
{
forward[0][state] = start_prob[state] * emiss_prob[state][obs[0]-1];
}
for(int i=1; i<obs.length; i++)
{
for(int state1 : states)
{
forward[i][state1] = 0;
for(int state2 : states)
{
forward[i][state1] += forward[i - 1][state2] * trans_prob[state2][state1];
// Forward Algorithm adds up every probability calculated, takes to the maximum.
}
forward[i][state1] *= emiss_prob[state1][obs[i] - 1];
}
}
// To check the status of Forward Matrix.
for(int i=0; i<obs.length; i++)
{
for(int j=0; j<states.length; j++)
{
out.println(forward[i][j]+"");
}
//out.println();
}
// Calculation of final likelihood probability.
double prob = 0;
for(int state: states)
{
prob += forward[obs.length - 1][state];
}
return prob;
}