维特比的Python实现

时间:2018-06-08 15:15:23

标签: python algorithm hmmlearn

对于Python项目,我需要实现Viterbi算法。 无论我输入哪个序列,它都返回0(=第一个状态)的列表,我无法理解为什么。 也许某人有使用此算法的经验

class HMM_model:

    def __init__(self, transition_matrix, emission_matrix, initial_state, obs_names, hidden_names):
        """ transition_matrix is of shape : len(hidden_names) * len(hidden_names)
            emission_matrix is of shape: len(hidden_names) * len(obs_names)
            initial_state is a vector of size len(hidden_names)

         """
        self.transition_matrix = transition_matrix
        self.emission_matrix = emission_matrix
        self.initial_state = initial_state
        self.obs_names = obs_names
        self.hidden_names = hidden_names


    def viterbi(self, observations):
        # initialize
        len_seq = len(observations)
        n_diff_states = len(self.hidden_names)
        prior = self.initial_state
        viterbi = np.zeros((len_seq, n_diff_states))
        backpointer  = np.zeros((len_seq, n_diff_states))
        best_path = np.empty(len_seq, 'B')

        # B. appoint initial values for viterbi
        viterbi[0,:] = prior * self.emission_matrix[:, observations[0]]
        backpointer[0,:] = 0

        for i in range(1,len_seq):
            viterbi[i, :] = np.max(viterbi[i-1, :, np.newaxis] * self.transition_matrix * self.emission_matrix[:, observations[i-1]], axis=0)
            backpointer[i,:] = np.argmax(viterbi[i-1, :, np.newaxis] * self.transition_matrix , axis = 0)


        best_path[-1] = np.argmax(viterbi[len_seq -1 ,:])
        for i in reversed(range(0, len_seq -1)):
            best_path[i-1] = backpointer[i, best_path[i]]
        return best_path

0 个答案:

没有答案