Python Implementation of Viterbi Algorithm

前端 未结 6 1579
别跟我提以往
别跟我提以往 2020-12-12 20:43

I\'m doing a Python project in which I\'d like to use the Viterbi Algorithm. Does anyone know of a complete Python implementation of the Viterbi algorithm? The correctness

6条回答
  •  孤城傲影
    2020-12-12 21:27

    I found the following code in the example repository of Artificial Intelligence: A Modern Approach. Is something like this what you're looking for?

    def viterbi_segment(text, P):
        """Find the best segmentation of the string of characters, given the
        UnigramTextModel P."""
        # best[i] = best probability for text[0:i]
        # words[i] = best word ending at position i
        n = len(text)
        words = [''] + list(text)
        best = [1.0] + [0.0] * n
        ## Fill in the vectors best, words via dynamic programming
        for i in range(n+1):
            for j in range(0, i):
                w = text[j:i]
                if P[w] * best[i - len(w)] >= best[i]:
                    best[i] = P[w] * best[i - len(w)]
                    words[i] = w
        ## Now recover the sequence of best words
        sequence = []; i = len(words)-1
        while i > 0:
            sequence[0:0] = [words[i]]
            i = i - len(words[i])
        ## Return sequence of best words and overall probability
        return sequence, best[-1]
    

提交回复
热议问题