-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhidden.py
65 lines (50 loc) · 2.13 KB
/
hidden.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
class HMM:
"""
Represents a basic Hidden Markov Model.
Parameters:
- states: tuple of states
- observations: tuple of observations
- state_transitions: dictionary of ((state_i, state_k), probability) pairs
- observ_transitions: dictionary of ((state_i, observation_k), probability) pairs
- p_initial: initial probabilities of states; dictionary of (state_i, probability_i) pairs
This class can be initialised either by a set of parameters,
or by an observation sequence, in which case a model that is trained with this sequence is generated.
"""
def __init__(self, *args):
if len(args) == 1: self.from_sequence(*args)
elif len(args) == 5: self.from_states(*args)
def from_states(self, states, observations, state_transitions, observ_transitions, p_initial):
self.states = states
self.observations = observations
self.state_transitions = state_transitions
self.observ_transitions = observ_transitions
self.p_initial = p_initial
def from_sequence(self, osequence):
self.train(osequence)
"""
Determines the probability that with the given HMM,
the hidden state at the end of the given observation sequence is exactly state.
"""
def filter (self, osequence, state):
pass
"""
Determines the most likely sequence of hidden states,
given the observations in osequence.
"""
def decode(self, osequence):
pass
"""
Determines the probability of the observation sequence osequence,
given the model.
"""
def evaluate(self, osequence):
alpha = [p_initial[i] * self.observ_transitions[(i, osequence[1])] for i in range(self.states.length())]
for t in range(osequence.len()):
alpha_ = [(sum(alpha[i] * state_transitions[(i, k)] for i in range (self.states.length())) * observ_transitions[(k, osequence[t])]) for k in range(self.states.length())]
alpha = alpha
return sum(alpha)
"""
Trains the current HMM with a given sequence of observations.
"""
def train(self, osequence):
pass