-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
81 lines (66 loc) · 2.29 KB
/
main.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Press the green button in the gutter to run the script.
def alpha(a, b, pi, sequence):
alpha = list()
curr = []
for i in range(0, len(a[0])):
var = float(pi[i] * b[i][sequence[0] - 1])
curr.append(var)
alpha.append(curr)
for x in range(1, len(sequence)):
curr = []
for i in range(0, len(a[0])):
var = 0
for j in range(0, len(a[0])):
var += float(a[j][i] * alpha[x - 1][j])
curr.append(var * b[i][sequence[x] - 1])
alpha.append(curr)
for x in range(0, len(alpha)):
print(f" alpha_t({x + 1}) |", end="")
print("\n", "______________ " * len(alpha[0]))
for x in alpha:
for y in x:
print(str(round(y, 6)).center(13), end="|")
print("\n", "______________ " * len(alpha[0]))
return alpha
def delta(a, b, pi, sequence):
delta = list()
curr = []
for i in range(0, len(a[0])):
var = float(pi[i] * b[i][sequence[0] - 1])
curr.append(var)
delta.append(curr)
for x in range(1, len(sequence)):
curr = []
for i in range(0, len(a[0])):
var = -1.0
for j in range(0, len(a[0])):
var = max(var, float(a[j][i] * delta[x - 1][j]))
curr.append(var * b[i][sequence[x] - 1])
delta.append(curr)
for x in range(0, len(delta[0])):
print(f" delta_t({x + 1}) |", end="")
print("\n", "______________ " * len(delta[0]))
for x in delta:
for y in x:
print(str(round(y, 6)).center(18), end="|")
print("\n", "______________ " * len(delta[0]))
return delta
if __name__ == '__main__':
# Transition properties
# a[i][j] = probability of traveling to state j from state i
a = [[0.3, 0.3, 0.4],
[0.2, 0.7, 0.1],
[0.2, 0.5, 0.3]]
# Emission probabilities
# b[i][x] = Probability of emitting output x at state i
b = [[0.1, 0.0, 0.9],
[0.3, 0.4, 0.3],
[0.7, 0.2, 0.1]]
# pi[i] = Probability of starting at state i
pi = [0.2, 0.5, 0.3]
# Observed output sequence
sequence = [1, 2, 3, 1, 1, 4]
# Prints alpha table and returns matrix
alpha_table = alpha(a, b, pi, sequence)
# Prints delta table and returns matrix
delta_table = delta(a, b, pi, sequence)