This repository was archived by the owner on Sep 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHMM.py
More file actions
170 lines (136 loc) · 5.54 KB
/
HMM.py
File metadata and controls
170 lines (136 loc) · 5.54 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import numpy as np
"""
An implementation of Hidden Morkov Model for evaluation problem and decoding problem
@author: Sotheanith Sok, Jesse Blacklock
@class: CECS 550
@instructor: Arjang Fahim
@date: 10/11/2019
"""
class HMM (object):
"""Hidden Morkov Model
"""
def __init__(self, input):
"""Constructor
Arguments:
input {string} -- a vector of observable states
"""
super().__init__()
# Convert input strings to integer values
input[input == 'yes'] = 1
input[input == 'no'] = 2
self.input = input.astype(np.int)
# Perform operations
self.loadData()
self.createTransitionProbabilities()
self.createEmissionProbabilities()
self.createAlphas()
self.runViterbi()
self.printResult()
def loadData(self):
"""Load data from file
"""
# Load from files
self.data = np.genfromtxt(
'./prompts/Project2Data.txt', delimiter=',', dtype='unicode')
# Convert string values to integer values
self.data[self.data == 'sunny'] = 1
self.data[self.data == 'rainy'] = 2
self.data[self.data == 'foggy'] = 3
self.data[self.data == 'yes'] = 1
self.data[self.data == 'no'] = 2
self.data = self.data.astype(np.int)
def createTransitionProbabilities(self):
"""Create transition probabilities from data
"""
# Count how many unique hidden states in data
hiddenStates = np.unique(self.data[:, 0]).size
# Create transition matrix including hidden state 0
self.a = np.zeros((hiddenStates+1, hiddenStates+1))
# Counting hidden states transition
initial = self.data[0, 0]
target = -1
for x in self.data[1:, 0]:
target = x
self.a[initial, target] = self.a[initial, target]+1
initial = x
# Average transitions by the number of transitions coming out of a hidden states
self.a = np.transpose(np.transpose(self.a) / np.sum(self.a, axis=1))
# Replace nan with 0
self.a = np.nan_to_num(self.a)
# Ensure that transition from hidden state 0 to hidden state 0 is one
self.a[0, 0] = 1
def createEmissionProbabilities(self):
"""Create emission matrix from data
"""
# Get the number of hidden states
hiddenStates = np.unique(self.data[:, 0]).size
# Get the number of observable states
observableStates = np.unique(self.data[:, 1]).size
# Initialize emmision matrix with hidden states 0 and emission states 0
self.b = np.zeros((hiddenStates+1, observableStates+1))
# Start couting
for x in self.data:
self.b[x[0], x[1]] = self.b[x[0], x[1]]+1
# Average emissions by the number of transitions coming out of a hidden states
self.b = np.transpose(np.transpose(self.b) / np.sum(self.b, axis=1))
# Replace nan with 0
self.b = np.nan_to_num(self.b)
# Ensure that transition from hidden state 0 to observable state 0 is one
self.b[0, 0] = 1
def createAlphas(self):
"""Generate alphas using forward algorithm
"""
# Get the length of time and number of hidden states
time = self.input.size
hiddenStates = np.unique(self.data[:, 0]).size
# Intialize the alpha matrix
self.alpha = np.zeros((hiddenStates+1, time+1))
# Populate the time 0 by the intial states (Assume starting at "sunny")
self.alpha[:, 0] = np.array([0, 1, 0, 0])
# Start the calculation
for t in range(1, time+1):
for w in range(hiddenStates+1):
s = np.sum(self.alpha[:, t-1] * self.a[:, w]
) * self.b[w, self.input[t-1]]
self.alpha[w, t] = s
def runViterbi(self):
"""Generate scores using Viterbi algorithm
"""
# Get the length of time and the number of hidden states
time = self.input.size
hiddenStates = np.unique(self.data[:, 0]).size
# Initialize the scores matrix
self.score = np.zeros((hiddenStates+1, time+1))
# Populate scores at time 0
self.score[:, 0] = np.array([0, 1, 0, 0])
# Begin the Viterbi algorithm
for t in range(1, time+1):
for w in range(hiddenStates+1):
s = np.max(self.score[:, t-1] * self.a[:, w]
) * self.b[w, self.input[t-1]]
self.score[w, t] = s
def printResult(self):
"""Print results
"""
# Transition probabilities
print("Transition Probabilities: ")
print(self.a)
# Emission probabilities
print("Emission Probabilities: ")
print(self.b)
# Overall probabilites of generating the sequence of observable states
inp = self.input.astype(np.unicode)
inp[inp == '1'] = "yes"
inp[inp == '2'] = "no"
print("For input: ", inp)
print("Probability of such evidents generated from this HMM: ",
np.sum(self.alpha[:, self.input.size]))
# Most likely sequence of hidden states to generate the given observable states
seq = np.argmax(self.score, axis=0)
seq = seq.astype(np.unicode)
seq[seq == "1"] = "sunny"
seq[seq == "2"] = "rainy"
seq[seq == "3"] = "foggy"
print(
"Most likely sequence of hidden states to generate the above evidents: \n", seq)
HMM(np.array(['no', 'no', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'yes']))